blob: f065802467af51b0be28cbf7709739a704351fa3 [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: {
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003137 // Visit non-init 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 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003143 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003144
Guy Benyei11169dd2012-12-18 14:30:41 +00003145 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3146 C->getLocation(),
3147 TU)))
3148 return true;
3149 }
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003150 // Visit init captures
3151 for (auto InitExpr : E->capture_inits()) {
3152 if (Visit(InitExpr))
3153 return true;
3154 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003155
Haojian Wuef87c262018-12-18 15:29:12 +00003156 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00003157 // Visit parameters and return type, if present.
Haojian Wuef87c262018-12-18 15:29:12 +00003158 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3159 if (E->hasExplicitParameters()) {
3160 // Visit parameters.
3161 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3162 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003163 return true;
Haojian Wuef87c262018-12-18 15:29:12 +00003164 }
3165 if (E->hasExplicitResultType()) {
3166 // Visit result type.
3167 if (Visit(Proto.getReturnLoc()))
3168 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003169 }
3170 }
3171 break;
3172 }
3173
3174 case VisitorJob::PostChildrenVisitKind:
3175 if (PostChildrenVisitor(Parent, ClientData))
3176 return true;
3177 break;
3178 }
3179 }
3180 return false;
3181}
3182
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003183bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003184 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003185 if (!WorkListFreeList.empty()) {
3186 WL = WorkListFreeList.back();
3187 WL->clear();
3188 WorkListFreeList.pop_back();
3189 }
3190 else {
3191 WL = new VisitorWorkList();
3192 WorkListCache.push_back(WL);
3193 }
3194 EnqueueWorkList(*WL, S);
3195 bool result = RunVisitorWorkList(*WL);
3196 WorkListFreeList.push_back(WL);
3197 return result;
3198}
3199
3200namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003201typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003202RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3203 const DeclarationNameInfo &NI, SourceRange QLoc,
3204 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003205 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3206 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3207 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3208
3209 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3210
3211 RefNamePieces Pieces;
3212
3213 if (WantQualifier && QLoc.isValid())
3214 Pieces.push_back(QLoc);
3215
3216 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3217 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003218
3219 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3220 Pieces.push_back(*TemplateArgsLoc);
3221
Guy Benyei11169dd2012-12-18 14:30:41 +00003222 if (Kind == DeclarationName::CXXOperatorName) {
3223 Pieces.push_back(SourceLocation::getFromRawEncoding(
3224 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3225 Pieces.push_back(SourceLocation::getFromRawEncoding(
3226 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3227 }
3228
3229 if (WantSinglePiece) {
3230 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3231 Pieces.clear();
3232 Pieces.push_back(R);
3233 }
3234
3235 return Pieces;
3236}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003237}
Guy Benyei11169dd2012-12-18 14:30:41 +00003238
3239//===----------------------------------------------------------------------===//
3240// Misc. API hooks.
3241//===----------------------------------------------------------------------===//
3242
Chad Rosier05c71aa2013-03-27 18:28:23 +00003243static void fatal_error_handler(void *user_data, const std::string& reason,
3244 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003245 // Write the result out to stderr avoiding errs() because raw_ostreams can
3246 // call report_fatal_error.
3247 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3248 ::abort();
3249}
3250
Chandler Carruth66660742014-06-27 16:37:27 +00003251namespace {
3252struct RegisterFatalErrorHandler {
3253 RegisterFatalErrorHandler() {
3254 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3255 }
3256};
3257}
3258
3259static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3260
Guy Benyei11169dd2012-12-18 14:30:41 +00003261CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3262 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003263 // We use crash recovery to make some of our APIs more reliable, implicitly
3264 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003265 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3266 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003267
Chandler Carruth66660742014-06-27 16:37:27 +00003268 // Look through the managed static to trigger construction of the managed
3269 // static which registers our fatal error handler. This ensures it is only
3270 // registered once.
3271 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003272
Adrian Prantlbc068582015-07-08 01:00:30 +00003273 // Initialize targets for clang module support.
3274 llvm::InitializeAllTargets();
3275 llvm::InitializeAllTargetMCs();
3276 llvm::InitializeAllAsmPrinters();
3277 llvm::InitializeAllAsmParsers();
3278
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003279 CIndexer *CIdxr = new CIndexer();
3280
Guy Benyei11169dd2012-12-18 14:30:41 +00003281 if (excludeDeclarationsFromPCH)
3282 CIdxr->setOnlyLocalDecls();
3283 if (displayDiagnostics)
3284 CIdxr->setDisplayDiagnostics();
3285
3286 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3287 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3288 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3289 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3290 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3291 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3292
3293 return CIdxr;
3294}
3295
3296void clang_disposeIndex(CXIndex CIdx) {
3297 if (CIdx)
3298 delete static_cast<CIndexer *>(CIdx);
3299}
3300
3301void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3302 if (CIdx)
3303 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3304}
3305
3306unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3307 if (CIdx)
3308 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3309 return 0;
3310}
3311
Alex Lorenz08615792017-12-04 21:56:36 +00003312void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3313 const char *Path) {
3314 if (CIdx)
3315 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3316}
3317
Guy Benyei11169dd2012-12-18 14:30:41 +00003318void clang_toggleCrashRecovery(unsigned isEnabled) {
3319 if (isEnabled)
3320 llvm::CrashRecoveryContext::Enable();
3321 else
3322 llvm::CrashRecoveryContext::Disable();
3323}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003324
Guy Benyei11169dd2012-12-18 14:30:41 +00003325CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3326 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003327 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003328 enum CXErrorCode Result =
3329 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003330 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003331 assert((TU && Result == CXError_Success) ||
3332 (!TU && Result != CXError_Success));
3333 return TU;
3334}
3335
3336enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3337 const char *ast_filename,
3338 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003339 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003340 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003341
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003342 if (!CIdx || !ast_filename || !out_TU)
3343 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003344
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003345 LOG_FUNC_SECTION {
3346 *Log << ast_filename;
3347 }
3348
Guy Benyei11169dd2012-12-18 14:30:41 +00003349 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3350 FileSystemOptions FileSystemOpts;
3351
Justin Bognerd512c1e2014-10-15 00:33:06 +00003352 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3353 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003354 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003355 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3356 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003357 FileSystemOpts, /*UseDebugInfo=*/false,
3358 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003359 /*CaptureDiagnostics=*/true,
3360 /*AllowPCHWithCompilerErrors=*/true,
3361 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003362 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003363 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003364}
3365
3366unsigned clang_defaultEditingTranslationUnitOptions() {
3367 return CXTranslationUnit_PrecompiledPreamble |
3368 CXTranslationUnit_CacheCompletionResults;
3369}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003370
Guy Benyei11169dd2012-12-18 14:30:41 +00003371CXTranslationUnit
3372clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3373 const char *source_filename,
3374 int num_command_line_args,
3375 const char * const *command_line_args,
3376 unsigned num_unsaved_files,
3377 struct CXUnsavedFile *unsaved_files) {
3378 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3379 return clang_parseTranslationUnit(CIdx, source_filename,
3380 command_line_args, num_command_line_args,
3381 unsaved_files, num_unsaved_files,
3382 Options);
3383}
3384
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003385static CXErrorCode
3386clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3387 const char *const *command_line_args,
3388 int num_command_line_args,
3389 ArrayRef<CXUnsavedFile> unsaved_files,
3390 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003391 // Set up the initial return values.
3392 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003393 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003394
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003395 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003396 if (!CIdx || !out_TU)
3397 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003398
Guy Benyei11169dd2012-12-18 14:30:41 +00003399 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3400
3401 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3402 setThreadBackgroundPriority();
3403
3404 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003405 bool CreatePreambleOnFirstParse =
3406 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003407 // FIXME: Add a flag for modules.
3408 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003409 = (options & (CXTranslationUnit_Incomplete |
3410 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003411 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003412 = options & CXTranslationUnit_CacheCompletionResults;
3413 bool IncludeBriefCommentsInCodeCompletion
3414 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003415 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3416 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003417 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3418 if (options & CXTranslationUnit_SkipFunctionBodies) {
3419 SkipFunctionBodies =
3420 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3421 ? SkipFunctionBodiesScope::Preamble
3422 : SkipFunctionBodiesScope::PreambleAndMainFile;
3423 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003424
3425 // Configure the diagnostics.
3426 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003427 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003428
Manuel Klimek016c0242016-03-01 10:56:19 +00003429 if (options & CXTranslationUnit_KeepGoing)
Ivan Donchevskii878271b2019-03-07 10:13:50 +00003430 Diags->setFatalsAsError(true);
Manuel Klimek016c0242016-03-01 10:56:19 +00003431
Guy Benyei11169dd2012-12-18 14:30:41 +00003432 // Recover resources if we crash before exiting this function.
3433 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3434 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003435 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003436
Ahmed Charlesb8984322014-03-07 20:03:18 +00003437 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3438 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003439
3440 // Recover resources if we crash before exiting this function.
3441 llvm::CrashRecoveryContextCleanupRegistrar<
3442 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3443
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003444 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003445 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003446 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003447 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003448 }
3449
Ahmed Charlesb8984322014-03-07 20:03:18 +00003450 std::unique_ptr<std::vector<const char *>> Args(
3451 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003452
3453 // Recover resources if we crash before exiting this method.
3454 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3455 ArgsCleanup(Args.get());
3456
3457 // Since the Clang C library is primarily used by batch tools dealing with
3458 // (often very broken) source code, where spell-checking can have a
3459 // significant negative impact on performance (particularly when
3460 // precompiled headers are involved), we disable it by default.
3461 // Only do this if we haven't found a spell-checking-related argument.
3462 bool FoundSpellCheckingArgument = false;
3463 for (int I = 0; I != num_command_line_args; ++I) {
3464 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3465 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3466 FoundSpellCheckingArgument = true;
3467 break;
3468 }
3469 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003470 Args->insert(Args->end(), command_line_args,
3471 command_line_args + num_command_line_args);
3472
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003473 if (!FoundSpellCheckingArgument)
3474 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3475
Guy Benyei11169dd2012-12-18 14:30:41 +00003476 // The 'source_filename' argument is optional. If the caller does not
3477 // specify it then it is assumed that the source file is specified
3478 // in the actual argument list.
3479 // Put the source file after command_line_args otherwise if '-x' flag is
3480 // present it will be unused.
3481 if (source_filename)
3482 Args->push_back(source_filename);
3483
3484 // Do we need the detailed preprocessing record?
3485 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3486 Args->push_back("-Xclang");
3487 Args->push_back("-detailed-preprocessing-record");
3488 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003489
3490 // Suppress any editor placeholder diagnostics.
3491 Args->push_back("-fallow-editor-placeholders");
3492
Guy Benyei11169dd2012-12-18 14:30:41 +00003493 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003494 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003495 // Unless the user specified that they want the preamble on the first parse
3496 // set it up to be created on the first reparse. This makes the first parse
3497 // faster, trading for a slower (first) reparse.
3498 unsigned PrecompilePreambleAfterNParses =
3499 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003500
Alex Lorenz08615792017-12-04 21:56:36 +00003501 LibclangInvocationReporter InvocationReporter(
3502 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003503 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3504 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003505 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003506 Args->data(), Args->data() + Args->size(),
3507 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003508 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3509 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003510 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3511 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003512 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003513 /*UserFilesAreVolatile=*/true, ForSerialization,
3514 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3515 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003516
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003517 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003518 if (!Unit && !ErrUnit)
3519 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003520
Guy Benyei11169dd2012-12-18 14:30:41 +00003521 if (NumErrors != Diags->getClient()->getNumErrors()) {
3522 // Make sure to check that 'Unit' is non-NULL.
3523 if (CXXIdx->getDisplayDiagnostics())
3524 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3525 }
3526
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003527 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3528 return CXError_ASTReadError;
3529
David Blaikieea4395e2017-01-06 19:49:01 +00003530 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003531 if (CXTranslationUnitImpl *TU = *out_TU) {
3532 TU->ParsingOptions = options;
3533 TU->Arguments.reserve(Args->size());
3534 for (const char *Arg : *Args)
3535 TU->Arguments.push_back(Arg);
3536 return CXError_Success;
3537 }
3538 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003539}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003540
3541CXTranslationUnit
3542clang_parseTranslationUnit(CXIndex CIdx,
3543 const char *source_filename,
3544 const char *const *command_line_args,
3545 int num_command_line_args,
3546 struct CXUnsavedFile *unsaved_files,
3547 unsigned num_unsaved_files,
3548 unsigned options) {
3549 CXTranslationUnit TU;
3550 enum CXErrorCode Result = clang_parseTranslationUnit2(
3551 CIdx, source_filename, command_line_args, num_command_line_args,
3552 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003553 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003554 assert((TU && Result == CXError_Success) ||
3555 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003556 return TU;
3557}
3558
3559enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003560 CXIndex CIdx, const char *source_filename,
3561 const char *const *command_line_args, int num_command_line_args,
3562 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3563 unsigned options, CXTranslationUnit *out_TU) {
3564 SmallVector<const char *, 4> Args;
3565 Args.push_back("clang");
3566 Args.append(command_line_args, command_line_args + num_command_line_args);
3567 return clang_parseTranslationUnit2FullArgv(
3568 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3569 num_unsaved_files, options, out_TU);
3570}
3571
3572enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3573 CXIndex CIdx, const char *source_filename,
3574 const char *const *command_line_args, int num_command_line_args,
3575 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3576 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003577 LOG_FUNC_SECTION {
3578 *Log << source_filename << ": ";
3579 for (int i = 0; i != num_command_line_args; ++i)
3580 *Log << command_line_args[i] << " ";
3581 }
3582
Alp Toker9d85b182014-07-07 01:23:14 +00003583 if (num_unsaved_files && !unsaved_files)
3584 return CXError_InvalidArguments;
3585
Alp Toker5c532982014-07-07 22:42:03 +00003586 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003587 auto ParseTranslationUnitImpl = [=, &result] {
3588 result = clang_parseTranslationUnit_Impl(
3589 CIdx, source_filename, command_line_args, num_command_line_args,
3590 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3591 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003592
Guy Benyei11169dd2012-12-18 14:30:41 +00003593 llvm::CrashRecoveryContext CRC;
3594
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003595 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003596 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3597 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3598 fprintf(stderr, " 'command_line_args' : [");
3599 for (int i = 0; i != num_command_line_args; ++i) {
3600 if (i)
3601 fprintf(stderr, ", ");
3602 fprintf(stderr, "'%s'", command_line_args[i]);
3603 }
3604 fprintf(stderr, "],\n");
3605 fprintf(stderr, " 'unsaved_files' : [");
3606 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3607 if (i)
3608 fprintf(stderr, ", ");
3609 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3610 unsaved_files[i].Length);
3611 }
3612 fprintf(stderr, "],\n");
3613 fprintf(stderr, " 'options' : %d,\n", options);
3614 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003615
3616 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003617 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003618 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003619 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003620 }
Alp Toker5c532982014-07-07 22:42:03 +00003621
3622 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003623}
3624
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003625CXString clang_Type_getObjCEncoding(CXType CT) {
3626 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3627 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3628 std::string encoding;
3629 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3630 encoding);
3631
3632 return cxstring::createDup(encoding);
3633}
3634
3635static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3636 if (C.kind == CXCursor_MacroDefinition) {
3637 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3638 return MDR->getName();
3639 } else if (C.kind == CXCursor_MacroExpansion) {
3640 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3641 return ME.getName();
3642 }
3643 return nullptr;
3644}
3645
3646unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3647 const IdentifierInfo *II = getMacroIdentifier(C);
3648 if (!II) {
3649 return false;
3650 }
3651 ASTUnit *ASTU = getCursorASTUnit(C);
3652 Preprocessor &PP = ASTU->getPreprocessor();
3653 if (const MacroInfo *MI = PP.getMacroInfo(II))
3654 return MI->isFunctionLike();
3655 return false;
3656}
3657
3658unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3659 const IdentifierInfo *II = getMacroIdentifier(C);
3660 if (!II) {
3661 return false;
3662 }
3663 ASTUnit *ASTU = getCursorASTUnit(C);
3664 Preprocessor &PP = ASTU->getPreprocessor();
3665 if (const MacroInfo *MI = PP.getMacroInfo(II))
3666 return MI->isBuiltinMacro();
3667 return false;
3668}
3669
3670unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3671 const Decl *D = getCursorDecl(C);
3672 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3673 if (!FD) {
3674 return false;
3675 }
3676 return FD->isInlined();
3677}
3678
3679static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3680 if (callExpr->getNumArgs() != 1) {
3681 return nullptr;
3682 }
3683
3684 StringLiteral *S = nullptr;
3685 auto *arg = callExpr->getArg(0);
3686 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3687 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3688 auto *subExpr = I->getSubExprAsWritten();
3689
3690 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3691 return nullptr;
3692 }
3693
3694 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3695 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3696 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3697 } else {
3698 return nullptr;
3699 }
3700 return S;
3701}
3702
David Blaikie59272572016-04-13 18:23:33 +00003703struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003704 CXEvalResultKind EvalType;
3705 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003706 unsigned long long unsignedVal;
3707 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003708 double floatVal;
3709 char *stringVal;
3710 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003711 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003712 ~ExprEvalResult() {
3713 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3714 EvalType != CXEval_Int) {
Alex Lorenza19cb2e2019-01-08 23:28:37 +00003715 delete[] EvalData.stringVal;
David Blaikie59272572016-04-13 18:23:33 +00003716 }
3717 }
3718};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003719
3720void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003721 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003722}
3723
3724CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3725 if (!E) {
3726 return CXEval_UnExposed;
3727 }
3728 return ((ExprEvalResult *)E)->EvalType;
3729}
3730
3731int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003732 return clang_EvalResult_getAsLongLong(E);
3733}
3734
3735long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003736 if (!E) {
3737 return 0;
3738 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003739 ExprEvalResult *Result = (ExprEvalResult*)E;
3740 if (Result->IsUnsignedInt)
3741 return Result->EvalData.unsignedVal;
3742 return Result->EvalData.intVal;
3743}
3744
3745unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3746 return ((ExprEvalResult *)E)->IsUnsignedInt;
3747}
3748
3749unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3750 if (!E) {
3751 return 0;
3752 }
3753
3754 ExprEvalResult *Result = (ExprEvalResult*)E;
3755 if (Result->IsUnsignedInt)
3756 return Result->EvalData.unsignedVal;
3757 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003758}
3759
3760double clang_EvalResult_getAsDouble(CXEvalResult E) {
3761 if (!E) {
3762 return 0;
3763 }
3764 return ((ExprEvalResult *)E)->EvalData.floatVal;
3765}
3766
3767const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3768 if (!E) {
3769 return nullptr;
3770 }
3771 return ((ExprEvalResult *)E)->EvalData.stringVal;
3772}
3773
3774static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3775 Expr::EvalResult ER;
3776 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003777 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003778 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003779
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003780 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003781 if (!expr->EvaluateAsRValue(ER, ctx))
3782 return nullptr;
3783
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003784 QualType rettype;
3785 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003786 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003787 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003788 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003789
David Blaikiebbc00882016-04-13 18:36:19 +00003790 if (ER.Val.isInt()) {
3791 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003792
3793 auto& val = ER.Val.getInt();
3794 if (val.isUnsigned()) {
3795 result->IsUnsignedInt = true;
3796 result->EvalData.unsignedVal = val.getZExtValue();
3797 } else {
3798 result->EvalData.intVal = val.getExtValue();
3799 }
3800
David Blaikiebbc00882016-04-13 18:36:19 +00003801 return result.release();
3802 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003803
David Blaikiebbc00882016-04-13 18:36:19 +00003804 if (ER.Val.isFloat()) {
3805 llvm::SmallVector<char, 100> Buffer;
3806 ER.Val.getFloat().toString(Buffer);
3807 std::string floatStr(Buffer.data(), Buffer.size());
3808 result->EvalType = CXEval_Float;
3809 bool ignored;
3810 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003811 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003812 llvm::APFloat::rmNearestTiesToEven, &ignored);
3813 result->EvalData.floatVal = apFloat.convertToDouble();
3814 return result.release();
3815 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003816
David Blaikiebbc00882016-04-13 18:36:19 +00003817 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3818 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3819 auto *subExpr = I->getSubExprAsWritten();
3820 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3821 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003822 const StringLiteral *StrE = nullptr;
3823 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003824 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003825
3826 if (ObjCExpr) {
3827 StrE = ObjCExpr->getString();
3828 result->EvalType = CXEval_ObjCStrLiteral;
3829 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003830 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003831 result->EvalType = CXEval_StrLiteral;
3832 }
3833
3834 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003835 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003836 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3837 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003838 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003839 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003840 }
3841 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3842 expr->getStmtClass() == Stmt::StringLiteralClass) {
3843 const StringLiteral *StrE = nullptr;
3844 const ObjCStringLiteral *ObjCExpr;
3845 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003846
David Blaikiebbc00882016-04-13 18:36:19 +00003847 if (ObjCExpr) {
3848 StrE = ObjCExpr->getString();
3849 result->EvalType = CXEval_ObjCStrLiteral;
3850 } else {
3851 StrE = cast<StringLiteral>(expr);
3852 result->EvalType = CXEval_StrLiteral;
3853 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003854
David Blaikiebbc00882016-04-13 18:36:19 +00003855 std::string strRef(StrE->getString().str());
3856 result->EvalData.stringVal = new char[strRef.size() + 1];
3857 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3858 result->EvalData.stringVal[strRef.size()] = '\0';
3859 return result.release();
3860 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003861
David Blaikiebbc00882016-04-13 18:36:19 +00003862 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3863 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003864
David Blaikiebbc00882016-04-13 18:36:19 +00003865 rettype = CC->getType();
3866 if (rettype.getAsString() == "CFStringRef" &&
3867 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003868
David Blaikiebbc00882016-04-13 18:36:19 +00003869 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3870 StringLiteral *S = getCFSTR_value(callExpr);
3871 if (S) {
3872 std::string strLiteral(S->getString().str());
3873 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003874
David Blaikiebbc00882016-04-13 18:36:19 +00003875 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3876 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3877 strLiteral.size());
3878 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003879 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003880 }
3881 }
3882
David Blaikiebbc00882016-04-13 18:36:19 +00003883 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3884 callExpr = static_cast<CallExpr *>(expr);
3885 rettype = callExpr->getCallReturnType(ctx);
3886
3887 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3888 return nullptr;
3889
3890 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3891 if (callExpr->getNumArgs() == 1 &&
3892 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3893 return nullptr;
3894 } else if (rettype.getAsString() == "CFStringRef") {
3895
3896 StringLiteral *S = getCFSTR_value(callExpr);
3897 if (S) {
3898 std::string strLiteral(S->getString().str());
3899 result->EvalType = CXEval_CFStr;
3900 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3901 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3902 strLiteral.size());
3903 result->EvalData.stringVal[strLiteral.size()] = '\0';
3904 return result.release();
3905 }
3906 }
3907 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3908 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3909 ValueDecl *V = D->getDecl();
3910 if (V->getKind() == Decl::Function) {
3911 std::string strName = V->getNameAsString();
3912 result->EvalType = CXEval_Other;
3913 result->EvalData.stringVal = new char[strName.size() + 1];
3914 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3915 result->EvalData.stringVal[strName.size()] = '\0';
3916 return result.release();
3917 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003918 }
3919
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003920 return nullptr;
3921}
3922
Alex Lorenz65317e12019-01-08 22:32:51 +00003923static const Expr *evaluateDeclExpr(const Decl *D) {
3924 if (!D)
Evgeniy Stepanov9b871492018-07-10 19:48:53 +00003925 return nullptr;
Alex Lorenz65317e12019-01-08 22:32:51 +00003926 if (auto *Var = dyn_cast<VarDecl>(D))
3927 return Var->getInit();
3928 else if (auto *Field = dyn_cast<FieldDecl>(D))
3929 return Field->getInClassInitializer();
3930 return nullptr;
3931}
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003932
Alex Lorenz65317e12019-01-08 22:32:51 +00003933static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
3934 assert(CS && "invalid compound statement");
3935 for (auto *bodyIterator : CS->body()) {
3936 if (const auto *E = dyn_cast<Expr>(bodyIterator))
3937 return E;
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003938 }
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00003939 return nullptr;
3940}
3941
Alex Lorenz65317e12019-01-08 22:32:51 +00003942CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3943 if (const Expr *E =
3944 clang_getCursorKind(C) == CXCursor_CompoundStmt
3945 ? evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)))
3946 : evaluateDeclExpr(getCursorDecl(C)))
3947 return const_cast<CXEvalResult>(
3948 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
3949 return nullptr;
3950}
3951
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003952unsigned clang_Cursor_hasAttrs(CXCursor C) {
3953 const Decl *D = getCursorDecl(C);
3954 if (!D) {
3955 return 0;
3956 }
3957
3958 if (D->hasAttrs()) {
3959 return 1;
3960 }
3961
3962 return 0;
3963}
Guy Benyei11169dd2012-12-18 14:30:41 +00003964unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3965 return CXSaveTranslationUnit_None;
3966}
3967
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003968static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3969 const char *FileName,
3970 unsigned options) {
3971 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003972 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3973 setThreadBackgroundPriority();
3974
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003975 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3976 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003977}
3978
3979int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3980 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003981 LOG_FUNC_SECTION {
3982 *Log << TU << ' ' << FileName;
3983 }
3984
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003985 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003986 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003987 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003988 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003989
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003990 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003991 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3992 if (!CXXUnit->hasSema())
3993 return CXSaveError_InvalidTU;
3994
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003995 CXSaveError result;
3996 auto SaveTranslationUnitImpl = [=, &result]() {
3997 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3998 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003999
Erik Verbruggen3cc39112017-11-14 09:34:39 +00004000 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004001 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00004002
4003 if (getenv("LIBCLANG_RESOURCE_USAGE"))
4004 PrintLibclangResourceUsage(TU);
4005
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004006 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004007 }
4008
4009 // We have an AST that has invalid nodes due to compiler errors.
4010 // Use a crash recovery thread for protection.
4011
4012 llvm::CrashRecoveryContext CRC;
4013
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004014 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004015 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
4016 fprintf(stderr, " 'filename' : '%s'\n", FileName);
4017 fprintf(stderr, " 'options' : %d,\n", options);
4018 fprintf(stderr, "}\n");
4019
4020 return CXSaveError_Unknown;
4021
4022 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4023 PrintLibclangResourceUsage(TU);
4024 }
4025
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004026 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004027}
4028
4029void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4030 if (CTUnit) {
4031 // If the translation unit has been marked as unsafe to free, just discard
4032 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004033 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4034 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004035 return;
4036
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004037 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004038 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004039 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4040 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004041 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004042 delete CTUnit;
4043 }
4044}
4045
Erik Verbruggen346066b2017-05-30 14:25:54 +00004046unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4047 if (CTUnit) {
4048 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4049
4050 if (Unit && Unit->isUnsafeToFree())
4051 return false;
4052
4053 Unit->ResetForParse();
4054 return true;
4055 }
4056
4057 return false;
4058}
4059
Guy Benyei11169dd2012-12-18 14:30:41 +00004060unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4061 return CXReparse_None;
4062}
4063
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004064static CXErrorCode
4065clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4066 ArrayRef<CXUnsavedFile> unsaved_files,
4067 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004068 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004069 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004070 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004071 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004072 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004073
4074 // Reset the associated diagnostics.
4075 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004076 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004077
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004078 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004079 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4080 setThreadBackgroundPriority();
4081
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004082 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004083 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004084
4085 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4086 new std::vector<ASTUnit::RemappedFile>());
4087
Guy Benyei11169dd2012-12-18 14:30:41 +00004088 // Recover resources if we crash before exiting this function.
4089 llvm::CrashRecoveryContextCleanupRegistrar<
4090 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004091
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004092 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004093 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004094 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004095 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004096 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004097
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004098 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4099 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004100 return CXError_Success;
4101 if (isASTReadError(CXXUnit))
4102 return CXError_ASTReadError;
4103 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004104}
4105
4106int clang_reparseTranslationUnit(CXTranslationUnit TU,
4107 unsigned num_unsaved_files,
4108 struct CXUnsavedFile *unsaved_files,
4109 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004110 LOG_FUNC_SECTION {
4111 *Log << TU;
4112 }
4113
Alp Toker9d85b182014-07-07 01:23:14 +00004114 if (num_unsaved_files && !unsaved_files)
4115 return CXError_InvalidArguments;
4116
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004117 CXErrorCode result;
4118 auto ReparseTranslationUnitImpl = [=, &result]() {
4119 result = clang_reparseTranslationUnit_Impl(
4120 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4121 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004122
Guy Benyei11169dd2012-12-18 14:30:41 +00004123 llvm::CrashRecoveryContext CRC;
4124
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004125 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004126 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004127 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004128 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004129 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4130 PrintLibclangResourceUsage(TU);
4131
Alp Toker5c532982014-07-07 22:42:03 +00004132 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004133}
4134
4135
4136CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004137 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004138 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004139 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004140 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004141
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004142 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004143 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004144}
4145
4146CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004147 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004148 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004149 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004150 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004151
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004152 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004153 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4154}
4155
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004156CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4157 if (isNotUsableTU(CTUnit)) {
4158 LOG_BAD_TU(CTUnit);
4159 return nullptr;
4160 }
4161
4162 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4163 impl->TranslationUnit = CTUnit;
4164 return impl;
4165}
4166
4167CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4168 if (!TargetInfo)
4169 return cxstring::createEmpty();
4170
4171 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4172 assert(!isNotUsableTU(CTUnit) &&
4173 "Unexpected unusable translation unit in TargetInfo");
4174
4175 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4176 std::string Triple =
4177 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4178 return cxstring::createDup(Triple);
4179}
4180
4181int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4182 if (!TargetInfo)
4183 return -1;
4184
4185 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4186 assert(!isNotUsableTU(CTUnit) &&
4187 "Unexpected unusable translation unit in TargetInfo");
4188
4189 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4190 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4191}
4192
4193void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4194 if (!TargetInfo)
4195 return;
4196
4197 delete TargetInfo;
4198}
4199
Guy Benyei11169dd2012-12-18 14:30:41 +00004200//===----------------------------------------------------------------------===//
4201// CXFile Operations.
4202//===----------------------------------------------------------------------===//
4203
Guy Benyei11169dd2012-12-18 14:30:41 +00004204CXString clang_getFileName(CXFile SFile) {
4205 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004206 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004207
4208 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004209 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004210}
4211
4212time_t clang_getFileTime(CXFile SFile) {
4213 if (!SFile)
4214 return 0;
4215
4216 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4217 return FEnt->getModificationTime();
4218}
4219
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004220CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004221 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004222 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004223 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004224 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004225
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004226 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004227
4228 FileManager &FMgr = CXXUnit->getFileManager();
4229 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4230}
4231
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004232const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4233 size_t *size) {
4234 if (isNotUsableTU(TU)) {
4235 LOG_BAD_TU(TU);
4236 return nullptr;
4237 }
4238
4239 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4240 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4241 bool Invalid = true;
Nico Weber04347d82019-04-04 21:06:41 +00004242 const llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004243 if (Invalid) {
4244 if (size)
4245 *size = 0;
4246 return nullptr;
4247 }
4248 if (size)
4249 *size = buf->getBufferSize();
4250 return buf->getBufferStart();
4251}
4252
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004253unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4254 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004255 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004256 LOG_BAD_TU(TU);
4257 return 0;
4258 }
4259
4260 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004261 return 0;
4262
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004263 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004264 FileEntry *FEnt = static_cast<FileEntry *>(file);
4265 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4266 .isFileMultipleIncludeGuarded(FEnt);
4267}
4268
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004269int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4270 if (!file || !outID)
4271 return 1;
4272
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004273 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004274 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4275 outID->data[0] = ID.getDevice();
4276 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004277 outID->data[2] = FEnt->getModificationTime();
4278 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004279}
4280
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004281int clang_File_isEqual(CXFile file1, CXFile file2) {
4282 if (file1 == file2)
4283 return true;
4284
4285 if (!file1 || !file2)
4286 return false;
4287
4288 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4289 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4290 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4291}
4292
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004293CXString clang_File_tryGetRealPathName(CXFile SFile) {
4294 if (!SFile)
4295 return cxstring::createNull();
4296
4297 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4298 return cxstring::createRef(FEnt->tryGetRealPathName());
4299}
4300
Guy Benyei11169dd2012-12-18 14:30:41 +00004301//===----------------------------------------------------------------------===//
4302// CXCursor Operations.
4303//===----------------------------------------------------------------------===//
4304
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004305static const Decl *getDeclFromExpr(const Stmt *E) {
4306 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004307 return getDeclFromExpr(CE->getSubExpr());
4308
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004309 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004310 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004311 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004312 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004313 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004314 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004315 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004316 if (PRE->isExplicitProperty())
4317 return PRE->getExplicitProperty();
4318 // It could be messaging both getter and setter as in:
4319 // ++myobj.myprop;
4320 // in which case prefer to associate the setter since it is less obvious
4321 // from inspecting the source that the setter is going to get called.
4322 if (PRE->isMessagingSetter())
4323 return PRE->getImplicitPropertySetter();
4324 return PRE->getImplicitPropertyGetter();
4325 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004326 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004327 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004328 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004329 if (Expr *Src = OVE->getSourceExpr())
4330 return getDeclFromExpr(Src);
4331
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004332 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004333 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004334 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004335 if (!CE->isElidable())
4336 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004337 if (const CXXInheritedCtorInitExpr *CE =
4338 dyn_cast<CXXInheritedCtorInitExpr>(E))
4339 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004340 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004341 return OME->getMethodDecl();
4342
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004343 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004344 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004345 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004346 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4347 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004348 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004349 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4350 isa<ParmVarDecl>(SizeOfPack->getPack()))
4351 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004352
4353 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004354}
4355
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004356static SourceLocation getLocationFromExpr(const Expr *E) {
4357 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004358 return getLocationFromExpr(CE->getSubExpr());
4359
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004360 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004361 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004362 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004363 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004364 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004365 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004366 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004367 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004368 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004369 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004370 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004371 return PropRef->getLocation();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004372
4373 return E->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00004374}
4375
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004376extern "C" {
4377
Guy Benyei11169dd2012-12-18 14:30:41 +00004378unsigned clang_visitChildren(CXCursor parent,
4379 CXCursorVisitor visitor,
4380 CXClientData client_data) {
4381 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4382 /*VisitPreprocessorLast=*/false);
4383 return CursorVis.VisitChildren(parent);
4384}
4385
4386#ifndef __has_feature
4387#define __has_feature(x) 0
4388#endif
4389#if __has_feature(blocks)
4390typedef enum CXChildVisitResult
4391 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4392
4393static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4394 CXClientData client_data) {
4395 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4396 return block(cursor, parent);
4397}
4398#else
4399// If we are compiled with a compiler that doesn't have native blocks support,
4400// define and call the block manually, so the
4401typedef struct _CXChildVisitResult
4402{
4403 void *isa;
4404 int flags;
4405 int reserved;
4406 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4407 CXCursor);
4408} *CXCursorVisitorBlock;
4409
4410static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4411 CXClientData client_data) {
4412 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4413 return block->invoke(block, cursor, parent);
4414}
4415#endif
4416
4417
4418unsigned clang_visitChildrenWithBlock(CXCursor parent,
4419 CXCursorVisitorBlock block) {
4420 return clang_visitChildren(parent, visitWithBlock, block);
4421}
4422
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004423static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004424 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004425 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004426
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004427 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004428 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004429 if (const ObjCPropertyImplDecl *PropImpl =
4430 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004431 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004432 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004433
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004434 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004435 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004436 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004437
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004438 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004439 }
4440
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004441 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004442 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004443
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004444 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004445 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4446 // and returns different names. NamedDecl returns the class name and
4447 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004448 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004449
4450 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004451 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004452
4453 SmallString<1024> S;
4454 llvm::raw_svector_ostream os(S);
4455 ND->printName(os);
4456
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004457 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004458}
4459
4460CXString clang_getCursorSpelling(CXCursor C) {
4461 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004462 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004463
4464 if (clang_isReference(C.kind)) {
4465 switch (C.kind) {
4466 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004467 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004468 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004469 }
4470 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004471 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004472 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004473 }
4474 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004475 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004476 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004477 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004478 }
4479 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004480 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004481 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004482 }
4483 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004484 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004485 assert(Type && "Missing type decl");
4486
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004487 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004488 getAsString());
4489 }
4490 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004491 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004492 assert(Template && "Missing template decl");
4493
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004494 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004495 }
4496
4497 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004498 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004499 assert(NS && "Missing namespace decl");
4500
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004501 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004502 }
4503
4504 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004505 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004506 assert(Field && "Missing member decl");
4507
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004508 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004509 }
4510
4511 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004512 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004513 assert(Label && "Missing label");
4514
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004515 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004516 }
4517
4518 case CXCursor_OverloadedDeclRef: {
4519 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004520 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4521 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004522 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004523 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004524 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004525 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004526 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004527 OverloadedTemplateStorage *Ovl
4528 = Storage.get<OverloadedTemplateStorage*>();
4529 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004530 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004531 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004532 }
4533
4534 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004535 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004536 assert(Var && "Missing variable decl");
4537
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004538 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004539 }
4540
4541 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004542 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004543 }
4544 }
4545
4546 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004547 const Expr *E = getCursorExpr(C);
4548
4549 if (C.kind == CXCursor_ObjCStringLiteral ||
4550 C.kind == CXCursor_StringLiteral) {
4551 const StringLiteral *SLit;
4552 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4553 SLit = OSL->getString();
4554 } else {
4555 SLit = cast<StringLiteral>(E);
4556 }
4557 SmallString<256> Buf;
4558 llvm::raw_svector_ostream OS(Buf);
4559 SLit->outputString(OS);
4560 return cxstring::createDup(OS.str());
4561 }
4562
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004563 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004564 if (D)
4565 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004566 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004567 }
4568
4569 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004570 const Stmt *S = getCursorStmt(C);
4571 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004572 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004573
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004574 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004575 }
4576
4577 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004578 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004579 ->getNameStart());
4580
4581 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004582 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004583 ->getNameStart());
4584
4585 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004586 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004587
4588 if (clang_isDeclaration(C.kind))
4589 return getDeclSpelling(getCursorDecl(C));
4590
4591 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004592 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004593 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004594 }
4595
4596 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004597 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004598 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004599 }
4600
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004601 if (C.kind == CXCursor_PackedAttr) {
4602 return cxstring::createRef("packed");
4603 }
4604
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004605 if (C.kind == CXCursor_VisibilityAttr) {
4606 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4607 switch (AA->getVisibility()) {
4608 case VisibilityAttr::VisibilityType::Default:
4609 return cxstring::createRef("default");
4610 case VisibilityAttr::VisibilityType::Hidden:
4611 return cxstring::createRef("hidden");
4612 case VisibilityAttr::VisibilityType::Protected:
4613 return cxstring::createRef("protected");
4614 }
4615 llvm_unreachable("unknown visibility type");
4616 }
4617
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004618 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004619}
4620
4621CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4622 unsigned pieceIndex,
4623 unsigned options) {
4624 if (clang_Cursor_isNull(C))
4625 return clang_getNullRange();
4626
4627 ASTContext &Ctx = getCursorContext(C);
4628
4629 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004630 const Stmt *S = getCursorStmt(C);
4631 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004632 if (pieceIndex > 0)
4633 return clang_getNullRange();
4634 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4635 }
4636
4637 return clang_getNullRange();
4638 }
4639
4640 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004641 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004642 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4643 if (pieceIndex >= ME->getNumSelectorLocs())
4644 return clang_getNullRange();
4645 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4646 }
4647 }
4648
4649 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4650 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004651 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004652 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4653 if (pieceIndex >= MD->getNumSelectorLocs())
4654 return clang_getNullRange();
4655 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4656 }
4657 }
4658
4659 if (C.kind == CXCursor_ObjCCategoryDecl ||
4660 C.kind == CXCursor_ObjCCategoryImplDecl) {
4661 if (pieceIndex > 0)
4662 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004663 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004664 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4665 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004666 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004667 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4668 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4669 }
4670
4671 if (C.kind == CXCursor_ModuleImportDecl) {
4672 if (pieceIndex > 0)
4673 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004674 if (const ImportDecl *ImportD =
4675 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004676 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4677 if (!Locs.empty())
4678 return cxloc::translateSourceRange(Ctx,
4679 SourceRange(Locs.front(), Locs.back()));
4680 }
4681 return clang_getNullRange();
4682 }
4683
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004684 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004685 C.kind == CXCursor_ConversionFunction ||
4686 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004687 if (pieceIndex > 0)
4688 return clang_getNullRange();
4689 if (const FunctionDecl *FD =
4690 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4691 DeclarationNameInfo FunctionName = FD->getNameInfo();
4692 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4693 }
4694 return clang_getNullRange();
4695 }
4696
Guy Benyei11169dd2012-12-18 14:30:41 +00004697 // FIXME: A CXCursor_InclusionDirective should give the location of the
4698 // filename, but we don't keep track of this.
4699
4700 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4701 // but we don't keep track of this.
4702
4703 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4704 // but we don't keep track of this.
4705
4706 // Default handling, give the location of the cursor.
4707
4708 if (pieceIndex > 0)
4709 return clang_getNullRange();
4710
4711 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4712 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4713 return cxloc::translateSourceRange(Ctx, Loc);
4714}
4715
Eli Bendersky44a206f2014-07-31 18:04:56 +00004716CXString clang_Cursor_getMangling(CXCursor C) {
4717 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4718 return cxstring::createEmpty();
4719
Eli Bendersky44a206f2014-07-31 18:04:56 +00004720 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004721 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004722 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4723 return cxstring::createEmpty();
4724
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004725 ASTContext &Ctx = D->getASTContext();
4726 index::CodegenNameGenerator CGNameGen(Ctx);
4727 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004728}
4729
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004730CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4731 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4732 return nullptr;
4733
4734 const Decl *D = getCursorDecl(C);
4735 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4736 return nullptr;
4737
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004738 ASTContext &Ctx = D->getASTContext();
4739 index::CodegenNameGenerator CGNameGen(Ctx);
4740 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004741 return cxstring::createSet(Manglings);
4742}
4743
Dave Lee1a532c92017-09-22 16:58:57 +00004744CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4745 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4746 return nullptr;
4747
4748 const Decl *D = getCursorDecl(C);
4749 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4750 return nullptr;
4751
4752 ASTContext &Ctx = D->getASTContext();
4753 index::CodegenNameGenerator CGNameGen(Ctx);
4754 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4755 return cxstring::createSet(Manglings);
4756}
4757
Jonathan Coe45ef5032018-01-16 10:19:56 +00004758CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4759 if (clang_Cursor_isNull(C))
4760 return 0;
4761 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4762}
4763
4764void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4765 if (Policy)
4766 delete static_cast<PrintingPolicy *>(Policy);
4767}
4768
4769unsigned
4770clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4771 enum CXPrintingPolicyProperty Property) {
4772 if (!Policy)
4773 return 0;
4774
4775 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4776 switch (Property) {
4777 case CXPrintingPolicy_Indentation:
4778 return P->Indentation;
4779 case CXPrintingPolicy_SuppressSpecifiers:
4780 return P->SuppressSpecifiers;
4781 case CXPrintingPolicy_SuppressTagKeyword:
4782 return P->SuppressTagKeyword;
4783 case CXPrintingPolicy_IncludeTagDefinition:
4784 return P->IncludeTagDefinition;
4785 case CXPrintingPolicy_SuppressScope:
4786 return P->SuppressScope;
4787 case CXPrintingPolicy_SuppressUnwrittenScope:
4788 return P->SuppressUnwrittenScope;
4789 case CXPrintingPolicy_SuppressInitializers:
4790 return P->SuppressInitializers;
4791 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4792 return P->ConstantArraySizeAsWritten;
4793 case CXPrintingPolicy_AnonymousTagLocations:
4794 return P->AnonymousTagLocations;
4795 case CXPrintingPolicy_SuppressStrongLifetime:
4796 return P->SuppressStrongLifetime;
4797 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4798 return P->SuppressLifetimeQualifiers;
4799 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4800 return P->SuppressTemplateArgsInCXXConstructors;
4801 case CXPrintingPolicy_Bool:
4802 return P->Bool;
4803 case CXPrintingPolicy_Restrict:
4804 return P->Restrict;
4805 case CXPrintingPolicy_Alignof:
4806 return P->Alignof;
4807 case CXPrintingPolicy_UnderscoreAlignof:
4808 return P->UnderscoreAlignof;
4809 case CXPrintingPolicy_UseVoidForZeroParams:
4810 return P->UseVoidForZeroParams;
4811 case CXPrintingPolicy_TerseOutput:
4812 return P->TerseOutput;
4813 case CXPrintingPolicy_PolishForDeclaration:
4814 return P->PolishForDeclaration;
4815 case CXPrintingPolicy_Half:
4816 return P->Half;
4817 case CXPrintingPolicy_MSWChar:
4818 return P->MSWChar;
4819 case CXPrintingPolicy_IncludeNewlines:
4820 return P->IncludeNewlines;
4821 case CXPrintingPolicy_MSVCFormatting:
4822 return P->MSVCFormatting;
4823 case CXPrintingPolicy_ConstantsAsWritten:
4824 return P->ConstantsAsWritten;
4825 case CXPrintingPolicy_SuppressImplicitBase:
4826 return P->SuppressImplicitBase;
4827 case CXPrintingPolicy_FullyQualifiedName:
4828 return P->FullyQualifiedName;
4829 }
4830
4831 assert(false && "Invalid CXPrintingPolicyProperty");
4832 return 0;
4833}
4834
4835void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4836 enum CXPrintingPolicyProperty Property,
4837 unsigned Value) {
4838 if (!Policy)
4839 return;
4840
4841 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4842 switch (Property) {
4843 case CXPrintingPolicy_Indentation:
4844 P->Indentation = Value;
4845 return;
4846 case CXPrintingPolicy_SuppressSpecifiers:
4847 P->SuppressSpecifiers = Value;
4848 return;
4849 case CXPrintingPolicy_SuppressTagKeyword:
4850 P->SuppressTagKeyword = Value;
4851 return;
4852 case CXPrintingPolicy_IncludeTagDefinition:
4853 P->IncludeTagDefinition = Value;
4854 return;
4855 case CXPrintingPolicy_SuppressScope:
4856 P->SuppressScope = Value;
4857 return;
4858 case CXPrintingPolicy_SuppressUnwrittenScope:
4859 P->SuppressUnwrittenScope = Value;
4860 return;
4861 case CXPrintingPolicy_SuppressInitializers:
4862 P->SuppressInitializers = Value;
4863 return;
4864 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4865 P->ConstantArraySizeAsWritten = Value;
4866 return;
4867 case CXPrintingPolicy_AnonymousTagLocations:
4868 P->AnonymousTagLocations = Value;
4869 return;
4870 case CXPrintingPolicy_SuppressStrongLifetime:
4871 P->SuppressStrongLifetime = Value;
4872 return;
4873 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4874 P->SuppressLifetimeQualifiers = Value;
4875 return;
4876 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4877 P->SuppressTemplateArgsInCXXConstructors = Value;
4878 return;
4879 case CXPrintingPolicy_Bool:
4880 P->Bool = Value;
4881 return;
4882 case CXPrintingPolicy_Restrict:
4883 P->Restrict = Value;
4884 return;
4885 case CXPrintingPolicy_Alignof:
4886 P->Alignof = Value;
4887 return;
4888 case CXPrintingPolicy_UnderscoreAlignof:
4889 P->UnderscoreAlignof = Value;
4890 return;
4891 case CXPrintingPolicy_UseVoidForZeroParams:
4892 P->UseVoidForZeroParams = Value;
4893 return;
4894 case CXPrintingPolicy_TerseOutput:
4895 P->TerseOutput = Value;
4896 return;
4897 case CXPrintingPolicy_PolishForDeclaration:
4898 P->PolishForDeclaration = Value;
4899 return;
4900 case CXPrintingPolicy_Half:
4901 P->Half = Value;
4902 return;
4903 case CXPrintingPolicy_MSWChar:
4904 P->MSWChar = Value;
4905 return;
4906 case CXPrintingPolicy_IncludeNewlines:
4907 P->IncludeNewlines = Value;
4908 return;
4909 case CXPrintingPolicy_MSVCFormatting:
4910 P->MSVCFormatting = Value;
4911 return;
4912 case CXPrintingPolicy_ConstantsAsWritten:
4913 P->ConstantsAsWritten = Value;
4914 return;
4915 case CXPrintingPolicy_SuppressImplicitBase:
4916 P->SuppressImplicitBase = Value;
4917 return;
4918 case CXPrintingPolicy_FullyQualifiedName:
4919 P->FullyQualifiedName = Value;
4920 return;
4921 }
4922
4923 assert(false && "Invalid CXPrintingPolicyProperty");
4924}
4925
4926CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4927 if (clang_Cursor_isNull(C))
4928 return cxstring::createEmpty();
4929
4930 if (clang_isDeclaration(C.kind)) {
4931 const Decl *D = getCursorDecl(C);
4932 if (!D)
4933 return cxstring::createEmpty();
4934
4935 SmallString<128> Str;
4936 llvm::raw_svector_ostream OS(Str);
4937 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4938 D->print(OS, UserPolicy ? *UserPolicy
4939 : getCursorContext(C).getPrintingPolicy());
4940
4941 return cxstring::createDup(OS.str());
4942 }
4943
4944 return cxstring::createEmpty();
4945}
4946
Guy Benyei11169dd2012-12-18 14:30:41 +00004947CXString clang_getCursorDisplayName(CXCursor C) {
4948 if (!clang_isDeclaration(C.kind))
4949 return clang_getCursorSpelling(C);
4950
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004951 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004952 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004953 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004954
4955 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004956 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004957 D = FunTmpl->getTemplatedDecl();
4958
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004959 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004960 SmallString<64> Str;
4961 llvm::raw_svector_ostream OS(Str);
4962 OS << *Function;
4963 if (Function->getPrimaryTemplate())
4964 OS << "<>";
4965 OS << "(";
4966 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4967 if (I)
4968 OS << ", ";
4969 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4970 }
4971
4972 if (Function->isVariadic()) {
4973 if (Function->getNumParams())
4974 OS << ", ";
4975 OS << "...";
4976 }
4977 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004978 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004979 }
4980
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004981 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004982 SmallString<64> Str;
4983 llvm::raw_svector_ostream OS(Str);
4984 OS << *ClassTemplate;
4985 OS << "<";
4986 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4987 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4988 if (I)
4989 OS << ", ";
4990
4991 NamedDecl *Param = Params->getParam(I);
4992 if (Param->getIdentifier()) {
4993 OS << Param->getIdentifier()->getName();
4994 continue;
4995 }
4996
4997 // There is no parameter name, which makes this tricky. Try to come up
4998 // with something useful that isn't too long.
4999 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5000 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
5001 else if (NonTypeTemplateParmDecl *NTTP
5002 = dyn_cast<NonTypeTemplateParmDecl>(Param))
5003 OS << NTTP->getType().getAsString(Policy);
5004 else
5005 OS << "template<...> class";
5006 }
5007
5008 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005009 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005010 }
5011
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005012 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00005013 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
5014 // If the type was explicitly written, use that.
5015 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005016 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00005017
Benjamin Kramer9170e912013-02-22 15:46:01 +00005018 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00005019 llvm::raw_svector_ostream OS(Str);
5020 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00005021 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5022 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005023 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005024 }
5025
5026 return clang_getCursorSpelling(C);
5027}
5028
5029CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5030 switch (Kind) {
5031 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005032 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005033 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005034 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005035 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005036 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005037 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005038 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005039 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005040 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005041 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005042 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005043 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005044 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005045 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005046 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005047 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005048 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005049 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005050 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005051 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005052 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005053 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005054 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005055 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005056 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005057 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005058 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005059 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005060 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005061 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005062 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005063 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005064 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005065 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005066 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005067 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005068 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005069 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005070 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005071 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005072 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005074 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005075 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005076 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005077 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005078 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005079 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005080 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005081 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005082 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005083 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005084 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005085 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005086 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005087 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005088 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005089 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005090 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005091 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005092 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005093 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005094 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005095 case CXCursor_FixedPointLiteral:
5096 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005097 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005098 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005099 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005100 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005101 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005102 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005103 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005104 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005105 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005106 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005107 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005108 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005109 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005110 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005111 case CXCursor_OMPArraySectionExpr:
5112 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005113 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005114 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005115 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005116 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005117 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005118 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005119 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005120 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005121 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005122 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005123 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005124 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005125 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005126 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005127 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005128 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005129 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005130 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005131 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005132 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005133 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005134 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005135 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005136 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005137 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005138 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005139 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005140 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005141 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005142 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005143 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005144 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005145 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005146 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005147 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005148 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005149 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005150 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005151 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005152 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005153 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005154 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005155 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005156 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005157 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005158 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005159 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005160 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005161 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005162 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005163 case CXCursor_ObjCAvailabilityCheckExpr:
5164 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005165 case CXCursor_ObjCSelfExpr:
5166 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005167 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005168 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005169 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005170 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005171 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005172 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005173 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005174 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005175 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005176 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005177 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005178 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005179 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005180 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005181 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005182 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005183 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005184 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005185 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005186 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005187 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005188 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005189 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005190 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005191 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005192 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005193 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005194 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005195 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005196 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005197 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005198 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005199 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005200 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005201 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005202 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005203 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005204 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005205 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005206 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005207 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005208 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005209 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005210 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005211 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005212 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005213 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005214 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005215 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005216 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005217 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005218 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005219 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005220 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005221 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005222 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005223 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005224 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005225 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005226 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005227 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005228 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005229 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005230 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005231 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005232 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005233 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005234 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005235 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005236 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005237 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005238 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005239 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005240 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005241 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005242 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005243 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005244 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005245 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005246 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005247 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005248 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005249 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005250 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005251 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005252 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005253 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005254 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005255 case CXCursor_SEHLeaveStmt:
5256 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005257 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005258 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005259 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005260 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005261 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005262 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005263 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005264 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005265 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005266 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005267 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005268 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005269 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005270 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005271 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005272 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005273 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005274 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005275 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005276 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005277 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005278 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005279 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005280 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005281 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005282 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005283 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005284 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005285 case CXCursor_PackedAttr:
5286 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005287 case CXCursor_PureAttr:
5288 return cxstring::createRef("attribute(pure)");
5289 case CXCursor_ConstAttr:
5290 return cxstring::createRef("attribute(const)");
5291 case CXCursor_NoDuplicateAttr:
5292 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005293 case CXCursor_CUDAConstantAttr:
5294 return cxstring::createRef("attribute(constant)");
5295 case CXCursor_CUDADeviceAttr:
5296 return cxstring::createRef("attribute(device)");
5297 case CXCursor_CUDAGlobalAttr:
5298 return cxstring::createRef("attribute(global)");
5299 case CXCursor_CUDAHostAttr:
5300 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005301 case CXCursor_CUDASharedAttr:
5302 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005303 case CXCursor_VisibilityAttr:
5304 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005305 case CXCursor_DLLExport:
5306 return cxstring::createRef("attribute(dllexport)");
5307 case CXCursor_DLLImport:
5308 return cxstring::createRef("attribute(dllimport)");
Michael Wud092d0b2018-08-03 05:03:22 +00005309 case CXCursor_NSReturnsRetained:
5310 return cxstring::createRef("attribute(ns_returns_retained)");
5311 case CXCursor_NSReturnsNotRetained:
5312 return cxstring::createRef("attribute(ns_returns_not_retained)");
5313 case CXCursor_NSReturnsAutoreleased:
5314 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5315 case CXCursor_NSConsumesSelf:
5316 return cxstring::createRef("attribute(ns_consumes_self)");
5317 case CXCursor_NSConsumed:
5318 return cxstring::createRef("attribute(ns_consumed)");
5319 case CXCursor_ObjCException:
5320 return cxstring::createRef("attribute(objc_exception)");
5321 case CXCursor_ObjCNSObject:
5322 return cxstring::createRef("attribute(NSObject)");
5323 case CXCursor_ObjCIndependentClass:
5324 return cxstring::createRef("attribute(objc_independent_class)");
5325 case CXCursor_ObjCPreciseLifetime:
5326 return cxstring::createRef("attribute(objc_precise_lifetime)");
5327 case CXCursor_ObjCReturnsInnerPointer:
5328 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5329 case CXCursor_ObjCRequiresSuper:
5330 return cxstring::createRef("attribute(objc_requires_super)");
5331 case CXCursor_ObjCRootClass:
5332 return cxstring::createRef("attribute(objc_root_class)");
5333 case CXCursor_ObjCSubclassingRestricted:
5334 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5335 case CXCursor_ObjCExplicitProtocolImpl:
5336 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5337 case CXCursor_ObjCDesignatedInitializer:
5338 return cxstring::createRef("attribute(objc_designated_initializer)");
5339 case CXCursor_ObjCRuntimeVisible:
5340 return cxstring::createRef("attribute(objc_runtime_visible)");
5341 case CXCursor_ObjCBoxable:
5342 return cxstring::createRef("attribute(objc_boxable)");
Michael Wu58d837d2018-08-03 05:55:40 +00005343 case CXCursor_FlagEnum:
5344 return cxstring::createRef("attribute(flag_enum)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005345 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005346 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005347 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005348 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005349 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005350 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005351 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005352 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005353 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005354 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005355 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005356 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005357 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005358 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005359 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005360 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005361 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005362 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005363 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005364 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005365 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005366 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005367 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005368 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005369 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005370 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005371 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005372 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005373 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005374 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005375 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005376 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005377 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005378 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005379 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005380 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005381 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005382 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005383 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005384 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005385 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005386 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005387 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005388 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005389 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005390 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005391 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005392 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005393 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005394 return cxstring::createRef("OMPParallelDirective");
5395 case CXCursor_OMPSimdDirective:
5396 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005397 case CXCursor_OMPForDirective:
5398 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005399 case CXCursor_OMPForSimdDirective:
5400 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005401 case CXCursor_OMPSectionsDirective:
5402 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005403 case CXCursor_OMPSectionDirective:
5404 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005405 case CXCursor_OMPSingleDirective:
5406 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005407 case CXCursor_OMPMasterDirective:
5408 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005409 case CXCursor_OMPCriticalDirective:
5410 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005411 case CXCursor_OMPParallelForDirective:
5412 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005413 case CXCursor_OMPParallelForSimdDirective:
5414 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005415 case CXCursor_OMPParallelSectionsDirective:
5416 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005417 case CXCursor_OMPTaskDirective:
5418 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005419 case CXCursor_OMPTaskyieldDirective:
5420 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005421 case CXCursor_OMPBarrierDirective:
5422 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005423 case CXCursor_OMPTaskwaitDirective:
5424 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005425 case CXCursor_OMPTaskgroupDirective:
5426 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005427 case CXCursor_OMPFlushDirective:
5428 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005429 case CXCursor_OMPOrderedDirective:
5430 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005431 case CXCursor_OMPAtomicDirective:
5432 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005433 case CXCursor_OMPTargetDirective:
5434 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005435 case CXCursor_OMPTargetDataDirective:
5436 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005437 case CXCursor_OMPTargetEnterDataDirective:
5438 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005439 case CXCursor_OMPTargetExitDataDirective:
5440 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005441 case CXCursor_OMPTargetParallelDirective:
5442 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005443 case CXCursor_OMPTargetParallelForDirective:
5444 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005445 case CXCursor_OMPTargetUpdateDirective:
5446 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005447 case CXCursor_OMPTeamsDirective:
5448 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005449 case CXCursor_OMPCancellationPointDirective:
5450 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005451 case CXCursor_OMPCancelDirective:
5452 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005453 case CXCursor_OMPTaskLoopDirective:
5454 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005455 case CXCursor_OMPTaskLoopSimdDirective:
5456 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005457 case CXCursor_OMPDistributeDirective:
5458 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005459 case CXCursor_OMPDistributeParallelForDirective:
5460 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005461 case CXCursor_OMPDistributeParallelForSimdDirective:
5462 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005463 case CXCursor_OMPDistributeSimdDirective:
5464 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005465 case CXCursor_OMPTargetParallelForSimdDirective:
5466 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005467 case CXCursor_OMPTargetSimdDirective:
5468 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005469 case CXCursor_OMPTeamsDistributeDirective:
5470 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005471 case CXCursor_OMPTeamsDistributeSimdDirective:
5472 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005473 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5474 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005475 case CXCursor_OMPTeamsDistributeParallelForDirective:
5476 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005477 case CXCursor_OMPTargetTeamsDirective:
5478 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005479 case CXCursor_OMPTargetTeamsDistributeDirective:
5480 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005481 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5482 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005483 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5484 return cxstring::createRef(
5485 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005486 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5487 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005488 case CXCursor_OverloadCandidate:
5489 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005490 case CXCursor_TypeAliasTemplateDecl:
5491 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005492 case CXCursor_StaticAssert:
5493 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005494 case CXCursor_FriendDecl:
Sven van Haastregtdc2c9302019-02-11 11:00:56 +00005495 return cxstring::createRef("FriendDecl");
5496 case CXCursor_ConvergentAttr:
5497 return cxstring::createRef("attribute(convergent)");
Emilio Cobos Alvarez0a3fe502019-02-25 21:24:52 +00005498 case CXCursor_WarnUnusedAttr:
5499 return cxstring::createRef("attribute(warn_unused)");
5500 case CXCursor_WarnUnusedResultAttr:
5501 return cxstring::createRef("attribute(warn_unused_result)");
Emilio Cobos Alvarezcd741272019-03-13 16:16:54 +00005502 case CXCursor_AlignedAttr:
5503 return cxstring::createRef("attribute(aligned)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005504 }
5505
5506 llvm_unreachable("Unhandled CXCursorKind");
5507}
5508
5509struct GetCursorData {
5510 SourceLocation TokenBeginLoc;
5511 bool PointsAtMacroArgExpansion;
5512 bool VisitedObjCPropertyImplDecl;
5513 SourceLocation VisitedDeclaratorDeclStartLoc;
5514 CXCursor &BestCursor;
5515
5516 GetCursorData(SourceManager &SM,
5517 SourceLocation tokenBegin, CXCursor &outputCursor)
5518 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5519 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5520 VisitedObjCPropertyImplDecl = false;
5521 }
5522};
5523
5524static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5525 CXCursor parent,
5526 CXClientData client_data) {
5527 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5528 CXCursor *BestCursor = &Data->BestCursor;
5529
5530 // If we point inside a macro argument we should provide info of what the
5531 // token is so use the actual cursor, don't replace it with a macro expansion
5532 // cursor.
5533 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5534 return CXChildVisit_Recurse;
5535
5536 if (clang_isDeclaration(cursor.kind)) {
5537 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005538 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005539 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5540 if (MD->isImplicit())
5541 return CXChildVisit_Break;
5542
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005543 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005544 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5545 // Check that when we have multiple @class references in the same line,
5546 // that later ones do not override the previous ones.
5547 // If we have:
5548 // @class Foo, Bar;
5549 // source ranges for both start at '@', so 'Bar' will end up overriding
5550 // 'Foo' even though the cursor location was at 'Foo'.
5551 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5552 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005553 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005554 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5555 if (PrevID != ID &&
5556 !PrevID->isThisDeclarationADefinition() &&
5557 !ID->isThisDeclarationADefinition())
5558 return CXChildVisit_Break;
5559 }
5560
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005561 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005562 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5563 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5564 // Check that when we have multiple declarators in the same line,
5565 // that later ones do not override the previous ones.
5566 // If we have:
5567 // int Foo, Bar;
5568 // source ranges for both start at 'int', so 'Bar' will end up overriding
5569 // 'Foo' even though the cursor location was at 'Foo'.
5570 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5571 return CXChildVisit_Break;
5572 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5573
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005574 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005575 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5576 (void)PropImp;
5577 // Check that when we have multiple @synthesize in the same line,
5578 // that later ones do not override the previous ones.
5579 // If we have:
5580 // @synthesize Foo, Bar;
5581 // source ranges for both start at '@', so 'Bar' will end up overriding
5582 // 'Foo' even though the cursor location was at 'Foo'.
5583 if (Data->VisitedObjCPropertyImplDecl)
5584 return CXChildVisit_Break;
5585 Data->VisitedObjCPropertyImplDecl = true;
5586 }
5587 }
5588
5589 if (clang_isExpression(cursor.kind) &&
5590 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005591 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005592 // Avoid having the cursor of an expression replace the declaration cursor
5593 // when the expression source range overlaps the declaration range.
5594 // This can happen for C++ constructor expressions whose range generally
5595 // include the variable declaration, e.g.:
5596 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5597 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5598 D->getLocation() == Data->TokenBeginLoc)
5599 return CXChildVisit_Break;
5600 }
5601 }
5602
5603 // If our current best cursor is the construction of a temporary object,
5604 // don't replace that cursor with a type reference, because we want
5605 // clang_getCursor() to point at the constructor.
5606 if (clang_isExpression(BestCursor->kind) &&
5607 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5608 cursor.kind == CXCursor_TypeRef) {
5609 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5610 // as having the actual point on the type reference.
5611 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5612 return CXChildVisit_Recurse;
5613 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005614
5615 // If we already have an Objective-C superclass reference, don't
5616 // update it further.
5617 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5618 return CXChildVisit_Break;
5619
Guy Benyei11169dd2012-12-18 14:30:41 +00005620 *BestCursor = cursor;
5621 return CXChildVisit_Recurse;
5622}
5623
5624CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005625 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005626 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005627 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005628 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005629
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005630 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005631 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5632
5633 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5634 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5635
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005636 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005637 CXFile SearchFile;
5638 unsigned SearchLine, SearchColumn;
5639 CXFile ResultFile;
5640 unsigned ResultLine, ResultColumn;
5641 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5642 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5643 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005644
5645 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5646 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005647 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005648 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005649 SearchFileName = clang_getFileName(SearchFile);
5650 ResultFileName = clang_getFileName(ResultFile);
5651 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5652 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005653 *Log << llvm::format("(%s:%d:%d) = %s",
5654 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5655 clang_getCString(KindSpelling))
5656 << llvm::format("(%s:%d:%d):%s%s",
5657 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5658 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005659 clang_disposeString(SearchFileName);
5660 clang_disposeString(ResultFileName);
5661 clang_disposeString(KindSpelling);
5662 clang_disposeString(USR);
5663
5664 CXCursor Definition = clang_getCursorDefinition(Result);
5665 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5666 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5667 CXString DefinitionKindSpelling
5668 = clang_getCursorKindSpelling(Definition.kind);
5669 CXFile DefinitionFile;
5670 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005671 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005672 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005673 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005674 *Log << llvm::format(" -> %s(%s:%d:%d)",
5675 clang_getCString(DefinitionKindSpelling),
5676 clang_getCString(DefinitionFileName),
5677 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005678 clang_disposeString(DefinitionFileName);
5679 clang_disposeString(DefinitionKindSpelling);
5680 }
5681 }
5682
5683 return Result;
5684}
5685
5686CXCursor clang_getNullCursor(void) {
5687 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5688}
5689
5690unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005691 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5692 // can't set consistently. For example, when visiting a DeclStmt we will set
5693 // it but we don't set it on the result of clang_getCursorDefinition for
5694 // a reference of the same declaration.
5695 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5696 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5697 // to provide that kind of info.
5698 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005699 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005700 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005701 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005702
Guy Benyei11169dd2012-12-18 14:30:41 +00005703 return X == Y;
5704}
5705
5706unsigned clang_hashCursor(CXCursor C) {
5707 unsigned Index = 0;
5708 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5709 Index = 1;
5710
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005711 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005712 std::make_pair(C.kind, C.data[Index]));
5713}
5714
5715unsigned clang_isInvalid(enum CXCursorKind K) {
5716 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5717}
5718
5719unsigned clang_isDeclaration(enum CXCursorKind K) {
5720 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005721 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5722}
5723
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005724unsigned clang_isInvalidDeclaration(CXCursor C) {
5725 if (clang_isDeclaration(C.kind)) {
5726 if (const Decl *D = getCursorDecl(C))
5727 return D->isInvalidDecl();
5728 }
5729
5730 return 0;
5731}
5732
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005733unsigned clang_isReference(enum CXCursorKind K) {
5734 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5735}
Guy Benyei11169dd2012-12-18 14:30:41 +00005736
5737unsigned clang_isExpression(enum CXCursorKind K) {
5738 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5739}
5740
5741unsigned clang_isStatement(enum CXCursorKind K) {
5742 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5743}
5744
5745unsigned clang_isAttribute(enum CXCursorKind K) {
5746 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5747}
5748
5749unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5750 return K == CXCursor_TranslationUnit;
5751}
5752
5753unsigned clang_isPreprocessing(enum CXCursorKind K) {
5754 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5755}
5756
5757unsigned clang_isUnexposed(enum CXCursorKind K) {
5758 switch (K) {
5759 case CXCursor_UnexposedDecl:
5760 case CXCursor_UnexposedExpr:
5761 case CXCursor_UnexposedStmt:
5762 case CXCursor_UnexposedAttr:
5763 return true;
5764 default:
5765 return false;
5766 }
5767}
5768
5769CXCursorKind clang_getCursorKind(CXCursor C) {
5770 return C.kind;
5771}
5772
5773CXSourceLocation clang_getCursorLocation(CXCursor C) {
5774 if (clang_isReference(C.kind)) {
5775 switch (C.kind) {
5776 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005777 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005778 = getCursorObjCSuperClassRef(C);
5779 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5780 }
5781
5782 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005783 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005784 = getCursorObjCProtocolRef(C);
5785 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5786 }
5787
5788 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005789 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005790 = getCursorObjCClassRef(C);
5791 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5792 }
5793
5794 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005795 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005796 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5797 }
5798
5799 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005800 std::pair<const TemplateDecl *, SourceLocation> P =
5801 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005802 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5803 }
5804
5805 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005806 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005807 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5808 }
5809
5810 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005811 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005812 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5813 }
5814
5815 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005816 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005817 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5818 }
5819
5820 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005821 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005822 if (!BaseSpec)
5823 return clang_getNullLocation();
5824
5825 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5826 return cxloc::translateSourceLocation(getCursorContext(C),
5827 TSInfo->getTypeLoc().getBeginLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005828
Guy Benyei11169dd2012-12-18 14:30:41 +00005829 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005830 BaseSpec->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005831 }
5832
5833 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005834 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005835 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5836 }
5837
5838 case CXCursor_OverloadedDeclRef:
5839 return cxloc::translateSourceLocation(getCursorContext(C),
5840 getCursorOverloadedDeclRef(C).second);
5841
5842 default:
5843 // FIXME: Need a way to enumerate all non-reference cases.
5844 llvm_unreachable("Missed a reference kind");
5845 }
5846 }
5847
5848 if (clang_isExpression(C.kind))
5849 return cxloc::translateSourceLocation(getCursorContext(C),
5850 getLocationFromExpr(getCursorExpr(C)));
5851
5852 if (clang_isStatement(C.kind))
5853 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005854 getCursorStmt(C)->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005855
5856 if (C.kind == CXCursor_PreprocessingDirective) {
5857 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5858 return cxloc::translateSourceLocation(getCursorContext(C), L);
5859 }
5860
5861 if (C.kind == CXCursor_MacroExpansion) {
5862 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005863 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005864 return cxloc::translateSourceLocation(getCursorContext(C), L);
5865 }
5866
5867 if (C.kind == CXCursor_MacroDefinition) {
5868 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5869 return cxloc::translateSourceLocation(getCursorContext(C), L);
5870 }
5871
5872 if (C.kind == CXCursor_InclusionDirective) {
5873 SourceLocation L
5874 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5875 return cxloc::translateSourceLocation(getCursorContext(C), L);
5876 }
5877
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005878 if (clang_isAttribute(C.kind)) {
5879 SourceLocation L
5880 = cxcursor::getCursorAttr(C)->getLocation();
5881 return cxloc::translateSourceLocation(getCursorContext(C), L);
5882 }
5883
Guy Benyei11169dd2012-12-18 14:30:41 +00005884 if (!clang_isDeclaration(C.kind))
5885 return clang_getNullLocation();
5886
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005887 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005888 if (!D)
5889 return clang_getNullLocation();
5890
5891 SourceLocation Loc = D->getLocation();
5892 // FIXME: Multiple variables declared in a single declaration
5893 // currently lack the information needed to correctly determine their
5894 // ranges when accounting for the type-specifier. We use context
5895 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5896 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005897 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005898 if (!cxcursor::isFirstInDeclGroup(C))
5899 Loc = VD->getLocation();
5900 }
5901
5902 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005903 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005904 Loc = MD->getSelectorStartLoc();
5905
5906 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5907}
5908
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005909} // end extern "C"
5910
Guy Benyei11169dd2012-12-18 14:30:41 +00005911CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5912 assert(TU);
5913
5914 // Guard against an invalid SourceLocation, or we may assert in one
5915 // of the following calls.
5916 if (SLoc.isInvalid())
5917 return clang_getNullCursor();
5918
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005919 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005920
5921 // Translate the given source location to make it point at the beginning of
5922 // the token under the cursor.
5923 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5924 CXXUnit->getASTContext().getLangOpts());
5925
5926 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5927 if (SLoc.isValid()) {
5928 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5929 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5930 /*VisitPreprocessorLast=*/true,
5931 /*VisitIncludedEntities=*/false,
5932 SourceLocation(SLoc));
5933 CursorVis.visitFileRegion();
5934 }
5935
5936 return Result;
5937}
5938
5939static SourceRange getRawCursorExtent(CXCursor C) {
5940 if (clang_isReference(C.kind)) {
5941 switch (C.kind) {
5942 case CXCursor_ObjCSuperClassRef:
5943 return getCursorObjCSuperClassRef(C).second;
5944
5945 case CXCursor_ObjCProtocolRef:
5946 return getCursorObjCProtocolRef(C).second;
5947
5948 case CXCursor_ObjCClassRef:
5949 return getCursorObjCClassRef(C).second;
5950
5951 case CXCursor_TypeRef:
5952 return getCursorTypeRef(C).second;
5953
5954 case CXCursor_TemplateRef:
5955 return getCursorTemplateRef(C).second;
5956
5957 case CXCursor_NamespaceRef:
5958 return getCursorNamespaceRef(C).second;
5959
5960 case CXCursor_MemberRef:
5961 return getCursorMemberRef(C).second;
5962
5963 case CXCursor_CXXBaseSpecifier:
5964 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5965
5966 case CXCursor_LabelRef:
5967 return getCursorLabelRef(C).second;
5968
5969 case CXCursor_OverloadedDeclRef:
5970 return getCursorOverloadedDeclRef(C).second;
5971
5972 case CXCursor_VariableRef:
5973 return getCursorVariableRef(C).second;
5974
5975 default:
5976 // FIXME: Need a way to enumerate all non-reference cases.
5977 llvm_unreachable("Missed a reference kind");
5978 }
5979 }
5980
5981 if (clang_isExpression(C.kind))
5982 return getCursorExpr(C)->getSourceRange();
5983
5984 if (clang_isStatement(C.kind))
5985 return getCursorStmt(C)->getSourceRange();
5986
5987 if (clang_isAttribute(C.kind))
5988 return getCursorAttr(C)->getRange();
5989
5990 if (C.kind == CXCursor_PreprocessingDirective)
5991 return cxcursor::getCursorPreprocessingDirective(C);
5992
5993 if (C.kind == CXCursor_MacroExpansion) {
5994 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005995 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005996 return TU->mapRangeFromPreamble(Range);
5997 }
5998
5999 if (C.kind == CXCursor_MacroDefinition) {
6000 ASTUnit *TU = getCursorASTUnit(C);
6001 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
6002 return TU->mapRangeFromPreamble(Range);
6003 }
6004
6005 if (C.kind == CXCursor_InclusionDirective) {
6006 ASTUnit *TU = getCursorASTUnit(C);
6007 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
6008 return TU->mapRangeFromPreamble(Range);
6009 }
6010
6011 if (C.kind == CXCursor_TranslationUnit) {
6012 ASTUnit *TU = getCursorASTUnit(C);
6013 FileID MainID = TU->getSourceManager().getMainFileID();
6014 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
6015 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
6016 return SourceRange(Start, End);
6017 }
6018
6019 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006020 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006021 if (!D)
6022 return SourceRange();
6023
6024 SourceRange R = D->getSourceRange();
6025 // FIXME: Multiple variables declared in a single declaration
6026 // currently lack the information needed to correctly determine their
6027 // ranges when accounting for the type-specifier. We use context
6028 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6029 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006030 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006031 if (!cxcursor::isFirstInDeclGroup(C))
6032 R.setBegin(VD->getLocation());
6033 }
6034 return R;
6035 }
6036 return SourceRange();
6037}
6038
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006039/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00006040/// the decl-specifier-seq for declarations.
6041static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6042 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006043 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006044 if (!D)
6045 return SourceRange();
6046
6047 SourceRange R = D->getSourceRange();
6048
6049 // Adjust the start of the location for declarations preceded by
6050 // declaration specifiers.
6051 SourceLocation StartLoc;
6052 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6053 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006054 StartLoc = TI->getTypeLoc().getBeginLoc();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006055 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006056 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006057 StartLoc = TI->getTypeLoc().getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006058 }
6059
6060 if (StartLoc.isValid() && R.getBegin().isValid() &&
6061 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6062 R.setBegin(StartLoc);
6063
6064 // FIXME: Multiple variables declared in a single declaration
6065 // currently lack the information needed to correctly determine their
6066 // ranges when accounting for the type-specifier. We use context
6067 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6068 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006069 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006070 if (!cxcursor::isFirstInDeclGroup(C))
6071 R.setBegin(VD->getLocation());
6072 }
6073
6074 return R;
6075 }
6076
6077 return getRawCursorExtent(C);
6078}
6079
Guy Benyei11169dd2012-12-18 14:30:41 +00006080CXSourceRange clang_getCursorExtent(CXCursor C) {
6081 SourceRange R = getRawCursorExtent(C);
6082 if (R.isInvalid())
6083 return clang_getNullRange();
6084
6085 return cxloc::translateSourceRange(getCursorContext(C), R);
6086}
6087
6088CXCursor clang_getCursorReferenced(CXCursor C) {
6089 if (clang_isInvalid(C.kind))
6090 return clang_getNullCursor();
6091
6092 CXTranslationUnit tu = getCursorTU(C);
6093 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006094 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006095 if (!D)
6096 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006097 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006098 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006099 if (const ObjCPropertyImplDecl *PropImpl =
6100 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006101 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6102 return MakeCXCursor(Property, tu);
6103
6104 return C;
6105 }
6106
6107 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006108 const Expr *E = getCursorExpr(C);
6109 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006110 if (D) {
6111 CXCursor declCursor = MakeCXCursor(D, tu);
6112 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6113 declCursor);
6114 return declCursor;
6115 }
6116
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006117 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006118 return MakeCursorOverloadedDeclRef(Ovl, tu);
6119
6120 return clang_getNullCursor();
6121 }
6122
6123 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006124 const Stmt *S = getCursorStmt(C);
6125 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006126 if (LabelDecl *label = Goto->getLabel())
6127 if (LabelStmt *labelS = label->getStmt())
6128 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6129
6130 return clang_getNullCursor();
6131 }
Richard Smith66a81862015-05-04 02:25:31 +00006132
Guy Benyei11169dd2012-12-18 14:30:41 +00006133 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006134 if (const MacroDefinitionRecord *Def =
6135 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006136 return MakeMacroDefinitionCursor(Def, tu);
6137 }
6138
6139 if (!clang_isReference(C.kind))
6140 return clang_getNullCursor();
6141
6142 switch (C.kind) {
6143 case CXCursor_ObjCSuperClassRef:
6144 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6145
6146 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006147 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6148 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006149 return MakeCXCursor(Def, tu);
6150
6151 return MakeCXCursor(Prot, tu);
6152 }
6153
6154 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006155 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6156 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006157 return MakeCXCursor(Def, tu);
6158
6159 return MakeCXCursor(Class, tu);
6160 }
6161
6162 case CXCursor_TypeRef:
6163 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6164
6165 case CXCursor_TemplateRef:
6166 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6167
6168 case CXCursor_NamespaceRef:
6169 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6170
6171 case CXCursor_MemberRef:
6172 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6173
6174 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006175 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006176 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6177 tu ));
6178 }
6179
6180 case CXCursor_LabelRef:
6181 // FIXME: We end up faking the "parent" declaration here because we
6182 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006183 return MakeCXCursor(getCursorLabelRef(C).first,
6184 cxtu::getASTUnit(tu)->getASTContext()
6185 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006186 tu);
6187
6188 case CXCursor_OverloadedDeclRef:
6189 return C;
6190
6191 case CXCursor_VariableRef:
6192 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6193
6194 default:
6195 // We would prefer to enumerate all non-reference cursor kinds here.
6196 llvm_unreachable("Unhandled reference cursor kind");
6197 }
6198}
6199
6200CXCursor clang_getCursorDefinition(CXCursor C) {
6201 if (clang_isInvalid(C.kind))
6202 return clang_getNullCursor();
6203
6204 CXTranslationUnit TU = getCursorTU(C);
6205
6206 bool WasReference = false;
6207 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6208 C = clang_getCursorReferenced(C);
6209 WasReference = true;
6210 }
6211
6212 if (C.kind == CXCursor_MacroExpansion)
6213 return clang_getCursorReferenced(C);
6214
6215 if (!clang_isDeclaration(C.kind))
6216 return clang_getNullCursor();
6217
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006218 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006219 if (!D)
6220 return clang_getNullCursor();
6221
6222 switch (D->getKind()) {
6223 // Declaration kinds that don't really separate the notions of
6224 // declaration and definition.
6225 case Decl::Namespace:
6226 case Decl::Typedef:
6227 case Decl::TypeAlias:
6228 case Decl::TypeAliasTemplate:
6229 case Decl::TemplateTypeParm:
6230 case Decl::EnumConstant:
6231 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006232 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006233 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006234 case Decl::IndirectField:
6235 case Decl::ObjCIvar:
6236 case Decl::ObjCAtDefsField:
6237 case Decl::ImplicitParam:
6238 case Decl::ParmVar:
6239 case Decl::NonTypeTemplateParm:
6240 case Decl::TemplateTemplateParm:
6241 case Decl::ObjCCategoryImpl:
6242 case Decl::ObjCImplementation:
6243 case Decl::AccessSpec:
6244 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006245 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006246 case Decl::ObjCPropertyImpl:
6247 case Decl::FileScopeAsm:
6248 case Decl::StaticAssert:
6249 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006250 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006251 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006252 case Decl::Label: // FIXME: Is this right??
6253 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006254 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006255 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006256 case Decl::OMPThreadPrivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00006257 case Decl::OMPAllocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006258 case Decl::OMPDeclareReduction:
Michael Kruse251e1482019-02-01 20:25:04 +00006259 case Decl::OMPDeclareMapper:
Kelvin Li1408f912018-09-26 04:28:39 +00006260 case Decl::OMPRequires:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006261 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006262 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006263 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006264 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006265 case Decl::UsingPack:
Guy Benyei11169dd2012-12-18 14:30:41 +00006266 return C;
6267
6268 // Declaration kinds that don't make any sense here, but are
6269 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006270 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006271 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006272 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006273 break;
6274
6275 // Declaration kinds for which the definition is not resolvable.
6276 case Decl::UnresolvedUsingTypename:
6277 case Decl::UnresolvedUsingValue:
6278 break;
6279
6280 case Decl::UsingDirective:
6281 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6282 TU);
6283
6284 case Decl::NamespaceAlias:
6285 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6286
6287 case Decl::Enum:
6288 case Decl::Record:
6289 case Decl::CXXRecord:
6290 case Decl::ClassTemplateSpecialization:
6291 case Decl::ClassTemplatePartialSpecialization:
6292 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6293 return MakeCXCursor(Def, TU);
6294 return clang_getNullCursor();
6295
6296 case Decl::Function:
6297 case Decl::CXXMethod:
6298 case Decl::CXXConstructor:
6299 case Decl::CXXDestructor:
6300 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006301 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006302 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006303 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006304 return clang_getNullCursor();
6305 }
6306
Larisse Voufo39a1e502013-08-06 01:03:05 +00006307 case Decl::Var:
6308 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006309 case Decl::VarTemplatePartialSpecialization:
6310 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006311 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006312 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006313 return MakeCXCursor(Def, TU);
6314 return clang_getNullCursor();
6315 }
6316
6317 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006318 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006319 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6320 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6321 return clang_getNullCursor();
6322 }
6323
6324 case Decl::ClassTemplate: {
6325 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6326 ->getDefinition())
6327 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6328 TU);
6329 return clang_getNullCursor();
6330 }
6331
Larisse Voufo39a1e502013-08-06 01:03:05 +00006332 case Decl::VarTemplate: {
6333 if (VarDecl *Def =
6334 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6335 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6336 return clang_getNullCursor();
6337 }
6338
Guy Benyei11169dd2012-12-18 14:30:41 +00006339 case Decl::Using:
6340 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6341 D->getLocation(), TU);
6342
6343 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006344 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006345 return clang_getCursorDefinition(
6346 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6347 TU));
6348
6349 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006350 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006351 if (Method->isThisDeclarationADefinition())
6352 return C;
6353
6354 // Dig out the method definition in the associated
6355 // @implementation, if we have it.
6356 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006357 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006358 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6359 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6360 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6361 Method->isInstanceMethod()))
6362 if (Def->isThisDeclarationADefinition())
6363 return MakeCXCursor(Def, TU);
6364
6365 return clang_getNullCursor();
6366 }
6367
6368 case Decl::ObjCCategory:
6369 if (ObjCCategoryImplDecl *Impl
6370 = cast<ObjCCategoryDecl>(D)->getImplementation())
6371 return MakeCXCursor(Impl, TU);
6372 return clang_getNullCursor();
6373
6374 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006375 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006376 return MakeCXCursor(Def, TU);
6377 return clang_getNullCursor();
6378
6379 case Decl::ObjCInterface: {
6380 // There are two notions of a "definition" for an Objective-C
6381 // class: the interface and its implementation. When we resolved a
6382 // reference to an Objective-C class, produce the @interface as
6383 // the definition; when we were provided with the interface,
6384 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006385 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006386 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006387 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006388 return MakeCXCursor(Def, TU);
6389 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6390 return MakeCXCursor(Impl, TU);
6391 return clang_getNullCursor();
6392 }
6393
6394 case Decl::ObjCProperty:
6395 // FIXME: We don't really know where to find the
6396 // ObjCPropertyImplDecls that implement this property.
6397 return clang_getNullCursor();
6398
6399 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006400 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006401 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006402 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006403 return MakeCXCursor(Def, TU);
6404
6405 return clang_getNullCursor();
6406
6407 case Decl::Friend:
6408 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6409 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6410 return clang_getNullCursor();
6411
6412 case Decl::FriendTemplate:
6413 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6414 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6415 return clang_getNullCursor();
6416 }
6417
6418 return clang_getNullCursor();
6419}
6420
6421unsigned clang_isCursorDefinition(CXCursor C) {
6422 if (!clang_isDeclaration(C.kind))
6423 return 0;
6424
6425 return clang_getCursorDefinition(C) == C;
6426}
6427
6428CXCursor clang_getCanonicalCursor(CXCursor C) {
6429 if (!clang_isDeclaration(C.kind))
6430 return C;
6431
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006432 if (const Decl *D = getCursorDecl(C)) {
6433 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006434 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6435 return MakeCXCursor(CatD, getCursorTU(C));
6436
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006437 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6438 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006439 return MakeCXCursor(IFD, getCursorTU(C));
6440
6441 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6442 }
6443
6444 return C;
6445}
6446
6447int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6448 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6449}
6450
6451unsigned clang_getNumOverloadedDecls(CXCursor C) {
6452 if (C.kind != CXCursor_OverloadedDeclRef)
6453 return 0;
6454
6455 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006456 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006457 return E->getNumDecls();
6458
6459 if (OverloadedTemplateStorage *S
6460 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6461 return S->size();
6462
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006463 const Decl *D = Storage.get<const Decl *>();
6464 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006465 return Using->shadow_size();
6466
6467 return 0;
6468}
6469
6470CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6471 if (cursor.kind != CXCursor_OverloadedDeclRef)
6472 return clang_getNullCursor();
6473
6474 if (index >= clang_getNumOverloadedDecls(cursor))
6475 return clang_getNullCursor();
6476
6477 CXTranslationUnit TU = getCursorTU(cursor);
6478 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006479 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006480 return MakeCXCursor(E->decls_begin()[index], TU);
6481
6482 if (OverloadedTemplateStorage *S
6483 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6484 return MakeCXCursor(S->begin()[index], TU);
6485
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006486 const Decl *D = Storage.get<const Decl *>();
6487 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006488 // FIXME: This is, unfortunately, linear time.
6489 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6490 std::advance(Pos, index);
6491 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6492 }
6493
6494 return clang_getNullCursor();
6495}
6496
6497void clang_getDefinitionSpellingAndExtent(CXCursor C,
6498 const char **startBuf,
6499 const char **endBuf,
6500 unsigned *startLine,
6501 unsigned *startColumn,
6502 unsigned *endLine,
6503 unsigned *endColumn) {
6504 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006505 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006506 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6507
6508 SourceManager &SM = FD->getASTContext().getSourceManager();
6509 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6510 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6511 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6512 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6513 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6514 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6515}
6516
6517
6518CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6519 unsigned PieceIndex) {
6520 RefNamePieces Pieces;
6521
6522 switch (C.kind) {
6523 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006524 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006525 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6526 E->getQualifierLoc().getSourceRange());
6527 break;
6528
6529 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006530 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6531 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6532 Pieces =
6533 buildPieces(NameFlags, false, E->getNameInfo(),
6534 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6535 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006536 break;
6537
6538 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006539 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006540 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006541 const Expr *Callee = OCE->getCallee();
6542 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006543 Callee = ICE->getSubExpr();
6544
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006545 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006546 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6547 DRE->getQualifierLoc().getSourceRange());
6548 }
6549 break;
6550
6551 default:
6552 break;
6553 }
6554
6555 if (Pieces.empty()) {
6556 if (PieceIndex == 0)
6557 return clang_getCursorExtent(C);
6558 } else if (PieceIndex < Pieces.size()) {
6559 SourceRange R = Pieces[PieceIndex];
6560 if (R.isValid())
6561 return cxloc::translateSourceRange(getCursorContext(C), R);
6562 }
6563
6564 return clang_getNullRange();
6565}
6566
6567void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006568 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6569 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006570}
6571
6572void clang_executeOnThread(void (*fn)(void*), void *user_data,
6573 unsigned stack_size) {
6574 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6575}
6576
Guy Benyei11169dd2012-12-18 14:30:41 +00006577//===----------------------------------------------------------------------===//
6578// Token-based Operations.
6579//===----------------------------------------------------------------------===//
6580
6581/* CXToken layout:
6582 * int_data[0]: a CXTokenKind
6583 * int_data[1]: starting token location
6584 * int_data[2]: token length
6585 * int_data[3]: reserved
6586 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6587 * otherwise unused.
6588 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006589CXTokenKind clang_getTokenKind(CXToken CXTok) {
6590 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6591}
6592
6593CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6594 switch (clang_getTokenKind(CXTok)) {
6595 case CXToken_Identifier:
6596 case CXToken_Keyword:
6597 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006598 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006599 ->getNameStart());
6600
6601 case CXToken_Literal: {
6602 // We have stashed the starting pointer in the ptr_data field. Use it.
6603 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006604 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006605 }
6606
6607 case CXToken_Punctuation:
6608 case CXToken_Comment:
6609 break;
6610 }
6611
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006612 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006613 LOG_BAD_TU(TU);
6614 return cxstring::createEmpty();
6615 }
6616
Guy Benyei11169dd2012-12-18 14:30:41 +00006617 // We have to find the starting buffer pointer the hard way, by
6618 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006619 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006620 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006621 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006622
6623 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6624 std::pair<FileID, unsigned> LocInfo
6625 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6626 bool Invalid = false;
6627 StringRef Buffer
6628 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6629 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006630 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006631
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006632 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006633}
6634
6635CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006636 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006637 LOG_BAD_TU(TU);
6638 return clang_getNullLocation();
6639 }
6640
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006641 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006642 if (!CXXUnit)
6643 return clang_getNullLocation();
6644
6645 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6646 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6647}
6648
6649CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006650 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006651 LOG_BAD_TU(TU);
6652 return clang_getNullRange();
6653 }
6654
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006655 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006656 if (!CXXUnit)
6657 return clang_getNullRange();
6658
6659 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6660 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6661}
6662
6663static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6664 SmallVectorImpl<CXToken> &CXTokens) {
6665 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6666 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006667 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006668 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006669 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006670
6671 // Cannot tokenize across files.
6672 if (BeginLocInfo.first != EndLocInfo.first)
6673 return;
6674
6675 // Create a lexer
6676 bool Invalid = false;
6677 StringRef Buffer
6678 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6679 if (Invalid)
6680 return;
6681
6682 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6683 CXXUnit->getASTContext().getLangOpts(),
6684 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6685 Lex.SetCommentRetentionState(true);
6686
6687 // Lex tokens until we hit the end of the range.
6688 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6689 Token Tok;
6690 bool previousWasAt = false;
6691 do {
6692 // Lex the next token
6693 Lex.LexFromRawLexer(Tok);
6694 if (Tok.is(tok::eof))
6695 break;
6696
6697 // Initialize the CXToken.
6698 CXToken CXTok;
6699
6700 // - Common fields
6701 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6702 CXTok.int_data[2] = Tok.getLength();
6703 CXTok.int_data[3] = 0;
6704
6705 // - Kind-specific fields
6706 if (Tok.isLiteral()) {
6707 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006708 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006709 } else if (Tok.is(tok::raw_identifier)) {
6710 // Lookup the identifier to determine whether we have a keyword.
6711 IdentifierInfo *II
6712 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6713
6714 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6715 CXTok.int_data[0] = CXToken_Keyword;
6716 }
6717 else {
6718 CXTok.int_data[0] = Tok.is(tok::identifier)
6719 ? CXToken_Identifier
6720 : CXToken_Keyword;
6721 }
6722 CXTok.ptr_data = II;
6723 } else if (Tok.is(tok::comment)) {
6724 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006725 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006726 } else {
6727 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006728 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006729 }
6730 CXTokens.push_back(CXTok);
6731 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006732 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006733}
6734
Ivan Donchevskii3957e482018-06-13 12:37:08 +00006735CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6736 LOG_FUNC_SECTION {
6737 *Log << TU << ' ' << Location;
6738 }
6739
6740 if (isNotUsableTU(TU)) {
6741 LOG_BAD_TU(TU);
6742 return NULL;
6743 }
6744
6745 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6746 if (!CXXUnit)
6747 return NULL;
6748
6749 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6750 if (Begin.isInvalid())
6751 return NULL;
6752 SourceManager &SM = CXXUnit->getSourceManager();
6753 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6754 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6755
6756 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6757
6758 SmallVector<CXToken, 32> CXTokens;
6759 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6760
6761 if (CXTokens.empty())
6762 return NULL;
6763
6764 CXTokens.resize(1);
6765 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6766
6767 memmove(Token, CXTokens.data(), sizeof(CXToken));
6768 return Token;
6769}
6770
Guy Benyei11169dd2012-12-18 14:30:41 +00006771void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6772 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006773 LOG_FUNC_SECTION {
6774 *Log << TU << ' ' << Range;
6775 }
6776
Guy Benyei11169dd2012-12-18 14:30:41 +00006777 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006778 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006779 if (NumTokens)
6780 *NumTokens = 0;
6781
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006782 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006783 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006784 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006785 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006786
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006787 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006788 if (!CXXUnit || !Tokens || !NumTokens)
6789 return;
6790
6791 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6792
6793 SourceRange R = cxloc::translateCXSourceRange(Range);
6794 if (R.isInvalid())
6795 return;
6796
6797 SmallVector<CXToken, 32> CXTokens;
6798 getTokens(CXXUnit, R, CXTokens);
6799
6800 if (CXTokens.empty())
6801 return;
6802
Serge Pavlov52525732018-02-21 02:02:39 +00006803 *Tokens = static_cast<CXToken *>(
6804 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006805 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6806 *NumTokens = CXTokens.size();
6807}
6808
6809void clang_disposeTokens(CXTranslationUnit TU,
6810 CXToken *Tokens, unsigned NumTokens) {
6811 free(Tokens);
6812}
6813
Guy Benyei11169dd2012-12-18 14:30:41 +00006814//===----------------------------------------------------------------------===//
6815// Token annotation APIs.
6816//===----------------------------------------------------------------------===//
6817
Guy Benyei11169dd2012-12-18 14:30:41 +00006818static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6819 CXCursor parent,
6820 CXClientData client_data);
6821static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6822 CXClientData client_data);
6823
6824namespace {
6825class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006826 CXToken *Tokens;
6827 CXCursor *Cursors;
6828 unsigned NumTokens;
6829 unsigned TokIdx;
6830 unsigned PreprocessingTokIdx;
6831 CursorVisitor AnnotateVis;
6832 SourceManager &SrcMgr;
6833 bool HasContextSensitiveKeywords;
6834
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006835 struct PostChildrenAction {
6836 CXCursor cursor;
6837 enum Action { Invalid, Ignore, Postpone } action;
6838 };
6839 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
6840
Guy Benyei11169dd2012-12-18 14:30:41 +00006841 struct PostChildrenInfo {
6842 CXCursor Cursor;
6843 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006844 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006845 unsigned BeforeChildrenTokenIdx;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006846 PostChildrenActions ChildActions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006847 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006848 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006849
6850 CXToken &getTok(unsigned Idx) {
6851 assert(Idx < NumTokens);
6852 return Tokens[Idx];
6853 }
6854 const CXToken &getTok(unsigned Idx) const {
6855 assert(Idx < NumTokens);
6856 return Tokens[Idx];
6857 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006858 bool MoreTokens() const { return TokIdx < NumTokens; }
6859 unsigned NextToken() const { return TokIdx; }
6860 void AdvanceToken() { ++TokIdx; }
6861 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006862 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006863 }
6864 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006865 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006866 }
6867 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006868 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006869 }
6870
6871 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006872 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006873 SourceRange);
6874
6875public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006876 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006877 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006878 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006879 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006880 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006881 AnnotateTokensVisitor, this,
6882 /*VisitPreprocessorLast=*/true,
6883 /*VisitIncludedEntities=*/false,
6884 RegionOfInterest,
6885 /*VisitDeclsOnly=*/false,
6886 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006887 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006888 HasContextSensitiveKeywords(false) { }
6889
6890 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6891 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006892 bool IsIgnoredChildCursor(CXCursor cursor) const;
6893 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
6894
Guy Benyei11169dd2012-12-18 14:30:41 +00006895 bool postVisitChildren(CXCursor cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006896 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
6897 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
6898
Guy Benyei11169dd2012-12-18 14:30:41 +00006899 void AnnotateTokens();
6900
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006901 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00006902 /// context-sensitive keywords.
6903 bool hasContextSensitiveKeywords() const {
6904 return HasContextSensitiveKeywords;
6905 }
6906
6907 ~AnnotateTokensWorker() {
6908 assert(PostChildrenInfos.empty());
6909 }
6910};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006911}
Guy Benyei11169dd2012-12-18 14:30:41 +00006912
6913void AnnotateTokensWorker::AnnotateTokens() {
6914 // Walk the AST within the region of interest, annotating tokens
6915 // along the way.
6916 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006917}
Guy Benyei11169dd2012-12-18 14:30:41 +00006918
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006919bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
6920 if (PostChildrenInfos.empty())
6921 return false;
6922
6923 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
6924 if (ChildAction.cursor == cursor &&
6925 ChildAction.action == PostChildrenAction::Ignore) {
6926 return true;
6927 }
6928 }
6929
6930 return false;
6931}
6932
6933const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
6934 if (!clang_isExpression(Cursor.kind))
6935 return nullptr;
6936
6937 const Expr *E = getCursorExpr(Cursor);
6938 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
6939 const OverloadedOperatorKind Kind = OCE->getOperator();
6940 if (Kind == OO_Call || Kind == OO_Subscript)
6941 return OCE;
6942 }
6943
6944 return nullptr;
6945}
6946
6947AnnotateTokensWorker::PostChildrenActions
6948AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
6949 PostChildrenActions actions;
6950
6951 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
6952 // visited before the arguments to the operator call. For the Call and
6953 // Subscript operator the range of this DeclRefExpr includes the whole call
6954 // expression, so that all tokens in that range would be mapped to the
6955 // operator function, including the tokens of the arguments. To avoid that,
6956 // ensure to visit this DeclRefExpr as last node.
6957 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
6958 const Expr *Callee = OCE->getCallee();
6959 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
6960 const Expr *SubExpr = ICE->getSubExpr();
6961 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
Fangrui Songcabb36d2018-11-20 08:00:00 +00006962 const Decl *parentDecl = getCursorDecl(Cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006963 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
6964
6965 // Visit the DeclRefExpr as last.
6966 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
6967 actions.push_back({cxChild, PostChildrenAction::Postpone});
6968
6969 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
6970 // wide range as the DeclRefExpr. We can skip visiting this entirely.
6971 cxChild = MakeCXCursor(ICE, parentDecl, TU);
6972 actions.push_back({cxChild, PostChildrenAction::Ignore});
6973 }
6974 }
6975 }
6976
6977 return actions;
6978}
6979
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006980static inline void updateCursorAnnotation(CXCursor &Cursor,
6981 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006982 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006983 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006984 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006985}
6986
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006987/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00006988//// between the cursor location and the source range is the same as
6989/// \arg compResult.
6990///
6991/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6992/// Pass RangeOverlap to annotate tokens inside a range.
6993void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6994 RangeComparisonResult compResult,
6995 SourceRange range) {
6996 while (MoreTokens()) {
6997 const unsigned I = NextToken();
6998 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006999 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
7000 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00007001
7002 SourceLocation TokLoc = GetTokenLoc(I);
7003 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007004 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007005 AdvanceToken();
7006 continue;
7007 }
7008 break;
7009 }
7010}
7011
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007012/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007013/// \returns true if it advanced beyond all macro tokens, false otherwise.
7014bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00007015 CXCursor updateC,
7016 RangeComparisonResult compResult,
7017 SourceRange range) {
7018 assert(MoreTokens());
7019 assert(isFunctionMacroToken(NextToken()) &&
7020 "Should be called only for macro arg tokens");
7021
7022 // This works differently than annotateAndAdvanceTokens; because expanded
7023 // macro arguments can have arbitrary translation-unit source order, we do not
7024 // advance the token index one by one until a token fails the range test.
7025 // We only advance once past all of the macro arg tokens if all of them
7026 // pass the range test. If one of them fails we keep the token index pointing
7027 // at the start of the macro arg tokens so that the failing token will be
7028 // annotated by a subsequent annotation try.
7029
7030 bool atLeastOneCompFail = false;
7031
7032 unsigned I = NextToken();
7033 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7034 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7035 if (TokLoc.isFileID())
7036 continue; // not macro arg token, it's parens or comma.
7037 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7038 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7039 Cursors[I] = updateC;
7040 } else
7041 atLeastOneCompFail = true;
7042 }
7043
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007044 if (atLeastOneCompFail)
7045 return false;
7046
7047 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7048 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00007049}
7050
7051enum CXChildVisitResult
7052AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007053 SourceRange cursorRange = getRawCursorExtent(cursor);
7054 if (cursorRange.isInvalid())
7055 return CXChildVisit_Recurse;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007056
7057 if (IsIgnoredChildCursor(cursor))
7058 return CXChildVisit_Continue;
7059
Guy Benyei11169dd2012-12-18 14:30:41 +00007060 if (!HasContextSensitiveKeywords) {
7061 // Objective-C properties can have context-sensitive keywords.
7062 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007063 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007064 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7065 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7066 }
7067 // Objective-C methods can have context-sensitive keywords.
7068 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7069 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007070 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007071 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7072 if (Method->getObjCDeclQualifier())
7073 HasContextSensitiveKeywords = true;
7074 else {
David Majnemer59f77922016-06-24 04:05:48 +00007075 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00007076 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007077 HasContextSensitiveKeywords = true;
7078 break;
7079 }
7080 }
7081 }
7082 }
7083 }
7084 // C++ methods can have context-sensitive keywords.
7085 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007086 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007087 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7088 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7089 HasContextSensitiveKeywords = true;
7090 }
7091 }
7092 // C++ classes can have context-sensitive keywords.
7093 else if (cursor.kind == CXCursor_StructDecl ||
7094 cursor.kind == CXCursor_ClassDecl ||
7095 cursor.kind == CXCursor_ClassTemplate ||
7096 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007097 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007098 if (D->hasAttr<FinalAttr>())
7099 HasContextSensitiveKeywords = true;
7100 }
7101 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00007102
7103 // Don't override a property annotation with its getter/setter method.
7104 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7105 parent.kind == CXCursor_ObjCPropertyDecl)
7106 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007107
7108 if (clang_isPreprocessing(cursor.kind)) {
7109 // Items in the preprocessing record are kept separate from items in
7110 // declarations, so we keep a separate token index.
7111 unsigned SavedTokIdx = TokIdx;
7112 TokIdx = PreprocessingTokIdx;
7113
7114 // Skip tokens up until we catch up to the beginning of the preprocessing
7115 // entry.
7116 while (MoreTokens()) {
7117 const unsigned I = NextToken();
7118 SourceLocation TokLoc = GetTokenLoc(I);
7119 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7120 case RangeBefore:
7121 AdvanceToken();
7122 continue;
7123 case RangeAfter:
7124 case RangeOverlap:
7125 break;
7126 }
7127 break;
7128 }
7129
7130 // Look at all of the tokens within this range.
7131 while (MoreTokens()) {
7132 const unsigned I = NextToken();
7133 SourceLocation TokLoc = GetTokenLoc(I);
7134 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7135 case RangeBefore:
7136 llvm_unreachable("Infeasible");
7137 case RangeAfter:
7138 break;
7139 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007140 // For macro expansions, just note where the beginning of the macro
7141 // expansion occurs.
7142 if (cursor.kind == CXCursor_MacroExpansion) {
7143 if (TokLoc == cursorRange.getBegin())
7144 Cursors[I] = cursor;
7145 AdvanceToken();
7146 break;
7147 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007148 // We may have already annotated macro names inside macro definitions.
7149 if (Cursors[I].kind != CXCursor_MacroExpansion)
7150 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007151 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007152 continue;
7153 }
7154 break;
7155 }
7156
7157 // Save the preprocessing token index; restore the non-preprocessing
7158 // token index.
7159 PreprocessingTokIdx = TokIdx;
7160 TokIdx = SavedTokIdx;
7161 return CXChildVisit_Recurse;
7162 }
7163
7164 if (cursorRange.isInvalid())
7165 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007166
7167 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007168 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007169 const enum CXCursorKind K = clang_getCursorKind(parent);
7170 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007171 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7172 // Attributes are annotated out-of-order, skip tokens until we reach it.
7173 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007174 ? clang_getNullCursor() : parent;
7175
7176 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7177
7178 // Avoid having the cursor of an expression "overwrite" the annotation of the
7179 // variable declaration that it belongs to.
7180 // This can happen for C++ constructor expressions whose range generally
7181 // include the variable declaration, e.g.:
7182 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007183 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00007184 const Expr *E = getCursorExpr(cursor);
Fangrui Songcabb36d2018-11-20 08:00:00 +00007185 if (const Decl *D = getCursorDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007186 const unsigned I = NextToken();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007187 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7188 E->getBeginLoc() == D->getLocation() &&
7189 E->getBeginLoc() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007190 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007191 AdvanceToken();
7192 }
7193 }
7194 }
7195
7196 // Before recursing into the children keep some state that we are going
7197 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7198 // extra work after the child nodes are visited.
7199 // Note that we don't call VisitChildren here to avoid traversing statements
7200 // code-recursively which can blow the stack.
7201
7202 PostChildrenInfo Info;
7203 Info.Cursor = cursor;
7204 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007205 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007206 Info.BeforeChildrenTokenIdx = NextToken();
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007207 Info.ChildActions = DetermineChildActions(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007208 PostChildrenInfos.push_back(Info);
7209
7210 return CXChildVisit_Recurse;
7211}
7212
7213bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7214 if (PostChildrenInfos.empty())
7215 return false;
7216 const PostChildrenInfo &Info = PostChildrenInfos.back();
7217 if (!clang_equalCursors(Info.Cursor, cursor))
7218 return false;
7219
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007220 HandlePostPonedChildCursors(Info);
7221
Guy Benyei11169dd2012-12-18 14:30:41 +00007222 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7223 const unsigned AfterChildren = NextToken();
7224 SourceRange cursorRange = Info.CursorRange;
7225
7226 // Scan the tokens that are at the end of the cursor, but are not captured
7227 // but the child cursors.
7228 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7229
7230 // Scan the tokens that are at the beginning of the cursor, but are not
7231 // capture by the child cursors.
7232 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7233 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7234 break;
7235
7236 Cursors[I] = cursor;
7237 }
7238
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007239 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7240 // encountered the attribute cursor.
7241 if (clang_isAttribute(cursor.kind))
7242 TokIdx = Info.BeforeReachingCursorIdx;
7243
Guy Benyei11169dd2012-12-18 14:30:41 +00007244 PostChildrenInfos.pop_back();
7245 return false;
7246}
7247
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007248void AnnotateTokensWorker::HandlePostPonedChildCursors(
7249 const PostChildrenInfo &Info) {
7250 for (const auto &ChildAction : Info.ChildActions) {
7251 if (ChildAction.action == PostChildrenAction::Postpone) {
7252 HandlePostPonedChildCursor(ChildAction.cursor,
7253 Info.BeforeChildrenTokenIdx);
7254 }
7255 }
7256}
7257
7258void AnnotateTokensWorker::HandlePostPonedChildCursor(
7259 CXCursor Cursor, unsigned StartTokenIndex) {
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007260 unsigned I = StartTokenIndex;
7261
7262 // The bracket tokens of a Call or Subscript operator are mapped to
7263 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7264 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7265 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
Nikolai Kosjar2a647e72019-05-08 13:19:29 +00007266 const CXSourceRange CXRefNameRange = clang_getCursorReferenceNameRange(
7267 Cursor, CXNameRange_WantQualifier, RefNameRangeNr);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007268 if (clang_Range_isNull(CXRefNameRange))
7269 break; // All ranges handled.
7270
7271 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7272 while (I < NumTokens) {
7273 const SourceLocation TokenLocation = GetTokenLoc(I);
7274 if (!TokenLocation.isValid())
7275 break;
7276
7277 // Adapt the end range, because LocationCompare() reports
7278 // RangeOverlap even for the not-inclusive end location.
7279 const SourceLocation fixedEnd =
7280 RefNameRange.getEnd().getLocWithOffset(-1);
7281 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7282
7283 const RangeComparisonResult ComparisonResult =
7284 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7285
7286 if (ComparisonResult == RangeOverlap) {
7287 Cursors[I++] = Cursor;
7288 } else if (ComparisonResult == RangeBefore) {
7289 ++I; // Not relevant token, check next one.
7290 } else if (ComparisonResult == RangeAfter) {
7291 break; // All tokens updated for current range, check next.
7292 }
7293 }
7294 }
7295}
7296
Guy Benyei11169dd2012-12-18 14:30:41 +00007297static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7298 CXCursor parent,
7299 CXClientData client_data) {
7300 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7301}
7302
7303static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7304 CXClientData client_data) {
7305 return static_cast<AnnotateTokensWorker*>(client_data)->
7306 postVisitChildren(cursor);
7307}
7308
7309namespace {
7310
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007311/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007312/// and mark tokens that are macro arguments. This info is used by the
7313/// AnnotateTokensWorker.
7314class MarkMacroArgTokensVisitor {
7315 SourceManager &SM;
7316 CXToken *Tokens;
7317 unsigned NumTokens;
7318 unsigned CurIdx;
7319
7320public:
7321 MarkMacroArgTokensVisitor(SourceManager &SM,
7322 CXToken *tokens, unsigned numTokens)
7323 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7324
7325 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7326 if (cursor.kind != CXCursor_MacroExpansion)
7327 return CXChildVisit_Continue;
7328
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007329 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007330 if (macroRange.getBegin() == macroRange.getEnd())
7331 return CXChildVisit_Continue; // it's not a function macro.
7332
7333 for (; CurIdx < NumTokens; ++CurIdx) {
7334 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7335 macroRange.getBegin()))
7336 break;
7337 }
7338
7339 if (CurIdx == NumTokens)
7340 return CXChildVisit_Break;
7341
7342 for (; CurIdx < NumTokens; ++CurIdx) {
7343 SourceLocation tokLoc = getTokenLoc(CurIdx);
7344 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7345 break;
7346
7347 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7348 }
7349
7350 if (CurIdx == NumTokens)
7351 return CXChildVisit_Break;
7352
7353 return CXChildVisit_Continue;
7354 }
7355
7356private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007357 CXToken &getTok(unsigned Idx) {
7358 assert(Idx < NumTokens);
7359 return Tokens[Idx];
7360 }
7361 const CXToken &getTok(unsigned Idx) const {
7362 assert(Idx < NumTokens);
7363 return Tokens[Idx];
7364 }
7365
Guy Benyei11169dd2012-12-18 14:30:41 +00007366 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007367 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007368 }
7369
7370 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7371 // The third field is reserved and currently not used. Use it here
7372 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007373 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007374 }
7375};
7376
7377} // end anonymous namespace
7378
7379static CXChildVisitResult
7380MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7381 CXClientData client_data) {
7382 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7383 parent);
7384}
7385
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007386/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007387/// \returns true if lexing was finished, false otherwise.
7388static bool lexNext(Lexer &Lex, Token &Tok,
7389 unsigned &NextIdx, unsigned NumTokens) {
7390 if (NextIdx >= NumTokens)
7391 return true;
7392
7393 ++NextIdx;
7394 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007395 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007396}
7397
Guy Benyei11169dd2012-12-18 14:30:41 +00007398static void annotatePreprocessorTokens(CXTranslationUnit TU,
7399 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007400 CXCursor *Cursors,
7401 CXToken *Tokens,
7402 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007403 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007404
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007405 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007406 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7407 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007408 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007409 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007410 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007411
7412 if (BeginLocInfo.first != EndLocInfo.first)
7413 return;
7414
7415 StringRef Buffer;
7416 bool Invalid = false;
7417 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7418 if (Buffer.empty() || Invalid)
7419 return;
7420
7421 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7422 CXXUnit->getASTContext().getLangOpts(),
7423 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7424 Buffer.end());
7425 Lex.SetCommentRetentionState(true);
7426
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007427 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007428 // Lex tokens in raw mode until we hit the end of the range, to avoid
7429 // entering #includes or expanding macros.
7430 while (true) {
7431 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007432 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7433 break;
7434 unsigned TokIdx = NextIdx-1;
7435 assert(Tok.getLocation() ==
7436 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007437
7438 reprocess:
7439 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007440 // We have found a preprocessing directive. Annotate the tokens
7441 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007442 //
7443 // FIXME: Some simple tests here could identify macro definitions and
7444 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007445
7446 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007447 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7448 break;
7449
Craig Topper69186e72014-06-08 08:38:04 +00007450 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007451 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007452 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7453 break;
7454
7455 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007456 IdentifierInfo &II =
7457 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007458 SourceLocation MappedTokLoc =
7459 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7460 MI = getMacroInfo(II, MappedTokLoc, TU);
7461 }
7462 }
7463
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007464 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007465 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007466 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7467 finished = true;
7468 break;
7469 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007470 // If we are in a macro definition, check if the token was ever a
7471 // macro name and annotate it if that's the case.
7472 if (MI) {
7473 SourceLocation SaveLoc = Tok.getLocation();
7474 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007475 MacroDefinitionRecord *MacroDef =
7476 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007477 Tok.setLocation(SaveLoc);
7478 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007479 Cursors[NextIdx - 1] =
7480 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007481 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007482 } while (!Tok.isAtStartOfLine());
7483
7484 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7485 assert(TokIdx <= LastIdx);
7486 SourceLocation EndLoc =
7487 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7488 CXCursor Cursor =
7489 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7490
7491 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007492 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007493
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007494 if (finished)
7495 break;
7496 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007497 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007498 }
7499}
7500
7501// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007502static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7503 CXToken *Tokens, unsigned NumTokens,
7504 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007505 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007506 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7507 setThreadBackgroundPriority();
7508
7509 // Determine the region of interest, which contains all of the tokens.
7510 SourceRange RegionOfInterest;
7511 RegionOfInterest.setBegin(
7512 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7513 RegionOfInterest.setEnd(
7514 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7515 Tokens[NumTokens-1])));
7516
Guy Benyei11169dd2012-12-18 14:30:41 +00007517 // Relex the tokens within the source range to look for preprocessing
7518 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007519 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007520
7521 // If begin location points inside a macro argument, set it to the expansion
7522 // location so we can have the full context when annotating semantically.
7523 {
7524 SourceManager &SM = CXXUnit->getSourceManager();
7525 SourceLocation Loc =
7526 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7527 if (Loc.isMacroID())
7528 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7529 }
7530
Guy Benyei11169dd2012-12-18 14:30:41 +00007531 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7532 // Search and mark tokens that are macro argument expansions.
7533 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7534 Tokens, NumTokens);
7535 CursorVisitor MacroArgMarker(TU,
7536 MarkMacroArgTokensVisitorDelegate, &Visitor,
7537 /*VisitPreprocessorLast=*/true,
7538 /*VisitIncludedEntities=*/false,
7539 RegionOfInterest);
7540 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7541 }
7542
7543 // Annotate all of the source locations in the region of interest that map to
7544 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007545 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007546
7547 // FIXME: We use a ridiculous stack size here because the data-recursion
7548 // algorithm uses a large stack frame than the non-data recursive version,
7549 // and AnnotationTokensWorker currently transforms the data-recursion
7550 // algorithm back into a traditional recursion by explicitly calling
7551 // VisitChildren(). We will need to remove this explicit recursive call.
7552 W.AnnotateTokens();
7553
7554 // If we ran into any entities that involve context-sensitive keywords,
7555 // take another pass through the tokens to mark them as such.
7556 if (W.hasContextSensitiveKeywords()) {
7557 for (unsigned I = 0; I != NumTokens; ++I) {
7558 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7559 continue;
7560
7561 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7562 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007563 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007564 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7565 if (Property->getPropertyAttributesAsWritten() != 0 &&
7566 llvm::StringSwitch<bool>(II->getName())
7567 .Case("readonly", true)
7568 .Case("assign", true)
7569 .Case("unsafe_unretained", true)
7570 .Case("readwrite", true)
7571 .Case("retain", true)
7572 .Case("copy", true)
7573 .Case("nonatomic", true)
7574 .Case("atomic", true)
7575 .Case("getter", true)
7576 .Case("setter", true)
7577 .Case("strong", true)
7578 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007579 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007580 .Default(false))
7581 Tokens[I].int_data[0] = CXToken_Keyword;
7582 }
7583 continue;
7584 }
7585
7586 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7587 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7588 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7589 if (llvm::StringSwitch<bool>(II->getName())
7590 .Case("in", true)
7591 .Case("out", true)
7592 .Case("inout", true)
7593 .Case("oneway", true)
7594 .Case("bycopy", true)
7595 .Case("byref", true)
7596 .Default(false))
7597 Tokens[I].int_data[0] = CXToken_Keyword;
7598 continue;
7599 }
7600
7601 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7602 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7603 Tokens[I].int_data[0] = CXToken_Keyword;
7604 continue;
7605 }
7606 }
7607 }
7608}
7609
Guy Benyei11169dd2012-12-18 14:30:41 +00007610void clang_annotateTokens(CXTranslationUnit TU,
7611 CXToken *Tokens, unsigned NumTokens,
7612 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007613 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007614 LOG_BAD_TU(TU);
7615 return;
7616 }
7617 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007618 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007619 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007620 }
7621
7622 LOG_FUNC_SECTION {
7623 *Log << TU << ' ';
7624 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7625 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7626 *Log << clang_getRange(bloc, eloc);
7627 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007628
7629 // Any token we don't specifically annotate will have a NULL cursor.
7630 CXCursor C = clang_getNullCursor();
7631 for (unsigned I = 0; I != NumTokens; ++I)
7632 Cursors[I] = C;
7633
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007634 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007635 if (!CXXUnit)
7636 return;
7637
7638 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007639
7640 auto AnnotateTokensImpl = [=]() {
7641 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7642 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007643 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007644 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007645 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7646 }
7647}
7648
Guy Benyei11169dd2012-12-18 14:30:41 +00007649//===----------------------------------------------------------------------===//
7650// Operations for querying linkage of a cursor.
7651//===----------------------------------------------------------------------===//
7652
Guy Benyei11169dd2012-12-18 14:30:41 +00007653CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7654 if (!clang_isDeclaration(cursor.kind))
7655 return CXLinkage_Invalid;
7656
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007657 const Decl *D = cxcursor::getCursorDecl(cursor);
7658 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007659 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007660 case NoLinkage:
7661 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007662 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007663 case InternalLinkage: return CXLinkage_Internal;
7664 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007665 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007666 case ExternalLinkage: return CXLinkage_External;
7667 };
7668
7669 return CXLinkage_Invalid;
7670}
Guy Benyei11169dd2012-12-18 14:30:41 +00007671
7672//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007673// Operations for querying visibility of a cursor.
7674//===----------------------------------------------------------------------===//
7675
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007676CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7677 if (!clang_isDeclaration(cursor.kind))
7678 return CXVisibility_Invalid;
7679
7680 const Decl *D = cxcursor::getCursorDecl(cursor);
7681 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7682 switch (ND->getVisibility()) {
7683 case HiddenVisibility: return CXVisibility_Hidden;
7684 case ProtectedVisibility: return CXVisibility_Protected;
7685 case DefaultVisibility: return CXVisibility_Default;
7686 };
7687
7688 return CXVisibility_Invalid;
7689}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007690
7691//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007692// Operations for querying language of a cursor.
7693//===----------------------------------------------------------------------===//
7694
7695static CXLanguageKind getDeclLanguage(const Decl *D) {
7696 if (!D)
7697 return CXLanguage_C;
7698
7699 switch (D->getKind()) {
7700 default:
7701 break;
7702 case Decl::ImplicitParam:
7703 case Decl::ObjCAtDefsField:
7704 case Decl::ObjCCategory:
7705 case Decl::ObjCCategoryImpl:
7706 case Decl::ObjCCompatibleAlias:
7707 case Decl::ObjCImplementation:
7708 case Decl::ObjCInterface:
7709 case Decl::ObjCIvar:
7710 case Decl::ObjCMethod:
7711 case Decl::ObjCProperty:
7712 case Decl::ObjCPropertyImpl:
7713 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007714 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007715 return CXLanguage_ObjC;
7716 case Decl::CXXConstructor:
7717 case Decl::CXXConversion:
7718 case Decl::CXXDestructor:
7719 case Decl::CXXMethod:
7720 case Decl::CXXRecord:
7721 case Decl::ClassTemplate:
7722 case Decl::ClassTemplatePartialSpecialization:
7723 case Decl::ClassTemplateSpecialization:
7724 case Decl::Friend:
7725 case Decl::FriendTemplate:
7726 case Decl::FunctionTemplate:
7727 case Decl::LinkageSpec:
7728 case Decl::Namespace:
7729 case Decl::NamespaceAlias:
7730 case Decl::NonTypeTemplateParm:
7731 case Decl::StaticAssert:
7732 case Decl::TemplateTemplateParm:
7733 case Decl::TemplateTypeParm:
7734 case Decl::UnresolvedUsingTypename:
7735 case Decl::UnresolvedUsingValue:
7736 case Decl::Using:
7737 case Decl::UsingDirective:
7738 case Decl::UsingShadow:
7739 return CXLanguage_CPlusPlus;
7740 }
7741
7742 return CXLanguage_C;
7743}
7744
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007745static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7746 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007747 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007748
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007749 switch (D->getAvailability()) {
7750 case AR_Available:
7751 case AR_NotYetIntroduced:
7752 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007753 return getCursorAvailabilityForDecl(
7754 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007755 return CXAvailability_Available;
7756
7757 case AR_Deprecated:
7758 return CXAvailability_Deprecated;
7759
7760 case AR_Unavailable:
7761 return CXAvailability_NotAvailable;
7762 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007763
7764 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007765}
7766
Guy Benyei11169dd2012-12-18 14:30:41 +00007767enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7768 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007769 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7770 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007771
7772 return CXAvailability_Available;
7773}
7774
7775static CXVersion convertVersion(VersionTuple In) {
7776 CXVersion Out = { -1, -1, -1 };
7777 if (In.empty())
7778 return Out;
7779
7780 Out.Major = In.getMajor();
7781
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007782 Optional<unsigned> Minor = In.getMinor();
7783 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007784 Out.Minor = *Minor;
7785 else
7786 return Out;
7787
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007788 Optional<unsigned> Subminor = In.getSubminor();
7789 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007790 Out.Subminor = *Subminor;
7791
7792 return Out;
7793}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007794
Alex Lorenz1345ea22017-06-12 19:06:30 +00007795static void getCursorPlatformAvailabilityForDecl(
7796 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7797 int *always_unavailable, CXString *unavailable_message,
7798 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007799 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007800 for (auto A : D->attrs()) {
7801 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007802 HadAvailAttr = true;
7803 if (always_deprecated)
7804 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007805 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007806 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007807 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007808 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007809 continue;
7810 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007811
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007812 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007813 HadAvailAttr = true;
7814 if (always_unavailable)
7815 *always_unavailable = 1;
7816 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007817 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007818 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7819 }
7820 continue;
7821 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007822
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007823 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007824 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007825 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007826 }
7827 }
7828
7829 if (!HadAvailAttr)
7830 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7831 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007832 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7833 deprecated_message, always_unavailable, unavailable_message,
7834 AvailabilityAttrs);
7835
7836 if (AvailabilityAttrs.empty())
7837 return;
7838
Fangrui Song55fab262018-09-26 22:16:28 +00007839 llvm::sort(AvailabilityAttrs,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007840 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7841 return LHS->getPlatform()->getName() <
7842 RHS->getPlatform()->getName();
Fangrui Song55fab262018-09-26 22:16:28 +00007843 });
Alex Lorenz1345ea22017-06-12 19:06:30 +00007844 ASTContext &Ctx = D->getASTContext();
7845 auto It = std::unique(
7846 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7847 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7848 if (LHS->getPlatform() != RHS->getPlatform())
7849 return false;
7850
7851 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7852 LHS->getDeprecated() == RHS->getDeprecated() &&
7853 LHS->getObsoleted() == RHS->getObsoleted() &&
7854 LHS->getMessage() == RHS->getMessage() &&
7855 LHS->getReplacement() == RHS->getReplacement())
7856 return true;
7857
7858 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7859 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7860 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7861 return false;
7862
7863 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7864 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7865
7866 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7867 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7868 if (LHS->getMessage().empty())
7869 LHS->setMessage(Ctx, RHS->getMessage());
7870 if (LHS->getReplacement().empty())
7871 LHS->setReplacement(Ctx, RHS->getReplacement());
7872 }
7873
7874 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7875 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7876 if (LHS->getMessage().empty())
7877 LHS->setMessage(Ctx, RHS->getMessage());
7878 if (LHS->getReplacement().empty())
7879 LHS->setReplacement(Ctx, RHS->getReplacement());
7880 }
7881
7882 return true;
7883 });
7884 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007885}
7886
Alex Lorenz1345ea22017-06-12 19:06:30 +00007887int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007888 CXString *deprecated_message,
7889 int *always_unavailable,
7890 CXString *unavailable_message,
7891 CXPlatformAvailability *availability,
7892 int availability_size) {
7893 if (always_deprecated)
7894 *always_deprecated = 0;
7895 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007896 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007897 if (always_unavailable)
7898 *always_unavailable = 0;
7899 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007900 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007901
Guy Benyei11169dd2012-12-18 14:30:41 +00007902 if (!clang_isDeclaration(cursor.kind))
7903 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007904
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007905 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007906 if (!D)
7907 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007908
Alex Lorenz1345ea22017-06-12 19:06:30 +00007909 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7910 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7911 always_unavailable, unavailable_message,
7912 AvailabilityAttrs);
7913 for (const auto &Avail :
7914 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7915 .take_front(availability_size))) {
7916 availability[Avail.index()].Platform =
7917 cxstring::createDup(Avail.value()->getPlatform()->getName());
7918 availability[Avail.index()].Introduced =
7919 convertVersion(Avail.value()->getIntroduced());
7920 availability[Avail.index()].Deprecated =
7921 convertVersion(Avail.value()->getDeprecated());
7922 availability[Avail.index()].Obsoleted =
7923 convertVersion(Avail.value()->getObsoleted());
7924 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7925 availability[Avail.index()].Message =
7926 cxstring::createDup(Avail.value()->getMessage());
7927 }
7928
7929 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007930}
Alex Lorenz1345ea22017-06-12 19:06:30 +00007931
Guy Benyei11169dd2012-12-18 14:30:41 +00007932void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7933 clang_disposeString(availability->Platform);
7934 clang_disposeString(availability->Message);
7935}
7936
7937CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7938 if (clang_isDeclaration(cursor.kind))
7939 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7940
7941 return CXLanguage_Invalid;
7942}
7943
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00007944CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7945 const Decl *D = cxcursor::getCursorDecl(cursor);
7946 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7947 switch (VD->getTLSKind()) {
7948 case VarDecl::TLS_None:
7949 return CXTLS_None;
7950 case VarDecl::TLS_Dynamic:
7951 return CXTLS_Dynamic;
7952 case VarDecl::TLS_Static:
7953 return CXTLS_Static;
7954 }
7955 }
7956
7957 return CXTLS_None;
7958}
7959
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007960 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007961 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00007962 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007963static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007964 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007965 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007966
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007967 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007968 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7969 return FunTmpl;
7970
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007971 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007972 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7973 return ClassTmpl;
7974
7975 return D;
7976}
7977
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007978
7979enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7980 StorageClass sc = SC_None;
7981 const Decl *D = getCursorDecl(C);
7982 if (D) {
7983 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7984 sc = FD->getStorageClass();
7985 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7986 sc = VD->getStorageClass();
7987 } else {
7988 return CX_SC_Invalid;
7989 }
7990 } else {
7991 return CX_SC_Invalid;
7992 }
7993 switch (sc) {
7994 case SC_None:
7995 return CX_SC_None;
7996 case SC_Extern:
7997 return CX_SC_Extern;
7998 case SC_Static:
7999 return CX_SC_Static;
8000 case SC_PrivateExtern:
8001 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008002 case SC_Auto:
8003 return CX_SC_Auto;
8004 case SC_Register:
8005 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008006 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00008007 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008008}
8009
Guy Benyei11169dd2012-12-18 14:30:41 +00008010CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
8011 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008012 if (const Decl *D = getCursorDecl(cursor)) {
8013 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008014 if (!DC)
8015 return clang_getNullCursor();
8016
8017 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8018 getCursorTU(cursor));
8019 }
8020 }
8021
8022 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008023 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00008024 return MakeCXCursor(D, getCursorTU(cursor));
8025 }
8026
8027 return clang_getNullCursor();
8028}
8029
8030CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8031 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008032 if (const Decl *D = getCursorDecl(cursor)) {
8033 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008034 if (!DC)
8035 return clang_getNullCursor();
8036
8037 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8038 getCursorTU(cursor));
8039 }
8040 }
8041
8042 // FIXME: Note that we can't easily compute the lexical context of a
8043 // statement or expression, so we return nothing.
8044 return clang_getNullCursor();
8045}
8046
8047CXFile clang_getIncludedFile(CXCursor cursor) {
8048 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00008049 return nullptr;
8050
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008051 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00008052 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00008053}
8054
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008055unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8056 if (C.kind != CXCursor_ObjCPropertyDecl)
8057 return CXObjCPropertyAttr_noattr;
8058
8059 unsigned Result = CXObjCPropertyAttr_noattr;
8060 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8061 ObjCPropertyDecl::PropertyAttributeKind Attr =
8062 PD->getPropertyAttributesAsWritten();
8063
8064#define SET_CXOBJCPROP_ATTR(A) \
8065 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8066 Result |= CXObjCPropertyAttr_##A
8067 SET_CXOBJCPROP_ATTR(readonly);
8068 SET_CXOBJCPROP_ATTR(getter);
8069 SET_CXOBJCPROP_ATTR(assign);
8070 SET_CXOBJCPROP_ATTR(readwrite);
8071 SET_CXOBJCPROP_ATTR(retain);
8072 SET_CXOBJCPROP_ATTR(copy);
8073 SET_CXOBJCPROP_ATTR(nonatomic);
8074 SET_CXOBJCPROP_ATTR(setter);
8075 SET_CXOBJCPROP_ATTR(atomic);
8076 SET_CXOBJCPROP_ATTR(weak);
8077 SET_CXOBJCPROP_ATTR(strong);
8078 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00008079 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008080#undef SET_CXOBJCPROP_ATTR
8081
8082 return Result;
8083}
8084
Michael Wu6e88f532018-08-03 05:38:29 +00008085CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8086 if (C.kind != CXCursor_ObjCPropertyDecl)
8087 return cxstring::createNull();
8088
8089 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8090 Selector sel = PD->getGetterName();
8091 if (sel.isNull())
8092 return cxstring::createNull();
8093
8094 return cxstring::createDup(sel.getAsString());
8095}
8096
8097CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8098 if (C.kind != CXCursor_ObjCPropertyDecl)
8099 return cxstring::createNull();
8100
8101 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8102 Selector sel = PD->getSetterName();
8103 if (sel.isNull())
8104 return cxstring::createNull();
8105
8106 return cxstring::createDup(sel.getAsString());
8107}
8108
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00008109unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8110 if (!clang_isDeclaration(C.kind))
8111 return CXObjCDeclQualifier_None;
8112
8113 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8114 const Decl *D = getCursorDecl(C);
8115 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8116 QT = MD->getObjCDeclQualifier();
8117 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8118 QT = PD->getObjCDeclQualifier();
8119 if (QT == Decl::OBJC_TQ_None)
8120 return CXObjCDeclQualifier_None;
8121
8122 unsigned Result = CXObjCDeclQualifier_None;
8123 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
8124 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
8125 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
8126 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
8127 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
8128 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
8129
8130 return Result;
8131}
8132
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00008133unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8134 if (!clang_isDeclaration(C.kind))
8135 return 0;
8136
8137 const Decl *D = getCursorDecl(C);
8138 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8139 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8140 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8141 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8142
8143 return 0;
8144}
8145
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00008146unsigned clang_Cursor_isVariadic(CXCursor C) {
8147 if (!clang_isDeclaration(C.kind))
8148 return 0;
8149
8150 const Decl *D = getCursorDecl(C);
8151 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8152 return FD->isVariadic();
8153 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8154 return MD->isVariadic();
8155
8156 return 0;
8157}
8158
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008159unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8160 CXString *language, CXString *definedIn,
8161 unsigned *isGenerated) {
8162 if (!clang_isDeclaration(C.kind))
8163 return 0;
8164
8165 const Decl *D = getCursorDecl(C);
8166
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00008167 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008168 if (language)
8169 *language = cxstring::createDup(attr->getLanguage());
8170 if (definedIn)
8171 *definedIn = cxstring::createDup(attr->getDefinedIn());
8172 if (isGenerated)
8173 *isGenerated = attr->getGeneratedDeclaration();
8174 return 1;
8175 }
8176 return 0;
8177}
8178
Guy Benyei11169dd2012-12-18 14:30:41 +00008179CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8180 if (!clang_isDeclaration(C.kind))
8181 return clang_getNullRange();
8182
8183 const Decl *D = getCursorDecl(C);
8184 ASTContext &Context = getCursorContext(C);
8185 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8186 if (!RC)
8187 return clang_getNullRange();
8188
8189 return cxloc::translateSourceRange(Context, RC->getSourceRange());
8190}
8191
8192CXString clang_Cursor_getRawCommentText(CXCursor C) {
8193 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008194 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008195
8196 const Decl *D = getCursorDecl(C);
8197 ASTContext &Context = getCursorContext(C);
8198 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8199 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8200 StringRef();
8201
8202 // Don't duplicate the string because RawText points directly into source
8203 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008204 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008205}
8206
8207CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8208 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008209 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008210
8211 const Decl *D = getCursorDecl(C);
8212 const ASTContext &Context = getCursorContext(C);
8213 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8214
8215 if (RC) {
8216 StringRef BriefText = RC->getBriefText(Context);
8217
8218 // Don't duplicate the string because RawComment ensures that this memory
8219 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008220 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008221 }
8222
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008223 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008224}
8225
Guy Benyei11169dd2012-12-18 14:30:41 +00008226CXModule clang_Cursor_getModule(CXCursor C) {
8227 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008228 if (const ImportDecl *ImportD =
8229 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00008230 return ImportD->getImportedModule();
8231 }
8232
Craig Topper69186e72014-06-08 08:38:04 +00008233 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008234}
8235
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008236CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8237 if (isNotUsableTU(TU)) {
8238 LOG_BAD_TU(TU);
8239 return nullptr;
8240 }
8241 if (!File)
8242 return nullptr;
8243 FileEntry *FE = static_cast<FileEntry *>(File);
8244
8245 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8246 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8247 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8248
Richard Smithfeb54b62014-10-23 02:01:19 +00008249 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008250}
8251
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008252CXFile clang_Module_getASTFile(CXModule CXMod) {
8253 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008254 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008255 Module *Mod = static_cast<Module*>(CXMod);
8256 return const_cast<FileEntry *>(Mod->getASTFile());
8257}
8258
Guy Benyei11169dd2012-12-18 14:30:41 +00008259CXModule clang_Module_getParent(CXModule CXMod) {
8260 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008261 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008262 Module *Mod = static_cast<Module*>(CXMod);
8263 return Mod->Parent;
8264}
8265
8266CXString clang_Module_getName(CXModule CXMod) {
8267 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008268 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008269 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008270 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00008271}
8272
8273CXString clang_Module_getFullName(CXModule CXMod) {
8274 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008275 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008276 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008277 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008278}
8279
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008280int clang_Module_isSystem(CXModule CXMod) {
8281 if (!CXMod)
8282 return 0;
8283 Module *Mod = static_cast<Module*>(CXMod);
8284 return Mod->IsSystem;
8285}
8286
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008287unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8288 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008289 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008290 LOG_BAD_TU(TU);
8291 return 0;
8292 }
8293 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008294 return 0;
8295 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008296 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8297 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8298 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008299}
8300
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008301CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8302 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008303 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008304 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008305 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008306 }
8307 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008308 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008309 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008310 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008311
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008312 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8313 if (Index < TopHeaders.size())
8314 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008315
Craig Topper69186e72014-06-08 08:38:04 +00008316 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008317}
8318
Guy Benyei11169dd2012-12-18 14:30:41 +00008319//===----------------------------------------------------------------------===//
8320// C++ AST instrospection.
8321//===----------------------------------------------------------------------===//
8322
Jonathan Coe29565352016-04-27 12:48:25 +00008323unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8324 if (!clang_isDeclaration(C.kind))
8325 return 0;
8326
8327 const Decl *D = cxcursor::getCursorDecl(C);
8328 const CXXConstructorDecl *Constructor =
8329 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8330 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8331}
8332
8333unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8334 if (!clang_isDeclaration(C.kind))
8335 return 0;
8336
8337 const Decl *D = cxcursor::getCursorDecl(C);
8338 const CXXConstructorDecl *Constructor =
8339 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8340 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8341}
8342
8343unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8344 if (!clang_isDeclaration(C.kind))
8345 return 0;
8346
8347 const Decl *D = cxcursor::getCursorDecl(C);
8348 const CXXConstructorDecl *Constructor =
8349 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8350 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8351}
8352
8353unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8354 if (!clang_isDeclaration(C.kind))
8355 return 0;
8356
8357 const Decl *D = cxcursor::getCursorDecl(C);
8358 const CXXConstructorDecl *Constructor =
8359 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8360 // Passing 'false' excludes constructors marked 'explicit'.
8361 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8362}
8363
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008364unsigned clang_CXXField_isMutable(CXCursor C) {
8365 if (!clang_isDeclaration(C.kind))
8366 return 0;
8367
8368 if (const auto D = cxcursor::getCursorDecl(C))
8369 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8370 return FD->isMutable() ? 1 : 0;
8371 return 0;
8372}
8373
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008374unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8375 if (!clang_isDeclaration(C.kind))
8376 return 0;
8377
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008378 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008379 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008380 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008381 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8382}
8383
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008384unsigned clang_CXXMethod_isConst(CXCursor C) {
8385 if (!clang_isDeclaration(C.kind))
8386 return 0;
8387
8388 const Decl *D = cxcursor::getCursorDecl(C);
8389 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008390 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008391 return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008392}
8393
Jonathan Coe29565352016-04-27 12:48:25 +00008394unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8395 if (!clang_isDeclaration(C.kind))
8396 return 0;
8397
8398 const Decl *D = cxcursor::getCursorDecl(C);
8399 const CXXMethodDecl *Method =
8400 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8401 return (Method && Method->isDefaulted()) ? 1 : 0;
8402}
8403
Guy Benyei11169dd2012-12-18 14:30:41 +00008404unsigned clang_CXXMethod_isStatic(CXCursor C) {
8405 if (!clang_isDeclaration(C.kind))
8406 return 0;
8407
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008408 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008409 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008410 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008411 return (Method && Method->isStatic()) ? 1 : 0;
8412}
8413
8414unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8415 if (!clang_isDeclaration(C.kind))
8416 return 0;
8417
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008418 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008419 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008420 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008421 return (Method && Method->isVirtual()) ? 1 : 0;
8422}
Guy Benyei11169dd2012-12-18 14:30:41 +00008423
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008424unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8425 if (!clang_isDeclaration(C.kind))
8426 return 0;
8427
8428 const auto *D = cxcursor::getCursorDecl(C);
8429 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8430 if (RD)
8431 RD = RD->getDefinition();
8432 return (RD && RD->isAbstract()) ? 1 : 0;
8433}
8434
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008435unsigned clang_EnumDecl_isScoped(CXCursor C) {
8436 if (!clang_isDeclaration(C.kind))
8437 return 0;
8438
8439 const Decl *D = cxcursor::getCursorDecl(C);
8440 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8441 return (Enum && Enum->isScoped()) ? 1 : 0;
8442}
8443
Guy Benyei11169dd2012-12-18 14:30:41 +00008444//===----------------------------------------------------------------------===//
8445// Attribute introspection.
8446//===----------------------------------------------------------------------===//
8447
Guy Benyei11169dd2012-12-18 14:30:41 +00008448CXType clang_getIBOutletCollectionType(CXCursor C) {
8449 if (C.kind != CXCursor_IBOutletCollectionAttr)
8450 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8451
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008452 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008453 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8454
8455 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8456}
Guy Benyei11169dd2012-12-18 14:30:41 +00008457
8458//===----------------------------------------------------------------------===//
8459// Inspecting memory usage.
8460//===----------------------------------------------------------------------===//
8461
8462typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8463
8464static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8465 enum CXTUResourceUsageKind k,
8466 unsigned long amount) {
8467 CXTUResourceUsageEntry entry = { k, amount };
8468 entries.push_back(entry);
8469}
8470
Guy Benyei11169dd2012-12-18 14:30:41 +00008471const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8472 const char *str = "";
8473 switch (kind) {
8474 case CXTUResourceUsage_AST:
8475 str = "ASTContext: expressions, declarations, and types";
8476 break;
8477 case CXTUResourceUsage_Identifiers:
8478 str = "ASTContext: identifiers";
8479 break;
8480 case CXTUResourceUsage_Selectors:
8481 str = "ASTContext: selectors";
8482 break;
8483 case CXTUResourceUsage_GlobalCompletionResults:
8484 str = "Code completion: cached global results";
8485 break;
8486 case CXTUResourceUsage_SourceManagerContentCache:
8487 str = "SourceManager: content cache allocator";
8488 break;
8489 case CXTUResourceUsage_AST_SideTables:
8490 str = "ASTContext: side tables";
8491 break;
8492 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8493 str = "SourceManager: malloc'ed memory buffers";
8494 break;
8495 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8496 str = "SourceManager: mmap'ed memory buffers";
8497 break;
8498 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8499 str = "ExternalASTSource: malloc'ed memory buffers";
8500 break;
8501 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8502 str = "ExternalASTSource: mmap'ed memory buffers";
8503 break;
8504 case CXTUResourceUsage_Preprocessor:
8505 str = "Preprocessor: malloc'ed memory";
8506 break;
8507 case CXTUResourceUsage_PreprocessingRecord:
8508 str = "Preprocessor: PreprocessingRecord";
8509 break;
8510 case CXTUResourceUsage_SourceManager_DataStructures:
8511 str = "SourceManager: data structures and tables";
8512 break;
8513 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8514 str = "Preprocessor: header search tables";
8515 break;
8516 }
8517 return str;
8518}
8519
8520CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008521 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008522 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008523 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008524 return usage;
8525 }
8526
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008527 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008528 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008529 ASTContext &astContext = astUnit->getASTContext();
8530
8531 // How much memory is used by AST nodes and types?
8532 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8533 (unsigned long) astContext.getASTAllocatedMemory());
8534
8535 // How much memory is used by identifiers?
8536 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8537 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8538
8539 // How much memory is used for selectors?
8540 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8541 (unsigned long) astContext.Selectors.getTotalMemory());
8542
8543 // How much memory is used by ASTContext's side tables?
8544 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8545 (unsigned long) astContext.getSideTableAllocatedMemory());
8546
8547 // How much memory is used for caching global code completion results?
8548 unsigned long completionBytes = 0;
8549 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008550 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008551 completionBytes = completionAllocator->getTotalMemory();
8552 }
8553 createCXTUResourceUsageEntry(*entries,
8554 CXTUResourceUsage_GlobalCompletionResults,
8555 completionBytes);
8556
8557 // How much memory is being used by SourceManager's content cache?
8558 createCXTUResourceUsageEntry(*entries,
8559 CXTUResourceUsage_SourceManagerContentCache,
8560 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8561
8562 // How much memory is being used by the MemoryBuffer's in SourceManager?
8563 const SourceManager::MemoryBufferSizes &srcBufs =
8564 astUnit->getSourceManager().getMemoryBufferSizes();
8565
8566 createCXTUResourceUsageEntry(*entries,
8567 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8568 (unsigned long) srcBufs.malloc_bytes);
8569 createCXTUResourceUsageEntry(*entries,
8570 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8571 (unsigned long) srcBufs.mmap_bytes);
8572 createCXTUResourceUsageEntry(*entries,
8573 CXTUResourceUsage_SourceManager_DataStructures,
8574 (unsigned long) astContext.getSourceManager()
8575 .getDataStructureSizes());
8576
8577 // How much memory is being used by the ExternalASTSource?
8578 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8579 const ExternalASTSource::MemoryBufferSizes &sizes =
8580 esrc->getMemoryBufferSizes();
8581
8582 createCXTUResourceUsageEntry(*entries,
8583 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8584 (unsigned long) sizes.malloc_bytes);
8585 createCXTUResourceUsageEntry(*entries,
8586 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8587 (unsigned long) sizes.mmap_bytes);
8588 }
8589
8590 // How much memory is being used by the Preprocessor?
8591 Preprocessor &pp = astUnit->getPreprocessor();
8592 createCXTUResourceUsageEntry(*entries,
8593 CXTUResourceUsage_Preprocessor,
8594 pp.getTotalMemory());
8595
8596 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8597 createCXTUResourceUsageEntry(*entries,
8598 CXTUResourceUsage_PreprocessingRecord,
8599 pRec->getTotalMemory());
8600 }
8601
8602 createCXTUResourceUsageEntry(*entries,
8603 CXTUResourceUsage_Preprocessor_HeaderSearch,
8604 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008605
Guy Benyei11169dd2012-12-18 14:30:41 +00008606 CXTUResourceUsage usage = { (void*) entries.get(),
8607 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008608 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008609 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008610 return usage;
8611}
8612
8613void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8614 if (usage.data)
8615 delete (MemUsageEntries*) usage.data;
8616}
8617
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008618CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8619 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008620 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008621 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008622
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008623 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008624 LOG_BAD_TU(TU);
8625 return skipped;
8626 }
8627
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008628 if (!file)
8629 return skipped;
8630
8631 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8632 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8633 if (!ppRec)
8634 return skipped;
8635
8636 ASTContext &Ctx = astUnit->getASTContext();
8637 SourceManager &sm = Ctx.getSourceManager();
8638 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8639 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008640 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008641
8642 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8643 std::vector<SourceRange> wantedRanges;
8644 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8645 i != ei; ++i) {
8646 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8647 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008648 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8649 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008650 }
8651
8652 skipped->count = wantedRanges.size();
8653 skipped->ranges = new CXSourceRange[skipped->count];
8654 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8655 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8656
8657 return skipped;
8658}
8659
Cameron Desrochersd8091282016-08-18 15:43:55 +00008660CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8661 CXSourceRangeList *skipped = new CXSourceRangeList;
8662 skipped->count = 0;
8663 skipped->ranges = nullptr;
8664
8665 if (isNotUsableTU(TU)) {
8666 LOG_BAD_TU(TU);
8667 return skipped;
8668 }
8669
8670 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8671 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8672 if (!ppRec)
8673 return skipped;
8674
8675 ASTContext &Ctx = astUnit->getASTContext();
8676
8677 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8678
8679 skipped->count = SkippedRanges.size();
8680 skipped->ranges = new CXSourceRange[skipped->count];
8681 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8682 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8683
8684 return skipped;
8685}
8686
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008687void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8688 if (ranges) {
8689 delete[] ranges->ranges;
8690 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008691 }
8692}
8693
Guy Benyei11169dd2012-12-18 14:30:41 +00008694void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8695 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8696 for (unsigned I = 0; I != Usage.numEntries; ++I)
8697 fprintf(stderr, " %s: %lu\n",
8698 clang_getTUResourceUsageName(Usage.entries[I].kind),
8699 Usage.entries[I].amount);
8700
8701 clang_disposeCXTUResourceUsage(Usage);
8702}
8703
8704//===----------------------------------------------------------------------===//
8705// Misc. utility functions.
8706//===----------------------------------------------------------------------===//
8707
Richard Smith0a7b2972018-07-03 21:34:13 +00008708/// Default to using our desired 8 MB stack size on "safety" threads.
8709static unsigned SafetyStackThreadSize = DesiredStackSize;
Guy Benyei11169dd2012-12-18 14:30:41 +00008710
8711namespace clang {
8712
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008713bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008714 unsigned Size) {
8715 if (!Size)
8716 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008717 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008718 return CRC.RunSafelyOnThread(Fn, Size);
8719 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008720}
8721
8722unsigned GetSafetyThreadStackSize() {
8723 return SafetyStackThreadSize;
8724}
8725
8726void SetSafetyThreadStackSize(unsigned Value) {
8727 SafetyStackThreadSize = Value;
8728}
8729
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008730}
Guy Benyei11169dd2012-12-18 14:30:41 +00008731
8732void clang::setThreadBackgroundPriority() {
8733 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8734 return;
8735
Nico Weber18cfd9f2019-04-21 19:18:41 +00008736#if LLVM_ENABLE_THREADS
Kadir Cetinkayab8f82ca2019-04-18 13:49:20 +00008737 llvm::set_thread_priority(llvm::ThreadPriority::Background);
Nico Weber18cfd9f2019-04-21 19:18:41 +00008738#endif
Guy Benyei11169dd2012-12-18 14:30:41 +00008739}
8740
8741void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8742 if (!Unit)
8743 return;
8744
8745 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8746 DEnd = Unit->stored_diag_end();
8747 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008748 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008749 CXString Msg = clang_formatDiagnostic(&Diag,
8750 clang_defaultDiagnosticDisplayOptions());
8751 fprintf(stderr, "%s\n", clang_getCString(Msg));
8752 clang_disposeString(Msg);
8753 }
Nico Weber1865df42018-04-27 19:11:14 +00008754#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008755 // On Windows, force a flush, since there may be multiple copies of
8756 // stderr and stdout in the file system, all with different buffers
8757 // but writing to the same device.
8758 fflush(stderr);
8759#endif
8760}
8761
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008762MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8763 SourceLocation MacroDefLoc,
8764 CXTranslationUnit TU){
8765 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008766 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008767 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008768 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008769
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008770 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008771 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008772 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008773 if (MD) {
8774 for (MacroDirective::DefInfo
8775 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8776 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8777 return Def.getMacroInfo();
8778 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008779 }
8780
Craig Topper69186e72014-06-08 08:38:04 +00008781 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008782}
8783
Richard Smith66a81862015-05-04 02:25:31 +00008784const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008785 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008786 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008787 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008788 const IdentifierInfo *II = MacroDef->getName();
8789 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008790 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008791
8792 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8793}
8794
Richard Smith66a81862015-05-04 02:25:31 +00008795MacroDefinitionRecord *
8796cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8797 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008798 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008799 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008800 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008801 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008802
8803 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008804 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008805 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8806 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008807 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008808
8809 // Check that the token is inside the definition and not its argument list.
8810 SourceManager &SM = Unit->getSourceManager();
8811 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008812 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008813 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008814 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008815
8816 Preprocessor &PP = Unit->getPreprocessor();
8817 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8818 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008819 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008820
Alp Toker2d57cea2014-05-17 04:53:25 +00008821 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008822 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008823 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008824
8825 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008826 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008827 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008828
Richard Smith20e883e2015-04-29 23:20:19 +00008829 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008830 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008831 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008832
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008833 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008834}
8835
Richard Smith66a81862015-05-04 02:25:31 +00008836MacroDefinitionRecord *
8837cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8838 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008839 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008840 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008841
8842 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008843 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008844 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008845 Preprocessor &PP = Unit->getPreprocessor();
8846 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008847 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008848 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8849 Token Tok;
8850 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008851 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008852
8853 return checkForMacroInMacroDefinition(MI, Tok, TU);
8854}
8855
Guy Benyei11169dd2012-12-18 14:30:41 +00008856CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008857 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008858}
8859
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008860Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8861 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008862 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008863 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008864 if (Unit->isMainFileAST())
8865 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008866 return *this;
8867 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008868 } else {
8869 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008870 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008871 return *this;
8872}
8873
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008874Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8875 *this << FE->getName();
8876 return *this;
8877}
8878
8879Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8880 CXString cursorName = clang_getCursorDisplayName(cursor);
8881 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8882 clang_disposeString(cursorName);
8883 return *this;
8884}
8885
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008886Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8887 CXFile File;
8888 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008889 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008890 CXString FileName = clang_getFileName(File);
8891 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8892 clang_disposeString(FileName);
8893 return *this;
8894}
8895
8896Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8897 CXSourceLocation BLoc = clang_getRangeStart(range);
8898 CXSourceLocation ELoc = clang_getRangeEnd(range);
8899
8900 CXFile BFile;
8901 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008902 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008903
8904 CXFile EFile;
8905 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008906 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008907
8908 CXString BFileName = clang_getFileName(BFile);
8909 if (BFile == EFile) {
8910 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8911 BLine, BColumn, ELine, EColumn);
8912 } else {
8913 CXString EFileName = clang_getFileName(EFile);
8914 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8915 BLine, BColumn)
8916 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8917 ELine, EColumn);
8918 clang_disposeString(EFileName);
8919 }
8920 clang_disposeString(BFileName);
8921 return *this;
8922}
8923
8924Logger &cxindex::Logger::operator<<(CXString Str) {
8925 *this << clang_getCString(Str);
8926 return *this;
8927}
8928
8929Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8930 LogOS << Fmt;
8931 return *this;
8932}
8933
Chandler Carruth37ad2582014-06-27 15:14:39 +00008934static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8935
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008936cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008937 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008938
8939 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8940
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008941 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008942 OS << "[libclang:" << Name << ':';
8943
Alp Toker1a86ad22014-07-06 06:24:00 +00008944#ifdef USE_DARWIN_THREADS
8945 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008946 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8947 OS << tid << ':';
8948#endif
8949
8950 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8951 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008952 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008953
8954 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008955 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008956 OS << "--------------------------------------------------\n";
8957 }
8958}
Ivan Donchevskiic5929132018-12-10 15:58:50 +00008959
8960#ifdef CLANG_TOOL_EXTRA_BUILD
8961// This anchor is used to force the linker to link the clang-tidy plugin.
8962extern volatile int ClangTidyPluginAnchorSource;
8963static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8964 ClangTidyPluginAnchorSource;
8965
8966// This anchor is used to force the linker to link the clang-include-fixer
8967// plugin.
8968extern volatile int ClangIncludeFixerPluginAnchorSource;
8969static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8970 ClangIncludeFixerPluginAnchorSource;
8971#endif