blob: 5e77808a74948eab014b1c5d80c4dc03417cc2bb [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"
Jan Korousf7d23762019-09-12 22:55:55 +000023#include "clang-c/FatalErrorHandler.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000024#include "clang/AST/Attr.h"
Jan Korous7e36ecd2019-09-05 20:33:52 +000025#include "clang/AST/Mangle.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000026#include "clang/AST/StmtVisitor.h"
27#include "clang/Basic/Diagnostic.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000028#include "clang/Basic/DiagnosticCategories.h"
29#include "clang/Basic/DiagnosticIDs.h"
Richard Smith0a7b2972018-07-03 21:34:13 +000030#include "clang/Basic/Stack.h"
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +000031#include "clang/Basic/TargetInfo.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000032#include "clang/Basic/Version.h"
33#include "clang/Frontend/ASTUnit.h"
34#include "clang/Frontend/CompilerInstance.h"
Dmitri Gribenko9e605112013-11-13 22:16:51 +000035#include "clang/Index/CommentToXML.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000036#include "clang/Lex/HeaderSearch.h"
37#include "clang/Lex/Lexer.h"
38#include "clang/Lex/PreprocessingRecord.h"
39#include "clang/Lex/Preprocessor.h"
40#include "llvm/ADT/Optional.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/StringSwitch.h"
Alp Toker1d257e12014-06-04 03:28:55 +000043#include "llvm/Config/llvm-config.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000044#include "llvm/Support/Compiler.h"
45#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000046#include "llvm/Support/Format.h"
Chandler Carruth37ad2582014-06-27 15:14:39 +000047#include "llvm/Support/ManagedStatic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000048#include "llvm/Support/MemoryBuffer.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"
Benjamin Kramer762bc332019-08-07 14:44:40 +000056#include <mutex>
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000057
Alp Toker1a86ad22014-07-06 06:24:00 +000058#if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
59#define USE_DARWIN_THREADS
60#endif
61
62#ifdef USE_DARWIN_THREADS
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000063#include <pthread.h>
64#endif
Guy Benyei11169dd2012-12-18 14:30:41 +000065
66using namespace clang;
67using namespace clang::cxcursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000068using namespace clang::cxtu;
69using namespace clang::cxindex;
70
David Blaikieea4395e2017-01-06 19:49:01 +000071CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
72 std::unique_ptr<ASTUnit> AU) {
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000073 if (!AU)
Craig Topper69186e72014-06-08 08:38:04 +000074 return nullptr;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000075 assert(CIdx);
Guy Benyei11169dd2012-12-18 14:30:41 +000076 CXTranslationUnit D = new CXTranslationUnitImpl();
77 D->CIdx = CIdx;
David Blaikieea4395e2017-01-06 19:49:01 +000078 D->TheASTUnit = AU.release();
Dmitri Gribenko74895212013-02-03 13:52:47 +000079 D->StringPool = new cxstring::CXStringPool();
Craig Topper69186e72014-06-08 08:38:04 +000080 D->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000081 D->OverridenCursorsPool = createOverridenCXCursorsPool();
Craig Topper69186e72014-06-08 08:38:04 +000082 D->CommentToXML = nullptr;
Alex Lorenz690f0e22017-12-07 20:37:50 +000083 D->ParsingOptions = 0;
84 D->Arguments = {};
Guy Benyei11169dd2012-12-18 14:30:41 +000085 return D;
86}
87
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000088bool cxtu::isASTReadError(ASTUnit *AU) {
89 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
90 DEnd = AU->stored_diag_end();
91 D != DEnd; ++D) {
92 if (D->getLevel() >= DiagnosticsEngine::Error &&
93 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
94 diag::DiagCat_AST_Deserialization_Issue)
95 return true;
96 }
97 return false;
98}
99
Guy Benyei11169dd2012-12-18 14:30:41 +0000100cxtu::CXTUOwner::~CXTUOwner() {
101 if (TU)
102 clang_disposeTranslationUnit(TU);
103}
104
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000105/// Compare two source ranges to determine their relative position in
Guy Benyei11169dd2012-12-18 14:30:41 +0000106/// the translation unit.
107static RangeComparisonResult RangeCompare(SourceManager &SM,
108 SourceRange R1,
109 SourceRange R2) {
110 assert(R1.isValid() && "First range is invalid?");
111 assert(R2.isValid() && "Second range is invalid?");
112 if (R1.getEnd() != R2.getBegin() &&
113 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
114 return RangeBefore;
115 if (R2.getEnd() != R1.getBegin() &&
116 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
117 return RangeAfter;
118 return RangeOverlap;
119}
120
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000121/// Determine if a source location falls within, before, or after a
Guy Benyei11169dd2012-12-18 14:30:41 +0000122/// a given source range.
123static RangeComparisonResult LocationCompare(SourceManager &SM,
124 SourceLocation L, SourceRange R) {
125 assert(R.isValid() && "First range is invalid?");
126 assert(L.isValid() && "Second range is invalid?");
127 if (L == R.getBegin() || L == R.getEnd())
128 return RangeOverlap;
129 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
130 return RangeBefore;
131 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
132 return RangeAfter;
133 return RangeOverlap;
134}
135
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000136/// Translate a Clang source range into a CIndex source range.
Guy Benyei11169dd2012-12-18 14:30:41 +0000137///
138/// Clang internally represents ranges where the end location points to the
139/// start of the token at the end. However, for external clients it is more
140/// useful to have a CXSourceRange be a proper half-open interval. This routine
141/// does the appropriate translation.
142CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
143 const LangOptions &LangOpts,
144 const CharSourceRange &R) {
145 // We want the last character in this location, so we will adjust the
146 // location accordingly.
147 SourceLocation EndLoc = R.getEnd();
Richard Smithb5f81712018-04-30 05:25:48 +0000148 bool IsTokenRange = R.isTokenRange();
149 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc)) {
150 CharSourceRange Expansion = SM.getExpansionRange(EndLoc);
151 EndLoc = Expansion.getEnd();
152 IsTokenRange = Expansion.isTokenRange();
153 }
154 if (IsTokenRange && EndLoc.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000155 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
156 SM, LangOpts);
157 EndLoc = EndLoc.getLocWithOffset(Length);
158 }
159
Bill Wendlingeade3622013-01-23 08:25:41 +0000160 CXSourceRange Result = {
Dmitri Gribenkof9304482013-01-23 15:56:07 +0000161 { &SM, &LangOpts },
Bill Wendlingeade3622013-01-23 08:25:41 +0000162 R.getBegin().getRawEncoding(),
163 EndLoc.getRawEncoding()
164 };
Guy Benyei11169dd2012-12-18 14:30:41 +0000165 return Result;
166}
167
168//===----------------------------------------------------------------------===//
169// Cursor visitor.
170//===----------------------------------------------------------------------===//
171
172static SourceRange getRawCursorExtent(CXCursor C);
173static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
174
Guy Benyei11169dd2012-12-18 14:30:41 +0000175RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
176 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
177}
178
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000179/// Visit the given cursor and, if requested by the visitor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000180/// its children.
181///
182/// \param Cursor the cursor to visit.
183///
184/// \param CheckedRegionOfInterest if true, then the caller already checked
185/// that this cursor is within the region of interest.
186///
187/// \returns true if the visitation should be aborted, false if it
188/// should continue.
189bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
190 if (clang_isInvalid(Cursor.kind))
191 return false;
192
193 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000194 const Decl *D = getCursorDecl(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +0000195 if (!D) {
196 assert(0 && "Invalid declaration cursor");
197 return true; // abort.
198 }
199
200 // Ignore implicit declarations, unless it's an objc method because
201 // currently we should report implicit methods for properties when indexing.
202 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
203 return false;
204 }
205
206 // If we have a range of interest, and this cursor doesn't intersect with it,
207 // we're done.
208 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
209 SourceRange Range = getRawCursorExtent(Cursor);
210 if (Range.isInvalid() || CompareRegionOfInterest(Range))
211 return false;
212 }
213
214 switch (Visitor(Cursor, Parent, ClientData)) {
215 case CXChildVisit_Break:
216 return true;
217
218 case CXChildVisit_Continue:
219 return false;
220
221 case CXChildVisit_Recurse: {
222 bool ret = VisitChildren(Cursor);
223 if (PostChildrenVisitor)
224 if (PostChildrenVisitor(Cursor, ClientData))
225 return true;
226 return ret;
227 }
228 }
229
230 llvm_unreachable("Invalid CXChildVisitResult!");
231}
232
233static bool visitPreprocessedEntitiesInRange(SourceRange R,
234 PreprocessingRecord &PPRec,
235 CursorVisitor &Visitor) {
236 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
237 FileID FID;
238
239 if (!Visitor.shouldVisitIncludedEntities()) {
240 // If the begin/end of the range lie in the same FileID, do the optimization
241 // where we skip preprocessed entities that do not come from the same FileID.
242 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
243 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
244 FID = FileID();
245 }
246
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000247 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
248 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000249 PPRec, FID);
250}
251
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000252bool CursorVisitor::visitFileRegion() {
Guy Benyei11169dd2012-12-18 14:30:41 +0000253 if (RegionOfInterest.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000254 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000255
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000256 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000257 SourceManager &SM = Unit->getSourceManager();
258
259 std::pair<FileID, unsigned>
260 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
261 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
262
263 if (End.first != Begin.first) {
264 // If the end does not reside in the same file, try to recover by
265 // picking the end of the file of begin location.
266 End.first = Begin.first;
267 End.second = SM.getFileIDSize(Begin.first);
268 }
269
270 assert(Begin.first == End.first);
271 if (Begin.second > End.second)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000272 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000273
274 FileID File = Begin.first;
275 unsigned Offset = Begin.second;
276 unsigned Length = End.second - Begin.second;
277
278 if (!VisitDeclsOnly && !VisitPreprocessorLast)
279 if (visitPreprocessedEntitiesInRegion())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000280 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000281
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000282 if (visitDeclsFromFileRegion(File, Offset, Length))
283 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000284
285 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000286 return visitPreprocessedEntitiesInRegion();
287
288 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000289}
290
291static bool isInLexicalContext(Decl *D, DeclContext *DC) {
292 if (!DC)
293 return false;
294
295 for (DeclContext *DeclDC = D->getLexicalDeclContext();
296 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
297 if (DeclDC == DC)
298 return true;
299 }
300 return false;
301}
302
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000303bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
Guy Benyei11169dd2012-12-18 14:30:41 +0000304 unsigned Offset, unsigned Length) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000305 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000306 SourceManager &SM = Unit->getSourceManager();
307 SourceRange Range = RegionOfInterest;
308
309 SmallVector<Decl *, 16> Decls;
310 Unit->findFileRegionDecls(File, Offset, Length, Decls);
311
312 // If we didn't find any file level decls for the file, try looking at the
313 // file that it was included from.
314 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
315 bool Invalid = false;
316 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
317 if (Invalid)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000318 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000319
320 SourceLocation Outer;
321 if (SLEntry.isFile())
322 Outer = SLEntry.getFile().getIncludeLoc();
323 else
324 Outer = SLEntry.getExpansion().getExpansionLocStart();
325 if (Outer.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000326 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000327
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000328 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
Guy Benyei11169dd2012-12-18 14:30:41 +0000329 Length = 0;
330 Unit->findFileRegionDecls(File, Offset, Length, Decls);
331 }
332
333 assert(!Decls.empty());
334
335 bool VisitedAtLeastOnce = false;
Craig Topper69186e72014-06-08 08:38:04 +0000336 DeclContext *CurDC = nullptr;
Craig Topper2341c0d2013-07-04 03:08:24 +0000337 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
338 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000339 Decl *D = *DIt;
340 if (D->getSourceRange().isInvalid())
341 continue;
342
343 if (isInLexicalContext(D, CurDC))
344 continue;
345
346 CurDC = dyn_cast<DeclContext>(D);
347
348 if (TagDecl *TD = dyn_cast<TagDecl>(D))
349 if (!TD->isFreeStanding())
350 continue;
351
352 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
353 if (CompRes == RangeBefore)
354 continue;
355 if (CompRes == RangeAfter)
356 break;
357
358 assert(CompRes == RangeOverlap);
359 VisitedAtLeastOnce = true;
360
361 if (isa<ObjCContainerDecl>(D)) {
362 FileDI_current = &DIt;
363 FileDE_current = DE;
364 } else {
Craig Topper69186e72014-06-08 08:38:04 +0000365 FileDI_current = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000366 }
367
368 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000369 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000370 }
371
372 if (VisitedAtLeastOnce)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000373 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000374
375 // No Decls overlapped with the range. Move up the lexical context until there
376 // is a context that contains the range or we reach the translation unit
377 // level.
378 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
379 : (*(DIt-1))->getLexicalDeclContext();
380
381 while (DC && !DC->isTranslationUnit()) {
382 Decl *D = cast<Decl>(DC);
383 SourceRange CurDeclRange = D->getSourceRange();
384 if (CurDeclRange.isInvalid())
385 break;
386
387 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000388 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
389 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000390 }
391
392 DC = D->getLexicalDeclContext();
393 }
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000394
395 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000396}
397
398bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
399 if (!AU->getPreprocessor().getPreprocessingRecord())
400 return false;
401
402 PreprocessingRecord &PPRec
403 = *AU->getPreprocessor().getPreprocessingRecord();
404 SourceManager &SM = AU->getSourceManager();
405
406 if (RegionOfInterest.isValid()) {
407 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
408 SourceLocation B = MappedRange.getBegin();
409 SourceLocation E = MappedRange.getEnd();
410
411 if (AU->isInPreambleFileID(B)) {
412 if (SM.isLoadedSourceLocation(E))
413 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
414 PPRec, *this);
415
416 // Beginning of range lies in the preamble but it also extends beyond
417 // it into the main file. Split the range into 2 parts, one covering
418 // the preamble and another covering the main file. This allows subsequent
419 // calls to visitPreprocessedEntitiesInRange to accept a source range that
420 // lies in the same FileID, allowing it to skip preprocessed entities that
421 // do not come from the same FileID.
422 bool breaked =
423 visitPreprocessedEntitiesInRange(
424 SourceRange(B, AU->getEndOfPreambleFileID()),
425 PPRec, *this);
426 if (breaked) return true;
427 return visitPreprocessedEntitiesInRange(
428 SourceRange(AU->getStartOfMainFileID(), E),
429 PPRec, *this);
430 }
431
432 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
433 }
434
435 bool OnlyLocalDecls
436 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
437
438 if (OnlyLocalDecls)
439 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
440 PPRec);
441
442 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
443}
444
445template<typename InputIterator>
446bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
447 InputIterator Last,
448 PreprocessingRecord &PPRec,
449 FileID FID) {
450 for (; First != Last; ++First) {
451 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
452 continue;
453
454 PreprocessedEntity *PPE = *First;
Argyrios Kyrtzidis1030f262013-05-07 20:37:17 +0000455 if (!PPE)
456 continue;
457
Guy Benyei11169dd2012-12-18 14:30:41 +0000458 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
459 if (Visit(MakeMacroExpansionCursor(ME, TU)))
460 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000461
Guy Benyei11169dd2012-12-18 14:30:41 +0000462 continue;
463 }
Richard Smith66a81862015-05-04 02:25:31 +0000464
465 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000466 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
467 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000468
Guy Benyei11169dd2012-12-18 14:30:41 +0000469 continue;
470 }
471
472 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
473 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
474 return true;
475
476 continue;
477 }
478 }
479
480 return false;
481}
482
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000483/// Visit the children of the given cursor.
Guy Benyei11169dd2012-12-18 14:30:41 +0000484///
485/// \returns true if the visitation should be aborted, false if it
486/// should continue.
487bool CursorVisitor::VisitChildren(CXCursor Cursor) {
488 if (clang_isReference(Cursor.kind) &&
489 Cursor.kind != CXCursor_CXXBaseSpecifier) {
490 // By definition, references have no children.
491 return false;
492 }
493
494 // Set the Parent field to Cursor, then back to its old value once we're
495 // done.
496 SetParentRAII SetParent(Parent, StmtParent, Cursor);
497
498 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000499 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +0000500 if (!D)
501 return false;
502
503 return VisitAttributes(D) || Visit(D);
504 }
505
506 if (clang_isStatement(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000507 if (const Stmt *S = getCursorStmt(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000508 return Visit(S);
509
510 return false;
511 }
512
513 if (clang_isExpression(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000514 if (const Expr *E = getCursorExpr(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000515 return Visit(E);
516
517 return false;
518 }
519
520 if (clang_isTranslationUnit(Cursor.kind)) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000521 CXTranslationUnit TU = getCursorTU(Cursor);
522 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000523
524 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
525 for (unsigned I = 0; I != 2; ++I) {
526 if (VisitOrder[I]) {
527 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
528 RegionOfInterest.isInvalid()) {
529 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
530 TLEnd = CXXUnit->top_level_end();
531 TL != TLEnd; ++TL) {
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000532 const Optional<bool> V = handleDeclForVisitation(*TL);
533 if (!V.hasValue())
534 continue;
535 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000536 }
537 } else if (VisitDeclContext(
538 CXXUnit->getASTContext().getTranslationUnitDecl()))
539 return true;
540 continue;
541 }
542
543 // Walk the preprocessing record.
544 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
545 visitPreprocessedEntitiesInRegion();
546 }
547
548 return false;
549 }
550
551 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000552 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000553 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
554 return Visit(BaseTSInfo->getTypeLoc());
555 }
556 }
557 }
558
559 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +0000560 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +0000561 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
Richard Smithb1f9a282013-10-31 01:56:18 +0000562 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
Richard Smithb87c4652013-10-31 21:23:20 +0000563 return Visit(cxcursor::MakeCursorObjCClassRef(
564 ObjT->getInterface(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000565 A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +0000566 }
567
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000568 // If pointing inside a macro definition, check if the token is an identifier
569 // that was ever defined as a macro. In such a case, create a "pseudo" macro
570 // expansion cursor for that token.
571 SourceLocation BeginLoc = RegionOfInterest.getBegin();
572 if (Cursor.kind == CXCursor_MacroDefinition &&
573 BeginLoc == RegionOfInterest.getEnd()) {
574 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000575 const MacroInfo *MI =
576 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
Richard Smith66a81862015-05-04 02:25:31 +0000577 if (MacroDefinitionRecord *MacroDef =
578 checkForMacroInMacroDefinition(MI, Loc, TU))
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000579 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
580 }
581
Guy Benyei11169dd2012-12-18 14:30:41 +0000582 // Nothing to visit at the moment.
583 return false;
584}
585
586bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
587 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
588 if (Visit(TSInfo->getTypeLoc()))
589 return true;
590
591 if (Stmt *Body = B->getBody())
592 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
593
594 return false;
595}
596
Ted Kremenek03325582013-02-21 01:29:01 +0000597Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000598 if (RegionOfInterest.isValid()) {
599 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
600 if (Range.isInvalid())
David Blaikie7a30dc52013-02-21 01:47:18 +0000601 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000602
603 switch (CompareRegionOfInterest(Range)) {
604 case RangeBefore:
605 // This declaration comes before the region of interest; skip it.
David Blaikie7a30dc52013-02-21 01:47:18 +0000606 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000607
608 case RangeAfter:
609 // This declaration comes after the region of interest; we're done.
610 return false;
611
612 case RangeOverlap:
613 // This declaration overlaps the region of interest; visit it.
614 break;
615 }
616 }
617 return true;
618}
619
620bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
621 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
622
623 // FIXME: Eventually remove. This part of a hack to support proper
624 // iteration over all Decls contained lexically within an ObjC container.
625 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
626 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
627
628 for ( ; I != E; ++I) {
629 Decl *D = *I;
630 if (D->getLexicalDeclContext() != DC)
631 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000632 const Optional<bool> V = handleDeclForVisitation(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000633 if (!V.hasValue())
634 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000635 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000636 }
637 return false;
638}
639
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000640Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
641 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
642
643 // Ignore synthesized ivars here, otherwise if we have something like:
644 // @synthesize prop = _prop;
645 // and '_prop' is not declared, we will encounter a '_prop' ivar before
646 // encountering the 'prop' synthesize declaration and we will think that
647 // we passed the region-of-interest.
648 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
649 if (ivarD->getSynthesize())
650 return None;
651 }
652
653 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
654 // declarations is a mismatch with the compiler semantics.
655 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
656 auto *ID = cast<ObjCInterfaceDecl>(D);
657 if (!ID->isThisDeclarationADefinition())
658 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
659
660 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
661 auto *PD = cast<ObjCProtocolDecl>(D);
662 if (!PD->isThisDeclarationADefinition())
663 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
664 }
665
666 const Optional<bool> V = shouldVisitCursor(Cursor);
667 if (!V.hasValue())
668 return None;
669 if (!V.getValue())
670 return false;
671 if (Visit(Cursor, true))
672 return true;
673 return None;
674}
675
Guy Benyei11169dd2012-12-18 14:30:41 +0000676bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
677 llvm_unreachable("Translation units are visited directly by Visit()");
678}
679
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +0000680bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
681 if (VisitTemplateParameters(D->getTemplateParameters()))
682 return true;
683
684 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
685}
686
Guy Benyei11169dd2012-12-18 14:30:41 +0000687bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
688 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
689 return Visit(TSInfo->getTypeLoc());
690
691 return false;
692}
693
694bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
695 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
696 return Visit(TSInfo->getTypeLoc());
697
698 return false;
699}
700
701bool CursorVisitor::VisitTagDecl(TagDecl *D) {
702 return VisitDeclContext(D);
703}
704
705bool CursorVisitor::VisitClassTemplateSpecializationDecl(
706 ClassTemplateSpecializationDecl *D) {
707 bool ShouldVisitBody = false;
708 switch (D->getSpecializationKind()) {
709 case TSK_Undeclared:
710 case TSK_ImplicitInstantiation:
711 // Nothing to visit
712 return false;
713
714 case TSK_ExplicitInstantiationDeclaration:
715 case TSK_ExplicitInstantiationDefinition:
716 break;
717
718 case TSK_ExplicitSpecialization:
719 ShouldVisitBody = true;
720 break;
721 }
722
723 // Visit the template arguments used in the specialization.
724 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
725 TypeLoc TL = SpecType->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +0000726 if (TemplateSpecializationTypeLoc TSTLoc =
727 TL.getAs<TemplateSpecializationTypeLoc>()) {
728 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
729 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000730 return true;
731 }
732 }
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000733
734 return ShouldVisitBody && VisitCXXRecordDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000735}
736
737bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
738 ClassTemplatePartialSpecializationDecl *D) {
739 // FIXME: Visit the "outer" template parameter lists on the TagDecl
740 // before visiting these template parameters.
741 if (VisitTemplateParameters(D->getTemplateParameters()))
742 return true;
743
744 // Visit the partial specialization arguments.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +0000745 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
746 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
747 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +0000748 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
749 return true;
750
751 return VisitCXXRecordDecl(D);
752}
753
754bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
755 // Visit the default argument.
756 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
757 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
758 if (Visit(DefArg->getTypeLoc()))
759 return true;
760
761 return false;
762}
763
764bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
765 if (Expr *Init = D->getInitExpr())
766 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
767 return false;
768}
769
770bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000771 unsigned NumParamList = DD->getNumTemplateParameterLists();
772 for (unsigned i = 0; i < NumParamList; i++) {
773 TemplateParameterList* Params = DD->getTemplateParameterList(i);
774 if (VisitTemplateParameters(Params))
775 return true;
776 }
777
Guy Benyei11169dd2012-12-18 14:30:41 +0000778 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
779 if (Visit(TSInfo->getTypeLoc()))
780 return true;
781
782 // Visit the nested-name-specifier, if present.
783 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
784 if (VisitNestedNameSpecifierLoc(QualifierLoc))
785 return true;
786
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000787 return false;
788}
789
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000790static bool HasTrailingReturnType(FunctionDecl *ND) {
791 const QualType Ty = ND->getType();
792 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
793 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT))
794 return FT->hasTrailingReturn();
795 }
796
797 return false;
798}
799
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000800/// Compare two base or member initializers based on their source order.
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000801static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
802 CXXCtorInitializer *const *Y) {
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000803 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
804}
805
Guy Benyei11169dd2012-12-18 14:30:41 +0000806bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000807 unsigned NumParamList = ND->getNumTemplateParameterLists();
808 for (unsigned i = 0; i < NumParamList; i++) {
809 TemplateParameterList* Params = ND->getTemplateParameterList(i);
810 if (VisitTemplateParameters(Params))
811 return true;
812 }
813
Guy Benyei11169dd2012-12-18 14:30:41 +0000814 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
815 // Visit the function declaration's syntactic components in the order
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000816 // written. This requires a bit of work.
817 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
818 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000819 const bool HasTrailingRT = HasTrailingReturnType(ND);
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000820
821 // If we have a function declared directly (without the use of a typedef),
822 // visit just the return type. Otherwise, just visit the function's type
823 // now.
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000824 if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT &&
825 Visit(FTL.getReturnLoc())) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000826 (!FTL && Visit(TL)))
827 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000828
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000829 // Visit the nested-name-specifier, if present.
830 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
831 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Guy Benyei11169dd2012-12-18 14:30:41 +0000832 return true;
833
834 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000835 if (!isa<CXXDestructorDecl>(ND))
836 if (VisitDeclarationNameInfo(ND->getNameInfo()))
837 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000838
839 // FIXME: Visit explicitly-specified template arguments!
840
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000841 // Visit the function parameters, if we have a function type.
842 if (FTL && VisitFunctionTypeLoc(FTL, true))
843 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000844
845 // Visit the function's trailing return type.
846 if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc()))
847 return true;
848
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000849 // FIXME: Attributes?
850 }
851
Guy Benyei11169dd2012-12-18 14:30:41 +0000852 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
853 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
854 // Find the initializers that were written in the source.
855 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000856 for (auto *I : Constructor->inits()) {
857 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000858 continue;
859
Aaron Ballman0ad78302014-03-13 17:34:31 +0000860 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000861 }
862
863 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000864 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
865 &CompareCXXCtorInitializers);
866
Guy Benyei11169dd2012-12-18 14:30:41 +0000867 // Visit the initializers in source order
868 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
869 CXXCtorInitializer *Init = WrittenInits[I];
870 if (Init->isAnyMemberInitializer()) {
871 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
872 Init->getMemberLocation(), TU)))
873 return true;
874 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
875 if (Visit(TInfo->getTypeLoc()))
876 return true;
877 }
878
879 // Visit the initializer value.
880 if (Expr *Initializer = Init->getInit())
881 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
882 return true;
883 }
884 }
885
886 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
887 return true;
888 }
889
890 return false;
891}
892
893bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
894 if (VisitDeclaratorDecl(D))
895 return true;
896
897 if (Expr *BitWidth = D->getBitWidth())
898 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
899
Benjamin Kramer99f97592017-11-15 12:20:41 +0000900 if (Expr *Init = D->getInClassInitializer())
901 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
902
Guy Benyei11169dd2012-12-18 14:30:41 +0000903 return false;
904}
905
906bool CursorVisitor::VisitVarDecl(VarDecl *D) {
907 if (VisitDeclaratorDecl(D))
908 return true;
909
910 if (Expr *Init = D->getInit())
911 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
912
913 return false;
914}
915
916bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
917 if (VisitDeclaratorDecl(D))
918 return true;
919
920 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
921 if (Expr *DefArg = D->getDefaultArgument())
922 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
923
924 return false;
925}
926
927bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
928 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
929 // before visiting these template parameters.
930 if (VisitTemplateParameters(D->getTemplateParameters()))
931 return true;
932
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000933 auto* FD = D->getTemplatedDecl();
934 return VisitAttributes(FD) || VisitFunctionDecl(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000935}
936
937bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
938 // FIXME: Visit the "outer" template parameter lists on the TagDecl
939 // before visiting these template parameters.
940 if (VisitTemplateParameters(D->getTemplateParameters()))
941 return true;
942
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000943 auto* CD = D->getTemplatedDecl();
944 return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000945}
946
947bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
948 if (VisitTemplateParameters(D->getTemplateParameters()))
949 return true;
950
951 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
952 VisitTemplateArgumentLoc(D->getDefaultArgument()))
953 return true;
954
955 return false;
956}
957
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000958bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
959 // Visit the bound, if it's explicit.
960 if (D->hasExplicitBound()) {
961 if (auto TInfo = D->getTypeSourceInfo()) {
962 if (Visit(TInfo->getTypeLoc()))
963 return true;
964 }
965 }
966
967 return false;
968}
969
Guy Benyei11169dd2012-12-18 14:30:41 +0000970bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000971 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000972 if (Visit(TSInfo->getTypeLoc()))
973 return true;
974
David Majnemer59f77922016-06-24 04:05:48 +0000975 for (const auto *P : ND->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000976 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000977 return true;
978 }
979
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000980 return ND->isThisDeclarationADefinition() &&
981 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000982}
983
984template <typename DeclIt>
985static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
986 SourceManager &SM, SourceLocation EndLoc,
987 SmallVectorImpl<Decl *> &Decls) {
988 DeclIt next = *DI_current;
989 while (++next != DE_current) {
990 Decl *D_next = *next;
991 if (!D_next)
992 break;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000993 SourceLocation L = D_next->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +0000994 if (!L.isValid())
995 break;
996 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
997 *DI_current = next;
998 Decls.push_back(D_next);
999 continue;
1000 }
1001 break;
1002 }
1003}
1004
Guy Benyei11169dd2012-12-18 14:30:41 +00001005bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
1006 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
1007 // an @implementation can lexically contain Decls that are not properly
1008 // nested in the AST. When we identify such cases, we need to retrofit
1009 // this nesting here.
1010 if (!DI_current && !FileDI_current)
1011 return VisitDeclContext(D);
1012
1013 // Scan the Decls that immediately come after the container
1014 // in the current DeclContext. If any fall within the
1015 // container's lexical region, stash them into a vector
1016 // for later processing.
1017 SmallVector<Decl *, 24> DeclsInContainer;
1018 SourceLocation EndLoc = D->getSourceRange().getEnd();
1019 SourceManager &SM = AU->getSourceManager();
1020 if (EndLoc.isValid()) {
1021 if (DI_current) {
1022 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
1023 DeclsInContainer);
1024 } else {
1025 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1026 DeclsInContainer);
1027 }
1028 }
1029
1030 // The common case.
1031 if (DeclsInContainer.empty())
1032 return VisitDeclContext(D);
1033
1034 // Get all the Decls in the DeclContext, and sort them with the
1035 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +00001036 for (auto *SubDecl : D->decls()) {
1037 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001038 SubDecl->getBeginLoc().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001039 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001040 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001041 }
1042
1043 // Now sort the Decls so that they appear in lexical order.
Fangrui Song55fab262018-09-26 22:16:28 +00001044 llvm::sort(DeclsInContainer,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001045 [&SM](Decl *A, Decl *B) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001046 SourceLocation L_A = A->getBeginLoc();
1047 SourceLocation L_B = B->getBeginLoc();
1048 return L_A != L_B ? SM.isBeforeInTranslationUnit(L_A, L_B)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001049 : SM.isBeforeInTranslationUnit(A->getEndLoc(),
1050 B->getEndLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001051 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001052
1053 // Now visit the decls.
1054 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1055 E = DeclsInContainer.end(); I != E; ++I) {
1056 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001057 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001058 if (!V.hasValue())
1059 continue;
1060 if (!V.getValue())
1061 return false;
1062 if (Visit(Cursor, true))
1063 return true;
1064 }
1065 return false;
1066}
1067
1068bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1069 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1070 TU)))
1071 return true;
1072
Douglas Gregore9d95f12015-07-07 03:57:35 +00001073 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1074 return true;
1075
Guy Benyei11169dd2012-12-18 14:30:41 +00001076 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1077 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1078 E = ND->protocol_end(); I != E; ++I, ++PL)
1079 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1080 return true;
1081
1082 return VisitObjCContainerDecl(ND);
1083}
1084
1085bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1086 if (!PID->isThisDeclarationADefinition())
1087 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1088
1089 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1090 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1091 E = PID->protocol_end(); I != E; ++I, ++PL)
1092 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1093 return true;
1094
1095 return VisitObjCContainerDecl(PID);
1096}
1097
1098bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1099 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1100 return true;
1101
1102 // FIXME: This implements a workaround with @property declarations also being
1103 // installed in the DeclContext for the @interface. Eventually this code
1104 // should be removed.
1105 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1106 if (!CDecl || !CDecl->IsClassExtension())
1107 return false;
1108
1109 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1110 if (!ID)
1111 return false;
1112
1113 IdentifierInfo *PropertyId = PD->getIdentifier();
1114 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001115 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1116 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001117
1118 if (!prevDecl)
1119 return false;
1120
1121 // Visit synthesized methods since they will be skipped when visiting
1122 // the @interface.
1123 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1124 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1125 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1126 return true;
1127
1128 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1129 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1130 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1131 return true;
1132
1133 return false;
1134}
1135
Douglas Gregore9d95f12015-07-07 03:57:35 +00001136bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1137 if (!typeParamList)
1138 return false;
1139
1140 for (auto *typeParam : *typeParamList) {
1141 // Visit the type parameter.
1142 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1143 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001144 }
1145
1146 return false;
1147}
1148
Guy Benyei11169dd2012-12-18 14:30:41 +00001149bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1150 if (!D->isThisDeclarationADefinition()) {
1151 // Forward declaration is treated like a reference.
1152 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1153 }
1154
Douglas Gregore9d95f12015-07-07 03:57:35 +00001155 // Objective-C type parameters.
1156 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1157 return true;
1158
Guy Benyei11169dd2012-12-18 14:30:41 +00001159 // Issue callbacks for super class.
1160 if (D->getSuperClass() &&
1161 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1162 D->getSuperClassLoc(),
1163 TU)))
1164 return true;
1165
Douglas Gregore9d95f12015-07-07 03:57:35 +00001166 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1167 if (Visit(SuperClassTInfo->getTypeLoc()))
1168 return true;
1169
Guy Benyei11169dd2012-12-18 14:30:41 +00001170 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1171 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1172 E = D->protocol_end(); I != E; ++I, ++PL)
1173 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1174 return true;
1175
1176 return VisitObjCContainerDecl(D);
1177}
1178
1179bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1180 return VisitObjCContainerDecl(D);
1181}
1182
1183bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1184 // 'ID' could be null when dealing with invalid code.
1185 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1186 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1187 return true;
1188
1189 return VisitObjCImplDecl(D);
1190}
1191
1192bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1193#if 0
1194 // Issue callbacks for super class.
1195 // FIXME: No source location information!
1196 if (D->getSuperClass() &&
1197 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1198 D->getSuperClassLoc(),
1199 TU)))
1200 return true;
1201#endif
1202
1203 return VisitObjCImplDecl(D);
1204}
1205
1206bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1207 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1208 if (PD->isIvarNameSpecified())
1209 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1210
1211 return false;
1212}
1213
1214bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1215 return VisitDeclContext(D);
1216}
1217
1218bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1219 // Visit nested-name-specifier.
1220 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1221 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1222 return true;
1223
1224 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1225 D->getTargetNameLoc(), TU));
1226}
1227
1228bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1229 // Visit nested-name-specifier.
1230 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1231 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1232 return true;
1233 }
1234
1235 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1236 return true;
1237
1238 return VisitDeclarationNameInfo(D->getNameInfo());
1239}
1240
1241bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1242 // Visit nested-name-specifier.
1243 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1244 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1245 return true;
1246
1247 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1248 D->getIdentLocation(), TU));
1249}
1250
1251bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1252 // Visit nested-name-specifier.
1253 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1254 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1255 return true;
1256 }
1257
1258 return VisitDeclarationNameInfo(D->getNameInfo());
1259}
1260
1261bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1262 UnresolvedUsingTypenameDecl *D) {
1263 // Visit nested-name-specifier.
1264 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1265 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1266 return true;
1267
1268 return false;
1269}
1270
Olivier Goffart81978012016-06-09 16:15:55 +00001271bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1272 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1273 return true;
Richard Trieuf3b77662016-09-13 01:37:01 +00001274 if (StringLiteral *Message = D->getMessage())
1275 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1276 return true;
Olivier Goffart81978012016-06-09 16:15:55 +00001277 return false;
1278}
1279
Olivier Goffartd211c642016-11-04 06:29:27 +00001280bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1281 if (NamedDecl *FriendD = D->getFriendDecl()) {
1282 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1283 return true;
1284 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1285 if (Visit(TI->getTypeLoc()))
1286 return true;
1287 }
1288 return false;
1289}
1290
Guy Benyei11169dd2012-12-18 14:30:41 +00001291bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1292 switch (Name.getName().getNameKind()) {
1293 case clang::DeclarationName::Identifier:
1294 case clang::DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001295 case clang::DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001296 case clang::DeclarationName::CXXOperatorName:
1297 case clang::DeclarationName::CXXUsingDirective:
1298 return false;
Richard Smith35845152017-02-07 01:37:30 +00001299
Guy Benyei11169dd2012-12-18 14:30:41 +00001300 case clang::DeclarationName::CXXConstructorName:
1301 case clang::DeclarationName::CXXDestructorName:
1302 case clang::DeclarationName::CXXConversionFunctionName:
1303 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1304 return Visit(TSInfo->getTypeLoc());
1305 return false;
1306
1307 case clang::DeclarationName::ObjCZeroArgSelector:
1308 case clang::DeclarationName::ObjCOneArgSelector:
1309 case clang::DeclarationName::ObjCMultiArgSelector:
1310 // FIXME: Per-identifier location info?
1311 return false;
1312 }
1313
1314 llvm_unreachable("Invalid DeclarationName::Kind!");
1315}
1316
1317bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1318 SourceRange Range) {
1319 // FIXME: This whole routine is a hack to work around the lack of proper
1320 // source information in nested-name-specifiers (PR5791). Since we do have
1321 // a beginning source location, we can visit the first component of the
1322 // nested-name-specifier, if it's a single-token component.
1323 if (!NNS)
1324 return false;
1325
1326 // Get the first component in the nested-name-specifier.
1327 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1328 NNS = Prefix;
1329
1330 switch (NNS->getKind()) {
1331 case NestedNameSpecifier::Namespace:
1332 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1333 TU));
1334
1335 case NestedNameSpecifier::NamespaceAlias:
1336 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1337 Range.getBegin(), TU));
1338
1339 case NestedNameSpecifier::TypeSpec: {
1340 // If the type has a form where we know that the beginning of the source
1341 // range matches up with a reference cursor. Visit the appropriate reference
1342 // cursor.
1343 const Type *T = NNS->getAsType();
1344 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1345 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1346 if (const TagType *Tag = dyn_cast<TagType>(T))
1347 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1348 if (const TemplateSpecializationType *TST
1349 = dyn_cast<TemplateSpecializationType>(T))
1350 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1351 break;
1352 }
1353
1354 case NestedNameSpecifier::TypeSpecWithTemplate:
1355 case NestedNameSpecifier::Global:
1356 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001357 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001358 break;
1359 }
1360
1361 return false;
1362}
1363
1364bool
1365CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1366 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1367 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1368 Qualifiers.push_back(Qualifier);
1369
1370 while (!Qualifiers.empty()) {
1371 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1372 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1373 switch (NNS->getKind()) {
1374 case NestedNameSpecifier::Namespace:
1375 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1376 Q.getLocalBeginLoc(),
1377 TU)))
1378 return true;
1379
1380 break;
1381
1382 case NestedNameSpecifier::NamespaceAlias:
1383 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1384 Q.getLocalBeginLoc(),
1385 TU)))
1386 return true;
1387
1388 break;
1389
1390 case NestedNameSpecifier::TypeSpec:
1391 case NestedNameSpecifier::TypeSpecWithTemplate:
1392 if (Visit(Q.getTypeLoc()))
1393 return true;
1394
1395 break;
1396
1397 case NestedNameSpecifier::Global:
1398 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001399 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001400 break;
1401 }
1402 }
1403
1404 return false;
1405}
1406
1407bool CursorVisitor::VisitTemplateParameters(
1408 const TemplateParameterList *Params) {
1409 if (!Params)
1410 return false;
1411
1412 for (TemplateParameterList::const_iterator P = Params->begin(),
1413 PEnd = Params->end();
1414 P != PEnd; ++P) {
1415 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1416 return true;
1417 }
1418
1419 return false;
1420}
1421
1422bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1423 switch (Name.getKind()) {
1424 case TemplateName::Template:
1425 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1426
1427 case TemplateName::OverloadedTemplate:
1428 // Visit the overloaded template set.
1429 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1430 return true;
1431
1432 return false;
1433
Richard Smithb23c5e82019-05-09 03:31:27 +00001434 case TemplateName::AssumedTemplate:
1435 // FIXME: Visit DeclarationName?
1436 return false;
1437
Guy Benyei11169dd2012-12-18 14:30:41 +00001438 case TemplateName::DependentTemplate:
1439 // FIXME: Visit nested-name-specifier.
1440 return false;
1441
1442 case TemplateName::QualifiedTemplate:
1443 // FIXME: Visit nested-name-specifier.
1444 return Visit(MakeCursorTemplateRef(
1445 Name.getAsQualifiedTemplateName()->getDecl(),
1446 Loc, TU));
1447
1448 case TemplateName::SubstTemplateTemplateParm:
1449 return Visit(MakeCursorTemplateRef(
1450 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1451 Loc, TU));
1452
1453 case TemplateName::SubstTemplateTemplateParmPack:
1454 return Visit(MakeCursorTemplateRef(
1455 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1456 Loc, TU));
1457 }
1458
1459 llvm_unreachable("Invalid TemplateName::Kind!");
1460}
1461
1462bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1463 switch (TAL.getArgument().getKind()) {
1464 case TemplateArgument::Null:
1465 case TemplateArgument::Integral:
1466 case TemplateArgument::Pack:
1467 return false;
1468
1469 case TemplateArgument::Type:
1470 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1471 return Visit(TSInfo->getTypeLoc());
1472 return false;
1473
1474 case TemplateArgument::Declaration:
1475 if (Expr *E = TAL.getSourceDeclExpression())
1476 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1477 return false;
1478
1479 case TemplateArgument::NullPtr:
1480 if (Expr *E = TAL.getSourceNullPtrExpression())
1481 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1482 return false;
1483
1484 case TemplateArgument::Expression:
1485 if (Expr *E = TAL.getSourceExpression())
1486 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1487 return false;
1488
1489 case TemplateArgument::Template:
1490 case TemplateArgument::TemplateExpansion:
1491 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1492 return true;
1493
1494 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1495 TAL.getTemplateNameLoc());
1496 }
1497
1498 llvm_unreachable("Invalid TemplateArgument::Kind!");
1499}
1500
1501bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1502 return VisitDeclContext(D);
1503}
1504
1505bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1506 return Visit(TL.getUnqualifiedLoc());
1507}
1508
1509bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1510 ASTContext &Context = AU->getASTContext();
1511
1512 // Some builtin types (such as Objective-C's "id", "sel", and
1513 // "Class") have associated declarations. Create cursors for those.
1514 QualType VisitType;
1515 switch (TL.getTypePtr()->getKind()) {
1516
1517 case BuiltinType::Void:
1518 case BuiltinType::NullPtr:
1519 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001520#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1521 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001522#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001523#define EXT_OPAQUE_TYPE(ExtTYpe, Id, Ext) \
1524 case BuiltinType::Id:
1525#include "clang/Basic/OpenCLExtensionTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001526 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001527 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001528 case BuiltinType::OCLClkEvent:
1529 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001530 case BuiltinType::OCLReserveID:
Richard Sandifordeb485fb2019-08-09 08:52:54 +00001531#define SVE_TYPE(Name, Id, SingletonId) \
1532 case BuiltinType::Id:
1533#include "clang/Basic/AArch64SVEACLETypes.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00001534#define BUILTIN_TYPE(Id, SingletonId)
1535#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1536#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1537#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1538#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1539#include "clang/AST/BuiltinTypes.def"
1540 break;
1541
1542 case BuiltinType::ObjCId:
1543 VisitType = Context.getObjCIdType();
1544 break;
1545
1546 case BuiltinType::ObjCClass:
1547 VisitType = Context.getObjCClassType();
1548 break;
1549
1550 case BuiltinType::ObjCSel:
1551 VisitType = Context.getObjCSelType();
1552 break;
1553 }
1554
1555 if (!VisitType.isNull()) {
1556 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1557 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1558 TU));
1559 }
1560
1561 return false;
1562}
1563
1564bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1565 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1566}
1567
1568bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1569 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1570}
1571
1572bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1573 if (TL.isDefinition())
1574 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1575
1576 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1577}
1578
1579bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1580 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1581}
1582
1583bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001584 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001585}
1586
Manman Rene6be26c2016-09-13 17:25:08 +00001587bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001588 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getBeginLoc(), TU)))
Manman Rene6be26c2016-09-13 17:25:08 +00001589 return true;
1590 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1591 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1592 TU)))
1593 return true;
1594 }
1595
1596 return false;
1597}
1598
Guy Benyei11169dd2012-12-18 14:30:41 +00001599bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1600 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1601 return true;
1602
Douglas Gregore9d95f12015-07-07 03:57:35 +00001603 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1604 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1605 return true;
1606 }
1607
Guy Benyei11169dd2012-12-18 14:30:41 +00001608 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1609 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1610 TU)))
1611 return true;
1612 }
1613
1614 return false;
1615}
1616
1617bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1618 return Visit(TL.getPointeeLoc());
1619}
1620
1621bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1622 return Visit(TL.getInnerLoc());
1623}
1624
Leonard Chanc72aaf62019-05-07 03:20:17 +00001625bool CursorVisitor::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
1626 return Visit(TL.getInnerLoc());
1627}
1628
Guy Benyei11169dd2012-12-18 14:30:41 +00001629bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1630 return Visit(TL.getPointeeLoc());
1631}
1632
1633bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1634 return Visit(TL.getPointeeLoc());
1635}
1636
1637bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1638 return Visit(TL.getPointeeLoc());
1639}
1640
1641bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1642 return Visit(TL.getPointeeLoc());
1643}
1644
1645bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1646 return Visit(TL.getPointeeLoc());
1647}
1648
1649bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1650 return Visit(TL.getModifiedLoc());
1651}
1652
1653bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1654 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001655 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001656 return true;
1657
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001658 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1659 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001660 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1661 return true;
1662
1663 return false;
1664}
1665
1666bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1667 if (Visit(TL.getElementLoc()))
1668 return true;
1669
1670 if (Expr *Size = TL.getSizeExpr())
1671 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1672
1673 return false;
1674}
1675
Reid Kleckner8a365022013-06-24 17:51:48 +00001676bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1677 return Visit(TL.getOriginalLoc());
1678}
1679
Reid Kleckner0503a872013-12-05 01:23:43 +00001680bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1681 return Visit(TL.getOriginalLoc());
1682}
1683
Richard Smith600b5262017-01-26 20:40:47 +00001684bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1685 DeducedTemplateSpecializationTypeLoc TL) {
1686 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1687 TL.getTemplateNameLoc()))
1688 return true;
1689
1690 return false;
1691}
1692
Guy Benyei11169dd2012-12-18 14:30:41 +00001693bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1694 TemplateSpecializationTypeLoc TL) {
1695 // Visit the template name.
1696 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1697 TL.getTemplateNameLoc()))
1698 return true;
1699
1700 // Visit the template arguments.
1701 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1702 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1703 return true;
1704
1705 return false;
1706}
1707
1708bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1709 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1710}
1711
1712bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1713 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1714 return Visit(TSInfo->getTypeLoc());
1715
1716 return false;
1717}
1718
1719bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1720 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1721 return Visit(TSInfo->getTypeLoc());
1722
1723 return false;
1724}
1725
1726bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001727 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001728}
1729
1730bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1731 DependentTemplateSpecializationTypeLoc TL) {
1732 // Visit the nested-name-specifier, if there is one.
1733 if (TL.getQualifierLoc() &&
1734 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1735 return true;
1736
1737 // Visit the template arguments.
1738 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1739 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1740 return true;
1741
1742 return false;
1743}
1744
1745bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1746 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1747 return true;
1748
1749 return Visit(TL.getNamedTypeLoc());
1750}
1751
1752bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1753 return Visit(TL.getPatternLoc());
1754}
1755
1756bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1757 if (Expr *E = TL.getUnderlyingExpr())
1758 return Visit(MakeCXCursor(E, StmtParent, TU));
1759
1760 return false;
1761}
1762
1763bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1764 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1765}
1766
1767bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1768 return Visit(TL.getValueLoc());
1769}
1770
Xiuli Pan9c14e282016-01-09 12:53:17 +00001771bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1772 return Visit(TL.getValueLoc());
1773}
1774
Guy Benyei11169dd2012-12-18 14:30:41 +00001775#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1776bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1777 return Visit##PARENT##Loc(TL); \
1778}
1779
1780DEFAULT_TYPELOC_IMPL(Complex, Type)
1781DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1782DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1783DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1784DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001785DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
Erich Keanef702b022018-07-13 19:46:04 +00001786DEFAULT_TYPELOC_IMPL(DependentVector, Type)
Guy Benyei11169dd2012-12-18 14:30:41 +00001787DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1788DEFAULT_TYPELOC_IMPL(Vector, Type)
1789DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1790DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1791DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1792DEFAULT_TYPELOC_IMPL(Record, TagType)
1793DEFAULT_TYPELOC_IMPL(Enum, TagType)
1794DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1795DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1796DEFAULT_TYPELOC_IMPL(Auto, Type)
1797
1798bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1799 // Visit the nested-name-specifier, if present.
1800 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1801 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1802 return true;
1803
1804 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001805 for (const auto &I : D->bases()) {
1806 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001807 return true;
1808 }
1809 }
1810
1811 return VisitTagDecl(D);
1812}
1813
1814bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001815 for (const auto *I : D->attrs())
Michael Wu40ff1052018-08-03 05:20:23 +00001816 if ((TU->ParsingOptions & CXTranslationUnit_VisitImplicitAttributes ||
1817 !I->isImplicit()) &&
1818 Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001819 return true;
1820
1821 return false;
1822}
1823
1824//===----------------------------------------------------------------------===//
1825// Data-recursive visitor methods.
1826//===----------------------------------------------------------------------===//
1827
1828namespace {
1829#define DEF_JOB(NAME, DATA, KIND)\
1830class NAME : public VisitorJob {\
1831public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001832 NAME(const DATA *d, CXCursor parent) : \
1833 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001834 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001835 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001836};
1837
1838DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1839DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1840DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1841DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001842DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1843DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1844DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1845#undef DEF_JOB
1846
James Y Knight04ec5bf2015-12-24 02:59:37 +00001847class ExplicitTemplateArgsVisit : public VisitorJob {
1848public:
1849 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1850 const TemplateArgumentLoc *End, CXCursor parent)
1851 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1852 End) {}
1853 static bool classof(const VisitorJob *VJ) {
1854 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1855 }
1856 const TemplateArgumentLoc *begin() const {
1857 return static_cast<const TemplateArgumentLoc *>(data[0]);
1858 }
1859 const TemplateArgumentLoc *end() {
1860 return static_cast<const TemplateArgumentLoc *>(data[1]);
1861 }
1862};
Guy Benyei11169dd2012-12-18 14:30:41 +00001863class DeclVisit : public VisitorJob {
1864public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001865 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001866 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001867 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001868 static bool classof(const VisitorJob *VJ) {
1869 return VJ->getKind() == DeclVisitKind;
1870 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001871 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001872 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001873};
1874class TypeLocVisit : public VisitorJob {
1875public:
1876 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1877 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1878 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1879
1880 static bool classof(const VisitorJob *VJ) {
1881 return VJ->getKind() == TypeLocVisitKind;
1882 }
1883
1884 TypeLoc get() const {
1885 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001886 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001887 }
1888};
1889
1890class LabelRefVisit : public VisitorJob {
1891public:
1892 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1893 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1894 labelLoc.getPtrEncoding()) {}
1895
1896 static bool classof(const VisitorJob *VJ) {
1897 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1898 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001899 const LabelDecl *get() const {
1900 return static_cast<const LabelDecl *>(data[0]);
1901 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001902 SourceLocation getLoc() const {
1903 return SourceLocation::getFromPtrEncoding(data[1]); }
1904};
1905
1906class NestedNameSpecifierLocVisit : public VisitorJob {
1907public:
1908 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1909 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1910 Qualifier.getNestedNameSpecifier(),
1911 Qualifier.getOpaqueData()) { }
1912
1913 static bool classof(const VisitorJob *VJ) {
1914 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1915 }
1916
1917 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001918 return NestedNameSpecifierLoc(
1919 const_cast<NestedNameSpecifier *>(
1920 static_cast<const NestedNameSpecifier *>(data[0])),
1921 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001922 }
1923};
1924
1925class DeclarationNameInfoVisit : public VisitorJob {
1926public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001927 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001928 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001929 static bool classof(const VisitorJob *VJ) {
1930 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1931 }
1932 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001933 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001934 switch (S->getStmtClass()) {
1935 default:
1936 llvm_unreachable("Unhandled Stmt");
1937 case clang::Stmt::MSDependentExistsStmtClass:
1938 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1939 case Stmt::CXXDependentScopeMemberExprClass:
1940 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1941 case Stmt::DependentScopeDeclRefExprClass:
1942 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001943 case Stmt::OMPCriticalDirectiveClass:
1944 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001945 }
1946 }
1947};
1948class MemberRefVisit : public VisitorJob {
1949public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001950 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001951 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1952 L.getPtrEncoding()) {}
1953 static bool classof(const VisitorJob *VJ) {
1954 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1955 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001956 const FieldDecl *get() const {
1957 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001958 }
1959 SourceLocation getLoc() const {
1960 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1961 }
1962};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001963class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001964 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001965 VisitorWorkList &WL;
1966 CXCursor Parent;
1967public:
1968 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1969 : WL(wl), Parent(parent) {}
1970
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001971 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1972 void VisitBlockExpr(const BlockExpr *B);
1973 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1974 void VisitCompoundStmt(const CompoundStmt *S);
1975 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1976 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1977 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1978 void VisitCXXNewExpr(const CXXNewExpr *E);
1979 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1980 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1981 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1982 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1983 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1984 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1985 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1986 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001987 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001988 void VisitDeclRefExpr(const DeclRefExpr *D);
1989 void VisitDeclStmt(const DeclStmt *S);
1990 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1991 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1992 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1993 void VisitForStmt(const ForStmt *FS);
1994 void VisitGotoStmt(const GotoStmt *GS);
1995 void VisitIfStmt(const IfStmt *If);
1996 void VisitInitListExpr(const InitListExpr *IE);
1997 void VisitMemberExpr(const MemberExpr *M);
1998 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1999 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
2000 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
2001 void VisitOverloadExpr(const OverloadExpr *E);
2002 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
2003 void VisitStmt(const Stmt *S);
2004 void VisitSwitchStmt(const SwitchStmt *S);
2005 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002006 void VisitTypeTraitExpr(const TypeTraitExpr *E);
2007 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
2008 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
2009 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
2010 void VisitVAArgExpr(const VAArgExpr *E);
2011 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
2012 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
2013 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
2014 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002015 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00002016 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002017 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002018 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002019 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002020 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002021 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002022 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002023 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00002024 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002025 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002026 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002027 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002028 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002029 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00002030 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002031 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00002032 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002033 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002034 void
2035 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00002036 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00002037 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002038 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00002039 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002040 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00002041 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00002042 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00002043 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002044 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002045 void
2046 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002047 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002048 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002049 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002050 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002051 void VisitOMPDistributeParallelForDirective(
2052 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00002053 void VisitOMPDistributeParallelForSimdDirective(
2054 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002055 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002056 void VisitOMPTargetParallelForSimdDirective(
2057 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002058 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002059 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002060 void VisitOMPTeamsDistributeSimdDirective(
2061 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002062 void VisitOMPTeamsDistributeParallelForSimdDirective(
2063 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002064 void VisitOMPTeamsDistributeParallelForDirective(
2065 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002066 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002067 void VisitOMPTargetTeamsDistributeDirective(
2068 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002069 void VisitOMPTargetTeamsDistributeParallelForDirective(
2070 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002071 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2072 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002073 void VisitOMPTargetTeamsDistributeSimdDirective(
2074 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002075
Guy Benyei11169dd2012-12-18 14:30:41 +00002076private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002077 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002078 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002079 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2080 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002081 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2082 void AddStmt(const Stmt *S);
2083 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002084 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002085 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002086 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002087};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002088} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002089
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002090void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002091 // 'S' should always be non-null, since it comes from the
2092 // statement we are visiting.
2093 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2094}
2095
2096void
2097EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2098 if (Qualifier)
2099 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2100}
2101
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002102void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002103 if (S)
2104 WL.push_back(StmtVisit(S, Parent));
2105}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002106void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002107 if (D)
2108 WL.push_back(DeclVisit(D, Parent, isFirst));
2109}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002110void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2111 unsigned NumTemplateArgs) {
2112 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002113}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002114void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002115 if (D)
2116 WL.push_back(MemberRefVisit(D, L, Parent));
2117}
2118void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2119 if (TI)
2120 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2121 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002122void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002123 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002124 for (const Stmt *SubStmt : S->children()) {
2125 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002126 }
2127 if (size == WL.size())
2128 return;
2129 // Now reverse the entries we just added. This will match the DFS
2130 // ordering performed by the worklist.
2131 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2132 std::reverse(I, E);
2133}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002134namespace {
2135class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2136 EnqueueVisitor *Visitor;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002137 /// Process clauses with list of variables.
Alexey Bataev756c1962013-09-24 03:17:45 +00002138 template <typename T>
2139 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002140public:
2141 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2142#define OPENMP_CLAUSE(Name, Class) \
2143 void Visit##Class(const Class *C);
2144#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002145 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002146 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002147};
2148
Alexey Bataev3392d762016-02-16 11:18:12 +00002149void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2150 const OMPClauseWithPreInit *C) {
2151 Visitor->AddStmt(C->getPreInitStmt());
2152}
2153
Alexey Bataev005248a2016-02-25 05:25:57 +00002154void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2155 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002156 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002157 Visitor->AddStmt(C->getPostUpdateExpr());
2158}
2159
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002160void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002161 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002162 Visitor->AddStmt(C->getCondition());
2163}
2164
Alexey Bataev3778b602014-07-17 07:32:53 +00002165void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2166 Visitor->AddStmt(C->getCondition());
2167}
2168
Alexey Bataev568a8332014-03-06 06:15:19 +00002169void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002170 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002171 Visitor->AddStmt(C->getNumThreads());
2172}
2173
Alexey Bataev62c87d22014-03-21 04:51:18 +00002174void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2175 Visitor->AddStmt(C->getSafelen());
2176}
2177
Alexey Bataev66b15b52015-08-21 11:14:16 +00002178void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2179 Visitor->AddStmt(C->getSimdlen());
2180}
2181
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002182void OMPClauseEnqueue::VisitOMPAllocatorClause(const OMPAllocatorClause *C) {
2183 Visitor->AddStmt(C->getAllocator());
2184}
2185
Alexander Musman8bd31e62014-05-27 15:12:19 +00002186void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2187 Visitor->AddStmt(C->getNumForLoops());
2188}
2189
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002190void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002191
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002192void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2193
Alexey Bataev56dafe82014-06-20 07:16:17 +00002194void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002195 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002196 Visitor->AddStmt(C->getChunkSize());
2197}
2198
Alexey Bataev10e775f2015-07-30 11:36:16 +00002199void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2200 Visitor->AddStmt(C->getNumForLoops());
2201}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002202
Alexey Bataev236070f2014-06-20 11:19:47 +00002203void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2204
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002205void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2206
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002207void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2208
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002209void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2210
Alexey Bataevdea47612014-07-23 07:46:59 +00002211void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2212
Alexey Bataev67a4f222014-07-23 10:25:33 +00002213void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2214
Alexey Bataev459dec02014-07-24 06:46:57 +00002215void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2216
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002217void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2218
Alexey Bataev346265e2015-09-25 10:37:12 +00002219void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2220
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002221void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2222
Alexey Bataevb825de12015-12-07 10:51:44 +00002223void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2224
Kelvin Li1408f912018-09-26 04:28:39 +00002225void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2226 const OMPUnifiedAddressClause *) {}
2227
Patrick Lyster4a370b92018-10-01 13:47:43 +00002228void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2229 const OMPUnifiedSharedMemoryClause *) {}
2230
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00002231void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2232 const OMPReverseOffloadClause *) {}
2233
Patrick Lyster3fe9e392018-10-11 14:41:10 +00002234void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2235 const OMPDynamicAllocatorsClause *) {}
2236
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00002237void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2238 const OMPAtomicDefaultMemOrderClause *) {}
2239
Michael Wonge710d542015-08-07 16:16:36 +00002240void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2241 Visitor->AddStmt(C->getDevice());
2242}
2243
Kelvin Li099bb8c2015-11-24 20:50:12 +00002244void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002245 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002246 Visitor->AddStmt(C->getNumTeams());
2247}
2248
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002249void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002250 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002251 Visitor->AddStmt(C->getThreadLimit());
2252}
2253
Alexey Bataeva0569352015-12-01 10:17:31 +00002254void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2255 Visitor->AddStmt(C->getPriority());
2256}
2257
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002258void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2259 Visitor->AddStmt(C->getGrainsize());
2260}
2261
Alexey Bataev382967a2015-12-08 12:06:20 +00002262void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2263 Visitor->AddStmt(C->getNumTasks());
2264}
2265
Alexey Bataev28c75412015-12-15 08:19:24 +00002266void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2267 Visitor->AddStmt(C->getHint());
2268}
2269
Alexey Bataev756c1962013-09-24 03:17:45 +00002270template<typename T>
2271void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002272 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002273 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002274 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002275}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002276
Alexey Bataeve04483e2019-03-27 14:14:31 +00002277void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) {
2278 VisitOMPClauseList(C);
2279 Visitor->AddStmt(C->getAllocator());
2280}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002281void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002282 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002283 for (const auto *E : C->private_copies()) {
2284 Visitor->AddStmt(E);
2285 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002286}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002287void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2288 const OMPFirstprivateClause *C) {
2289 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002290 VisitOMPClauseWithPreInit(C);
2291 for (const auto *E : C->private_copies()) {
2292 Visitor->AddStmt(E);
2293 }
2294 for (const auto *E : C->inits()) {
2295 Visitor->AddStmt(E);
2296 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002297}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002298void OMPClauseEnqueue::VisitOMPLastprivateClause(
2299 const OMPLastprivateClause *C) {
2300 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002301 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002302 for (auto *E : C->private_copies()) {
2303 Visitor->AddStmt(E);
2304 }
2305 for (auto *E : C->source_exprs()) {
2306 Visitor->AddStmt(E);
2307 }
2308 for (auto *E : C->destination_exprs()) {
2309 Visitor->AddStmt(E);
2310 }
2311 for (auto *E : C->assignment_ops()) {
2312 Visitor->AddStmt(E);
2313 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002314}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002315void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002316 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002317}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002318void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2319 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002320 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002321 for (auto *E : C->privates()) {
2322 Visitor->AddStmt(E);
2323 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002324 for (auto *E : C->lhs_exprs()) {
2325 Visitor->AddStmt(E);
2326 }
2327 for (auto *E : C->rhs_exprs()) {
2328 Visitor->AddStmt(E);
2329 }
2330 for (auto *E : C->reduction_ops()) {
2331 Visitor->AddStmt(E);
2332 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002333}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002334void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2335 const OMPTaskReductionClause *C) {
2336 VisitOMPClauseList(C);
2337 VisitOMPClauseWithPostUpdate(C);
2338 for (auto *E : C->privates()) {
2339 Visitor->AddStmt(E);
2340 }
2341 for (auto *E : C->lhs_exprs()) {
2342 Visitor->AddStmt(E);
2343 }
2344 for (auto *E : C->rhs_exprs()) {
2345 Visitor->AddStmt(E);
2346 }
2347 for (auto *E : C->reduction_ops()) {
2348 Visitor->AddStmt(E);
2349 }
2350}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002351void OMPClauseEnqueue::VisitOMPInReductionClause(
2352 const OMPInReductionClause *C) {
2353 VisitOMPClauseList(C);
2354 VisitOMPClauseWithPostUpdate(C);
2355 for (auto *E : C->privates()) {
2356 Visitor->AddStmt(E);
2357 }
2358 for (auto *E : C->lhs_exprs()) {
2359 Visitor->AddStmt(E);
2360 }
2361 for (auto *E : C->rhs_exprs()) {
2362 Visitor->AddStmt(E);
2363 }
2364 for (auto *E : C->reduction_ops()) {
2365 Visitor->AddStmt(E);
2366 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002367 for (auto *E : C->taskgroup_descriptors())
2368 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002369}
Alexander Musman8dba6642014-04-22 13:09:42 +00002370void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2371 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002372 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002373 for (const auto *E : C->privates()) {
2374 Visitor->AddStmt(E);
2375 }
Alexander Musman3276a272015-03-21 10:12:56 +00002376 for (const auto *E : C->inits()) {
2377 Visitor->AddStmt(E);
2378 }
2379 for (const auto *E : C->updates()) {
2380 Visitor->AddStmt(E);
2381 }
2382 for (const auto *E : C->finals()) {
2383 Visitor->AddStmt(E);
2384 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002385 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002386 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002387}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002388void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2389 VisitOMPClauseList(C);
2390 Visitor->AddStmt(C->getAlignment());
2391}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002392void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2393 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002394 for (auto *E : C->source_exprs()) {
2395 Visitor->AddStmt(E);
2396 }
2397 for (auto *E : C->destination_exprs()) {
2398 Visitor->AddStmt(E);
2399 }
2400 for (auto *E : C->assignment_ops()) {
2401 Visitor->AddStmt(E);
2402 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002403}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002404void
2405OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2406 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002407 for (auto *E : C->source_exprs()) {
2408 Visitor->AddStmt(E);
2409 }
2410 for (auto *E : C->destination_exprs()) {
2411 Visitor->AddStmt(E);
2412 }
2413 for (auto *E : C->assignment_ops()) {
2414 Visitor->AddStmt(E);
2415 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002416}
Alexey Bataev6125da92014-07-21 11:26:11 +00002417void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2418 VisitOMPClauseList(C);
2419}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002420void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2421 VisitOMPClauseList(C);
2422}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002423void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2424 VisitOMPClauseList(C);
2425}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002426void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2427 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002428 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002429 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002430}
Alexey Bataev3392d762016-02-16 11:18:12 +00002431void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2432 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002433void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2434 VisitOMPClauseList(C);
2435}
Samuel Antaoec172c62016-05-26 17:49:04 +00002436void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2437 VisitOMPClauseList(C);
2438}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002439void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2440 VisitOMPClauseList(C);
2441}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002442void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2443 VisitOMPClauseList(C);
2444}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002445}
Alexey Bataev756c1962013-09-24 03:17:45 +00002446
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002447void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2448 unsigned size = WL.size();
2449 OMPClauseEnqueue Visitor(this);
2450 Visitor.Visit(S);
2451 if (size == WL.size())
2452 return;
2453 // Now reverse the entries we just added. This will match the DFS
2454 // ordering performed by the worklist.
2455 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2456 std::reverse(I, E);
2457}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002458void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002459 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2460}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002461void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002462 AddDecl(B->getBlockDecl());
2463}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002464void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002465 EnqueueChildren(E);
2466 AddTypeLoc(E->getTypeSourceInfo());
2467}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002468void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002469 for (auto &I : llvm::reverse(S->body()))
2470 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002471}
2472void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002473VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002474 AddStmt(S->getSubStmt());
2475 AddDeclarationNameInfo(S);
2476 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2477 AddNestedNameSpecifierLoc(QualifierLoc);
2478}
2479
2480void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002481VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002482 if (E->hasExplicitTemplateArgs())
2483 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002484 AddDeclarationNameInfo(E);
2485 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2486 AddNestedNameSpecifierLoc(QualifierLoc);
2487 if (!E->isImplicitAccess())
2488 AddStmt(E->getBase());
2489}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002490void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002491 // Enqueue the initializer , if any.
2492 AddStmt(E->getInitializer());
2493 // Enqueue the array size, if any.
Richard Smithb9fb1212019-05-06 03:47:15 +00002494 AddStmt(E->getArraySize().getValueOr(nullptr));
Guy Benyei11169dd2012-12-18 14:30:41 +00002495 // Enqueue the allocated type.
2496 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2497 // Enqueue the placement arguments.
2498 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2499 AddStmt(E->getPlacementArg(I-1));
2500}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002501void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002502 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2503 AddStmt(CE->getArg(I-1));
2504 AddStmt(CE->getCallee());
2505 AddStmt(CE->getArg(0));
2506}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002507void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2508 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002509 // Visit the name of the type being destroyed.
2510 AddTypeLoc(E->getDestroyedTypeInfo());
2511 // Visit the scope type that looks disturbingly like the nested-name-specifier
2512 // but isn't.
2513 AddTypeLoc(E->getScopeTypeInfo());
2514 // Visit the nested-name-specifier.
2515 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2516 AddNestedNameSpecifierLoc(QualifierLoc);
2517 // Visit base expression.
2518 AddStmt(E->getBase());
2519}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002520void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2521 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002522 AddTypeLoc(E->getTypeSourceInfo());
2523}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002524void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2525 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002526 EnqueueChildren(E);
2527 AddTypeLoc(E->getTypeSourceInfo());
2528}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002529void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002530 EnqueueChildren(E);
2531 if (E->isTypeOperand())
2532 AddTypeLoc(E->getTypeOperandSourceInfo());
2533}
2534
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002535void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2536 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002537 EnqueueChildren(E);
2538 AddTypeLoc(E->getTypeSourceInfo());
2539}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002540void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002541 EnqueueChildren(E);
2542 if (E->isTypeOperand())
2543 AddTypeLoc(E->getTypeOperandSourceInfo());
2544}
2545
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002546void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002547 EnqueueChildren(S);
2548 AddDecl(S->getExceptionDecl());
2549}
2550
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002551void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002552 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002553 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002554 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002555}
2556
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002557void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002558 if (DR->hasExplicitTemplateArgs())
2559 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002560 WL.push_back(DeclRefExprParts(DR, Parent));
2561}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002562void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2563 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002564 if (E->hasExplicitTemplateArgs())
2565 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002566 AddDeclarationNameInfo(E);
2567 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2568}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002569void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002570 unsigned size = WL.size();
2571 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002572 for (const auto *D : S->decls()) {
2573 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 isFirst = false;
2575 }
2576 if (size == WL.size())
2577 return;
2578 // Now reverse the entries we just added. This will match the DFS
2579 // ordering performed by the worklist.
2580 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2581 std::reverse(I, E);
2582}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002583void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002584 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002585 for (const DesignatedInitExpr::Designator &D :
2586 llvm::reverse(E->designators())) {
2587 if (D.isFieldDesignator()) {
2588 if (FieldDecl *Field = D.getField())
2589 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002590 continue;
2591 }
David Majnemerf7e36092016-06-23 00:15:04 +00002592 if (D.isArrayDesignator()) {
2593 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 continue;
2595 }
David Majnemerf7e36092016-06-23 00:15:04 +00002596 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2597 AddStmt(E->getArrayRangeEnd(D));
2598 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002599 }
2600}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002601void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 EnqueueChildren(E);
2603 AddTypeLoc(E->getTypeInfoAsWritten());
2604}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002605void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002606 AddStmt(FS->getBody());
2607 AddStmt(FS->getInc());
2608 AddStmt(FS->getCond());
2609 AddDecl(FS->getConditionVariable());
2610 AddStmt(FS->getInit());
2611}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002612void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002613 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2614}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002615void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002616 AddStmt(If->getElse());
2617 AddStmt(If->getThen());
2618 AddStmt(If->getCond());
2619 AddDecl(If->getConditionVariable());
2620}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002621void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002622 // We care about the syntactic form of the initializer list, only.
2623 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2624 IE = Syntactic;
2625 EnqueueChildren(IE);
2626}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002627void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002628 WL.push_back(MemberExprParts(M, Parent));
2629
2630 // If the base of the member access expression is an implicit 'this', don't
2631 // visit it.
2632 // FIXME: If we ever want to show these implicit accesses, this will be
2633 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002634 if (M->isImplicitAccess())
2635 return;
2636
2637 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002638 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002639 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2640 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2641 if (FD->isAnonymousStructOrUnion()) {
2642 AddStmt(SubME->getBase());
2643 return;
2644 }
2645 }
2646 }
2647
2648 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002649}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002650void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002651 AddTypeLoc(E->getEncodedTypeSourceInfo());
2652}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002653void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002654 EnqueueChildren(M);
2655 AddTypeLoc(M->getClassReceiverTypeInfo());
2656}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002657void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002658 // Visit the components of the offsetof expression.
2659 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002660 const OffsetOfNode &Node = E->getComponent(I-1);
2661 switch (Node.getKind()) {
2662 case OffsetOfNode::Array:
2663 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2664 break;
2665 case OffsetOfNode::Field:
2666 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2667 break;
2668 case OffsetOfNode::Identifier:
2669 case OffsetOfNode::Base:
2670 continue;
2671 }
2672 }
2673 // Visit the type into which we're computing the offset.
2674 AddTypeLoc(E->getTypeSourceInfo());
2675}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002676void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002677 if (E->hasExplicitTemplateArgs())
2678 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002679 WL.push_back(OverloadExprParts(E, Parent));
2680}
2681void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002682 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002683 EnqueueChildren(E);
2684 if (E->isArgumentType())
2685 AddTypeLoc(E->getArgumentTypeInfo());
2686}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002687void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002688 EnqueueChildren(S);
2689}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002690void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 AddStmt(S->getBody());
2692 AddStmt(S->getCond());
2693 AddDecl(S->getConditionVariable());
2694}
2695
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002696void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002697 AddStmt(W->getBody());
2698 AddStmt(W->getCond());
2699 AddDecl(W->getConditionVariable());
2700}
2701
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002702void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002703 for (unsigned I = E->getNumArgs(); I > 0; --I)
2704 AddTypeLoc(E->getArg(I-1));
2705}
2706
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002707void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002708 AddTypeLoc(E->getQueriedTypeSourceInfo());
2709}
2710
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002711void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002712 EnqueueChildren(E);
2713}
2714
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002715void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002716 VisitOverloadExpr(U);
2717 if (!U->isImplicitAccess())
2718 AddStmt(U->getBase());
2719}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002720void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002721 AddStmt(E->getSubExpr());
2722 AddTypeLoc(E->getWrittenTypeInfo());
2723}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002724void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002725 WL.push_back(SizeOfPackExprParts(E, Parent));
2726}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002727void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002728 // If the opaque value has a source expression, just transparently
2729 // visit that. This is useful for (e.g.) pseudo-object expressions.
2730 if (Expr *SourceExpr = E->getSourceExpr())
2731 return Visit(SourceExpr);
2732}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002733void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002734 AddStmt(E->getBody());
2735 WL.push_back(LambdaExprParts(E, Parent));
2736}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002737void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002738 // Treat the expression like its syntactic form.
2739 Visit(E->getSyntacticForm());
2740}
2741
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002742void EnqueueVisitor::VisitOMPExecutableDirective(
2743 const OMPExecutableDirective *D) {
2744 EnqueueChildren(D);
2745 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2746 E = D->clauses().end();
2747 I != E; ++I)
2748 EnqueueChildren(*I);
2749}
2750
Alexander Musman3aaab662014-08-19 11:27:13 +00002751void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2752 VisitOMPExecutableDirective(D);
2753}
2754
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002755void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2756 VisitOMPExecutableDirective(D);
2757}
2758
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002759void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002760 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002761}
2762
Alexey Bataevf29276e2014-06-18 04:14:57 +00002763void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002764 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002765}
2766
Alexander Musmanf82886e2014-09-18 05:12:34 +00002767void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2768 VisitOMPLoopDirective(D);
2769}
2770
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002771void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2772 VisitOMPExecutableDirective(D);
2773}
2774
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002775void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2776 VisitOMPExecutableDirective(D);
2777}
2778
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002779void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2780 VisitOMPExecutableDirective(D);
2781}
2782
Alexander Musman80c22892014-07-17 08:54:58 +00002783void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2784 VisitOMPExecutableDirective(D);
2785}
2786
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002787void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2788 VisitOMPExecutableDirective(D);
2789 AddDeclarationNameInfo(D);
2790}
2791
Alexey Bataev4acb8592014-07-07 13:01:15 +00002792void
2793EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002794 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002795}
2796
Alexander Musmane4e893b2014-09-23 09:33:00 +00002797void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2798 const OMPParallelForSimdDirective *D) {
2799 VisitOMPLoopDirective(D);
2800}
2801
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002802void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2803 const OMPParallelSectionsDirective *D) {
2804 VisitOMPExecutableDirective(D);
2805}
2806
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002807void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2808 VisitOMPExecutableDirective(D);
2809}
2810
Alexey Bataev68446b72014-07-18 07:47:19 +00002811void
2812EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2813 VisitOMPExecutableDirective(D);
2814}
2815
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002816void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2817 VisitOMPExecutableDirective(D);
2818}
2819
Alexey Bataev2df347a2014-07-18 10:17:07 +00002820void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2821 VisitOMPExecutableDirective(D);
2822}
2823
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002824void EnqueueVisitor::VisitOMPTaskgroupDirective(
2825 const OMPTaskgroupDirective *D) {
2826 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002827 if (const Expr *E = D->getReductionRef())
2828 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002829}
2830
Alexey Bataev6125da92014-07-21 11:26:11 +00002831void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2832 VisitOMPExecutableDirective(D);
2833}
2834
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002835void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2836 VisitOMPExecutableDirective(D);
2837}
2838
Alexey Bataev0162e452014-07-22 10:10:35 +00002839void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2840 VisitOMPExecutableDirective(D);
2841}
2842
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002843void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2844 VisitOMPExecutableDirective(D);
2845}
2846
Michael Wong65f367f2015-07-21 13:44:28 +00002847void EnqueueVisitor::VisitOMPTargetDataDirective(const
2848 OMPTargetDataDirective *D) {
2849 VisitOMPExecutableDirective(D);
2850}
2851
Samuel Antaodf67fc42016-01-19 19:15:56 +00002852void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2853 const OMPTargetEnterDataDirective *D) {
2854 VisitOMPExecutableDirective(D);
2855}
2856
Samuel Antao72590762016-01-19 20:04:50 +00002857void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2858 const OMPTargetExitDataDirective *D) {
2859 VisitOMPExecutableDirective(D);
2860}
2861
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002862void EnqueueVisitor::VisitOMPTargetParallelDirective(
2863 const OMPTargetParallelDirective *D) {
2864 VisitOMPExecutableDirective(D);
2865}
2866
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002867void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2868 const OMPTargetParallelForDirective *D) {
2869 VisitOMPLoopDirective(D);
2870}
2871
Alexey Bataev13314bf2014-10-09 04:18:56 +00002872void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2873 VisitOMPExecutableDirective(D);
2874}
2875
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002876void EnqueueVisitor::VisitOMPCancellationPointDirective(
2877 const OMPCancellationPointDirective *D) {
2878 VisitOMPExecutableDirective(D);
2879}
2880
Alexey Bataev80909872015-07-02 11:25:17 +00002881void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2882 VisitOMPExecutableDirective(D);
2883}
2884
Alexey Bataev49f6e782015-12-01 04:18:41 +00002885void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2886 VisitOMPLoopDirective(D);
2887}
2888
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002889void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2890 const OMPTaskLoopSimdDirective *D) {
2891 VisitOMPLoopDirective(D);
2892}
2893
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002894void EnqueueVisitor::VisitOMPDistributeDirective(
2895 const OMPDistributeDirective *D) {
2896 VisitOMPLoopDirective(D);
2897}
2898
Carlo Bertolli9925f152016-06-27 14:55:37 +00002899void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2900 const OMPDistributeParallelForDirective *D) {
2901 VisitOMPLoopDirective(D);
2902}
2903
Kelvin Li4a39add2016-07-05 05:00:15 +00002904void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2905 const OMPDistributeParallelForSimdDirective *D) {
2906 VisitOMPLoopDirective(D);
2907}
2908
Kelvin Li787f3fc2016-07-06 04:45:38 +00002909void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2910 const OMPDistributeSimdDirective *D) {
2911 VisitOMPLoopDirective(D);
2912}
2913
Kelvin Lia579b912016-07-14 02:54:56 +00002914void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2915 const OMPTargetParallelForSimdDirective *D) {
2916 VisitOMPLoopDirective(D);
2917}
2918
Kelvin Li986330c2016-07-20 22:57:10 +00002919void EnqueueVisitor::VisitOMPTargetSimdDirective(
2920 const OMPTargetSimdDirective *D) {
2921 VisitOMPLoopDirective(D);
2922}
2923
Kelvin Li02532872016-08-05 14:37:37 +00002924void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2925 const OMPTeamsDistributeDirective *D) {
2926 VisitOMPLoopDirective(D);
2927}
2928
Kelvin Li4e325f72016-10-25 12:50:55 +00002929void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2930 const OMPTeamsDistributeSimdDirective *D) {
2931 VisitOMPLoopDirective(D);
2932}
2933
Kelvin Li579e41c2016-11-30 23:51:03 +00002934void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2935 const OMPTeamsDistributeParallelForSimdDirective *D) {
2936 VisitOMPLoopDirective(D);
2937}
2938
Kelvin Li7ade93f2016-12-09 03:24:30 +00002939void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2940 const OMPTeamsDistributeParallelForDirective *D) {
2941 VisitOMPLoopDirective(D);
2942}
2943
Kelvin Libf594a52016-12-17 05:48:59 +00002944void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2945 const OMPTargetTeamsDirective *D) {
2946 VisitOMPExecutableDirective(D);
2947}
2948
Kelvin Li83c451e2016-12-25 04:52:54 +00002949void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2950 const OMPTargetTeamsDistributeDirective *D) {
2951 VisitOMPLoopDirective(D);
2952}
2953
Kelvin Li80e8f562016-12-29 22:16:30 +00002954void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2955 const OMPTargetTeamsDistributeParallelForDirective *D) {
2956 VisitOMPLoopDirective(D);
2957}
2958
Kelvin Li1851df52017-01-03 05:23:48 +00002959void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2960 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2961 VisitOMPLoopDirective(D);
2962}
2963
Kelvin Lida681182017-01-10 18:08:18 +00002964void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2965 const OMPTargetTeamsDistributeSimdDirective *D) {
2966 VisitOMPLoopDirective(D);
2967}
2968
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002969void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002970 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2971}
2972
2973bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2974 if (RegionOfInterest.isValid()) {
2975 SourceRange Range = getRawCursorExtent(C);
2976 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2977 return false;
2978 }
2979 return true;
2980}
2981
2982bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2983 while (!WL.empty()) {
2984 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002985 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002986
2987 // Set the Parent field, then back to its old value once we're done.
2988 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2989
2990 switch (LI.getKind()) {
2991 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002992 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002993 if (!D)
2994 continue;
2995
2996 // For now, perform default visitation for Decls.
2997 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2998 cast<DeclVisit>(&LI)->isFirst())))
2999 return true;
3000
3001 continue;
3002 }
3003 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00003004 for (const TemplateArgumentLoc &Arg :
3005 *cast<ExplicitTemplateArgsVisit>(&LI)) {
3006 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00003007 return true;
3008 }
3009 continue;
3010 }
3011 case VisitorJob::TypeLocVisitKind: {
3012 // Perform default visitation for TypeLocs.
3013 if (Visit(cast<TypeLocVisit>(&LI)->get()))
3014 return true;
3015 continue;
3016 }
3017 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003018 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003019 if (LabelStmt *stmt = LS->getStmt()) {
3020 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3021 TU))) {
3022 return true;
3023 }
3024 }
3025 continue;
3026 }
3027
3028 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3029 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3030 if (VisitNestedNameSpecifierLoc(V->get()))
3031 return true;
3032 continue;
3033 }
3034
3035 case VisitorJob::DeclarationNameInfoVisitKind: {
3036 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3037 ->get()))
3038 return true;
3039 continue;
3040 }
3041 case VisitorJob::MemberRefVisitKind: {
3042 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3043 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3044 return true;
3045 continue;
3046 }
3047 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003048 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003049 if (!S)
3050 continue;
3051
3052 // Update the current cursor.
3053 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3054 if (!IsInRegionOfInterest(Cursor))
3055 continue;
3056 switch (Visitor(Cursor, Parent, ClientData)) {
3057 case CXChildVisit_Break: return true;
3058 case CXChildVisit_Continue: break;
3059 case CXChildVisit_Recurse:
3060 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003061 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003062 EnqueueWorkList(WL, S);
3063 break;
3064 }
3065 continue;
3066 }
3067 case VisitorJob::MemberExprPartsKind: {
3068 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003069 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003070
3071 // Visit the nested-name-specifier
3072 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3073 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3074 return true;
3075
3076 // Visit the declaration name.
3077 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3078 return true;
3079
3080 // Visit the explicitly-specified template arguments, if any.
3081 if (M->hasExplicitTemplateArgs()) {
3082 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3083 *ArgEnd = Arg + M->getNumTemplateArgs();
3084 Arg != ArgEnd; ++Arg) {
3085 if (VisitTemplateArgumentLoc(*Arg))
3086 return true;
3087 }
3088 }
3089 continue;
3090 }
3091 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003092 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003093 // Visit nested-name-specifier, if present.
3094 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3095 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3096 return true;
3097 // Visit declaration name.
3098 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3099 return true;
3100 continue;
3101 }
3102 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003103 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003104 // Visit the nested-name-specifier.
3105 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3106 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3107 return true;
3108 // Visit the declaration name.
3109 if (VisitDeclarationNameInfo(O->getNameInfo()))
3110 return true;
3111 // Visit the overloaded declaration reference.
3112 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3113 return true;
3114 continue;
3115 }
3116 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003117 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003118 NamedDecl *Pack = E->getPack();
3119 if (isa<TemplateTypeParmDecl>(Pack)) {
3120 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3121 E->getPackLoc(), TU)))
3122 return true;
3123
3124 continue;
3125 }
3126
3127 if (isa<TemplateTemplateParmDecl>(Pack)) {
3128 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3129 E->getPackLoc(), TU)))
3130 return true;
3131
3132 continue;
3133 }
3134
3135 // Non-type template parameter packs and function parameter packs are
3136 // treated like DeclRefExpr cursors.
3137 continue;
3138 }
3139
3140 case VisitorJob::LambdaExprPartsKind: {
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003141 // Visit non-init captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003142 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003143 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3144 CEnd = E->explicit_capture_end();
3145 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003146 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003147 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003148
Guy Benyei11169dd2012-12-18 14:30:41 +00003149 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3150 C->getLocation(),
3151 TU)))
3152 return true;
3153 }
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003154 // Visit init captures
3155 for (auto InitExpr : E->capture_inits()) {
3156 if (Visit(InitExpr))
3157 return true;
3158 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003159
Haojian Wuef87c262018-12-18 15:29:12 +00003160 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00003161 // Visit parameters and return type, if present.
Haojian Wuef87c262018-12-18 15:29:12 +00003162 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3163 if (E->hasExplicitParameters()) {
3164 // Visit parameters.
3165 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3166 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003167 return true;
Haojian Wuef87c262018-12-18 15:29:12 +00003168 }
3169 if (E->hasExplicitResultType()) {
3170 // Visit result type.
3171 if (Visit(Proto.getReturnLoc()))
3172 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003173 }
3174 }
3175 break;
3176 }
3177
3178 case VisitorJob::PostChildrenVisitKind:
3179 if (PostChildrenVisitor(Parent, ClientData))
3180 return true;
3181 break;
3182 }
3183 }
3184 return false;
3185}
3186
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003187bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003188 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003189 if (!WorkListFreeList.empty()) {
3190 WL = WorkListFreeList.back();
3191 WL->clear();
3192 WorkListFreeList.pop_back();
3193 }
3194 else {
3195 WL = new VisitorWorkList();
3196 WorkListCache.push_back(WL);
3197 }
3198 EnqueueWorkList(*WL, S);
3199 bool result = RunVisitorWorkList(*WL);
3200 WorkListFreeList.push_back(WL);
3201 return result;
3202}
3203
3204namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003205typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003206RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3207 const DeclarationNameInfo &NI, SourceRange QLoc,
3208 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003209 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3210 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3211 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3212
3213 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3214
3215 RefNamePieces Pieces;
3216
3217 if (WantQualifier && QLoc.isValid())
3218 Pieces.push_back(QLoc);
3219
3220 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3221 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003222
3223 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3224 Pieces.push_back(*TemplateArgsLoc);
3225
Guy Benyei11169dd2012-12-18 14:30:41 +00003226 if (Kind == DeclarationName::CXXOperatorName) {
3227 Pieces.push_back(SourceLocation::getFromRawEncoding(
3228 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3229 Pieces.push_back(SourceLocation::getFromRawEncoding(
3230 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3231 }
3232
3233 if (WantSinglePiece) {
3234 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3235 Pieces.clear();
3236 Pieces.push_back(R);
3237 }
3238
3239 return Pieces;
3240}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003241}
Guy Benyei11169dd2012-12-18 14:30:41 +00003242
3243//===----------------------------------------------------------------------===//
3244// Misc. API hooks.
3245//===----------------------------------------------------------------------===//
3246
Chandler Carruth66660742014-06-27 16:37:27 +00003247namespace {
3248struct RegisterFatalErrorHandler {
3249 RegisterFatalErrorHandler() {
Jan Korousf7d23762019-09-12 22:55:55 +00003250 clang_install_aborting_llvm_fatal_error_handler();
Chandler Carruth66660742014-06-27 16:37:27 +00003251 }
3252};
3253}
3254
3255static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3256
Guy Benyei11169dd2012-12-18 14:30:41 +00003257CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3258 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003259 // We use crash recovery to make some of our APIs more reliable, implicitly
3260 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003261 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3262 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003263
Chandler Carruth66660742014-06-27 16:37:27 +00003264 // Look through the managed static to trigger construction of the managed
3265 // static which registers our fatal error handler. This ensures it is only
3266 // registered once.
3267 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003268
Adrian Prantlbc068582015-07-08 01:00:30 +00003269 // Initialize targets for clang module support.
3270 llvm::InitializeAllTargets();
3271 llvm::InitializeAllTargetMCs();
3272 llvm::InitializeAllAsmPrinters();
3273 llvm::InitializeAllAsmParsers();
3274
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003275 CIndexer *CIdxr = new CIndexer();
3276
Guy Benyei11169dd2012-12-18 14:30:41 +00003277 if (excludeDeclarationsFromPCH)
3278 CIdxr->setOnlyLocalDecls();
3279 if (displayDiagnostics)
3280 CIdxr->setDisplayDiagnostics();
3281
3282 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3283 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3284 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3285 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3286 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3287 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3288
3289 return CIdxr;
3290}
3291
3292void clang_disposeIndex(CXIndex CIdx) {
3293 if (CIdx)
3294 delete static_cast<CIndexer *>(CIdx);
3295}
3296
3297void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3298 if (CIdx)
3299 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3300}
3301
3302unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3303 if (CIdx)
3304 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3305 return 0;
3306}
3307
Alex Lorenz08615792017-12-04 21:56:36 +00003308void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3309 const char *Path) {
3310 if (CIdx)
3311 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3312}
3313
Guy Benyei11169dd2012-12-18 14:30:41 +00003314void clang_toggleCrashRecovery(unsigned isEnabled) {
3315 if (isEnabled)
3316 llvm::CrashRecoveryContext::Enable();
3317 else
3318 llvm::CrashRecoveryContext::Disable();
3319}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003320
Guy Benyei11169dd2012-12-18 14:30:41 +00003321CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3322 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003323 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003324 enum CXErrorCode Result =
3325 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003326 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003327 assert((TU && Result == CXError_Success) ||
3328 (!TU && Result != CXError_Success));
3329 return TU;
3330}
3331
3332enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3333 const char *ast_filename,
3334 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003335 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003336 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003337
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003338 if (!CIdx || !ast_filename || !out_TU)
3339 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003340
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003341 LOG_FUNC_SECTION {
3342 *Log << ast_filename;
3343 }
3344
Guy Benyei11169dd2012-12-18 14:30:41 +00003345 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3346 FileSystemOptions FileSystemOpts;
3347
Justin Bognerd512c1e2014-10-15 00:33:06 +00003348 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3349 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003350 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003351 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3352 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003353 FileSystemOpts, /*UseDebugInfo=*/false,
3354 CXXIdx->getOnlyLocalDecls(), None,
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003355 CaptureDiagsKind::All,
David Blaikie6f7382d2014-08-10 19:08:04 +00003356 /*AllowPCHWithCompilerErrors=*/true,
3357 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003358 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003359 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003360}
3361
3362unsigned clang_defaultEditingTranslationUnitOptions() {
3363 return CXTranslationUnit_PrecompiledPreamble |
3364 CXTranslationUnit_CacheCompletionResults;
3365}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003366
Guy Benyei11169dd2012-12-18 14:30:41 +00003367CXTranslationUnit
3368clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3369 const char *source_filename,
3370 int num_command_line_args,
3371 const char * const *command_line_args,
3372 unsigned num_unsaved_files,
3373 struct CXUnsavedFile *unsaved_files) {
3374 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3375 return clang_parseTranslationUnit(CIdx, source_filename,
3376 command_line_args, num_command_line_args,
3377 unsaved_files, num_unsaved_files,
3378 Options);
3379}
3380
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003381static CXErrorCode
3382clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3383 const char *const *command_line_args,
3384 int num_command_line_args,
3385 ArrayRef<CXUnsavedFile> unsaved_files,
3386 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003387 // Set up the initial return values.
3388 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003389 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003390
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003391 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003392 if (!CIdx || !out_TU)
3393 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003394
Guy Benyei11169dd2012-12-18 14:30:41 +00003395 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3396
3397 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3398 setThreadBackgroundPriority();
3399
3400 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003401 bool CreatePreambleOnFirstParse =
3402 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003403 // FIXME: Add a flag for modules.
3404 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003405 = (options & (CXTranslationUnit_Incomplete |
3406 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003407 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003408 = options & CXTranslationUnit_CacheCompletionResults;
3409 bool IncludeBriefCommentsInCodeCompletion
3410 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003411 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3412 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003413 bool RetainExcludedCB = options &
3414 CXTranslationUnit_RetainExcludedConditionalBlocks;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003415 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3416 if (options & CXTranslationUnit_SkipFunctionBodies) {
3417 SkipFunctionBodies =
3418 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3419 ? SkipFunctionBodiesScope::Preamble
3420 : SkipFunctionBodiesScope::PreambleAndMainFile;
3421 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003422
3423 // Configure the diagnostics.
3424 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003425 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003426
Manuel Klimek016c0242016-03-01 10:56:19 +00003427 if (options & CXTranslationUnit_KeepGoing)
Ivan Donchevskii878271b2019-03-07 10:13:50 +00003428 Diags->setFatalsAsError(true);
Manuel Klimek016c0242016-03-01 10:56:19 +00003429
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003430 CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::All;
3431 if (options & CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles)
3432 CaptureDiagnostics = CaptureDiagsKind::AllWithoutNonErrorsFromIncludes;
3433
Guy Benyei11169dd2012-12-18 14:30:41 +00003434 // Recover resources if we crash before exiting this function.
3435 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3436 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003437 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003438
Ahmed Charlesb8984322014-03-07 20:03:18 +00003439 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3440 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003441
3442 // Recover resources if we crash before exiting this function.
3443 llvm::CrashRecoveryContextCleanupRegistrar<
3444 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3445
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003446 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003447 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003448 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003449 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003450 }
3451
Ahmed Charlesb8984322014-03-07 20:03:18 +00003452 std::unique_ptr<std::vector<const char *>> Args(
3453 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003454
3455 // Recover resources if we crash before exiting this method.
3456 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3457 ArgsCleanup(Args.get());
3458
3459 // Since the Clang C library is primarily used by batch tools dealing with
3460 // (often very broken) source code, where spell-checking can have a
3461 // significant negative impact on performance (particularly when
3462 // precompiled headers are involved), we disable it by default.
3463 // Only do this if we haven't found a spell-checking-related argument.
3464 bool FoundSpellCheckingArgument = false;
3465 for (int I = 0; I != num_command_line_args; ++I) {
3466 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3467 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3468 FoundSpellCheckingArgument = true;
3469 break;
3470 }
3471 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003472 Args->insert(Args->end(), command_line_args,
3473 command_line_args + num_command_line_args);
3474
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003475 if (!FoundSpellCheckingArgument)
3476 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3477
Guy Benyei11169dd2012-12-18 14:30:41 +00003478 // The 'source_filename' argument is optional. If the caller does not
3479 // specify it then it is assumed that the source file is specified
3480 // in the actual argument list.
3481 // Put the source file after command_line_args otherwise if '-x' flag is
3482 // present it will be unused.
3483 if (source_filename)
3484 Args->push_back(source_filename);
3485
3486 // Do we need the detailed preprocessing record?
3487 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3488 Args->push_back("-Xclang");
3489 Args->push_back("-detailed-preprocessing-record");
3490 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003491
3492 // Suppress any editor placeholder diagnostics.
3493 Args->push_back("-fallow-editor-placeholders");
3494
Guy Benyei11169dd2012-12-18 14:30:41 +00003495 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003496 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003497 // Unless the user specified that they want the preamble on the first parse
3498 // set it up to be created on the first reparse. This makes the first parse
3499 // faster, trading for a slower (first) reparse.
3500 unsigned PrecompilePreambleAfterNParses =
3501 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003502
Alex Lorenz08615792017-12-04 21:56:36 +00003503 LibclangInvocationReporter InvocationReporter(
3504 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003505 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3506 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003507 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003508 Args->data(), Args->data() + Args->size(),
3509 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003510 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003511 CaptureDiagnostics, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003512 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3513 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003514 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Evgeny Mankov2ed2e622019-08-27 22:15:32 +00003515 /*UserFilesAreVolatile=*/true, ForSerialization, RetainExcludedCB,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003516 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3517 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003518
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003519 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003520 if (!Unit && !ErrUnit)
3521 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003522
Guy Benyei11169dd2012-12-18 14:30:41 +00003523 if (NumErrors != Diags->getClient()->getNumErrors()) {
3524 // Make sure to check that 'Unit' is non-NULL.
3525 if (CXXIdx->getDisplayDiagnostics())
3526 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3527 }
3528
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003529 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3530 return CXError_ASTReadError;
3531
David Blaikieea4395e2017-01-06 19:49:01 +00003532 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003533 if (CXTranslationUnitImpl *TU = *out_TU) {
3534 TU->ParsingOptions = options;
3535 TU->Arguments.reserve(Args->size());
3536 for (const char *Arg : *Args)
3537 TU->Arguments.push_back(Arg);
3538 return CXError_Success;
3539 }
3540 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003541}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003542
3543CXTranslationUnit
3544clang_parseTranslationUnit(CXIndex CIdx,
3545 const char *source_filename,
3546 const char *const *command_line_args,
3547 int num_command_line_args,
3548 struct CXUnsavedFile *unsaved_files,
3549 unsigned num_unsaved_files,
3550 unsigned options) {
3551 CXTranslationUnit TU;
3552 enum CXErrorCode Result = clang_parseTranslationUnit2(
3553 CIdx, source_filename, command_line_args, num_command_line_args,
3554 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003555 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003556 assert((TU && Result == CXError_Success) ||
3557 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003558 return TU;
3559}
3560
3561enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003562 CXIndex CIdx, const char *source_filename,
3563 const char *const *command_line_args, int num_command_line_args,
3564 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3565 unsigned options, CXTranslationUnit *out_TU) {
3566 SmallVector<const char *, 4> Args;
3567 Args.push_back("clang");
3568 Args.append(command_line_args, command_line_args + num_command_line_args);
3569 return clang_parseTranslationUnit2FullArgv(
3570 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3571 num_unsaved_files, options, out_TU);
3572}
3573
3574enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3575 CXIndex CIdx, const char *source_filename,
3576 const char *const *command_line_args, int num_command_line_args,
3577 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3578 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003579 LOG_FUNC_SECTION {
3580 *Log << source_filename << ": ";
3581 for (int i = 0; i != num_command_line_args; ++i)
3582 *Log << command_line_args[i] << " ";
3583 }
3584
Alp Toker9d85b182014-07-07 01:23:14 +00003585 if (num_unsaved_files && !unsaved_files)
3586 return CXError_InvalidArguments;
3587
Alp Toker5c532982014-07-07 22:42:03 +00003588 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003589 auto ParseTranslationUnitImpl = [=, &result] {
3590 result = clang_parseTranslationUnit_Impl(
3591 CIdx, source_filename, command_line_args, num_command_line_args,
3592 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3593 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003594
Guy Benyei11169dd2012-12-18 14:30:41 +00003595 llvm::CrashRecoveryContext CRC;
3596
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003597 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003598 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3599 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3600 fprintf(stderr, " 'command_line_args' : [");
3601 for (int i = 0; i != num_command_line_args; ++i) {
3602 if (i)
3603 fprintf(stderr, ", ");
3604 fprintf(stderr, "'%s'", command_line_args[i]);
3605 }
3606 fprintf(stderr, "],\n");
3607 fprintf(stderr, " 'unsaved_files' : [");
3608 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3609 if (i)
3610 fprintf(stderr, ", ");
3611 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3612 unsaved_files[i].Length);
3613 }
3614 fprintf(stderr, "],\n");
3615 fprintf(stderr, " 'options' : %d,\n", options);
3616 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003617
3618 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003619 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003620 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003621 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003622 }
Alp Toker5c532982014-07-07 22:42:03 +00003623
3624 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003625}
3626
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003627CXString clang_Type_getObjCEncoding(CXType CT) {
3628 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3629 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3630 std::string encoding;
3631 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3632 encoding);
3633
3634 return cxstring::createDup(encoding);
3635}
3636
3637static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3638 if (C.kind == CXCursor_MacroDefinition) {
3639 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3640 return MDR->getName();
3641 } else if (C.kind == CXCursor_MacroExpansion) {
3642 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3643 return ME.getName();
3644 }
3645 return nullptr;
3646}
3647
3648unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3649 const IdentifierInfo *II = getMacroIdentifier(C);
3650 if (!II) {
3651 return false;
3652 }
3653 ASTUnit *ASTU = getCursorASTUnit(C);
3654 Preprocessor &PP = ASTU->getPreprocessor();
3655 if (const MacroInfo *MI = PP.getMacroInfo(II))
3656 return MI->isFunctionLike();
3657 return false;
3658}
3659
3660unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3661 const IdentifierInfo *II = getMacroIdentifier(C);
3662 if (!II) {
3663 return false;
3664 }
3665 ASTUnit *ASTU = getCursorASTUnit(C);
3666 Preprocessor &PP = ASTU->getPreprocessor();
3667 if (const MacroInfo *MI = PP.getMacroInfo(II))
3668 return MI->isBuiltinMacro();
3669 return false;
3670}
3671
3672unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3673 const Decl *D = getCursorDecl(C);
3674 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3675 if (!FD) {
3676 return false;
3677 }
3678 return FD->isInlined();
3679}
3680
3681static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3682 if (callExpr->getNumArgs() != 1) {
3683 return nullptr;
3684 }
3685
3686 StringLiteral *S = nullptr;
3687 auto *arg = callExpr->getArg(0);
3688 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3689 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3690 auto *subExpr = I->getSubExprAsWritten();
3691
3692 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3693 return nullptr;
3694 }
3695
3696 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3697 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3698 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3699 } else {
3700 return nullptr;
3701 }
3702 return S;
3703}
3704
David Blaikie59272572016-04-13 18:23:33 +00003705struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003706 CXEvalResultKind EvalType;
3707 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003708 unsigned long long unsignedVal;
3709 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003710 double floatVal;
3711 char *stringVal;
3712 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003713 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003714 ~ExprEvalResult() {
3715 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3716 EvalType != CXEval_Int) {
Alex Lorenza19cb2e2019-01-08 23:28:37 +00003717 delete[] EvalData.stringVal;
David Blaikie59272572016-04-13 18:23:33 +00003718 }
3719 }
3720};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003721
3722void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003723 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003724}
3725
3726CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3727 if (!E) {
3728 return CXEval_UnExposed;
3729 }
3730 return ((ExprEvalResult *)E)->EvalType;
3731}
3732
3733int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003734 return clang_EvalResult_getAsLongLong(E);
3735}
3736
3737long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003738 if (!E) {
3739 return 0;
3740 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003741 ExprEvalResult *Result = (ExprEvalResult*)E;
3742 if (Result->IsUnsignedInt)
3743 return Result->EvalData.unsignedVal;
3744 return Result->EvalData.intVal;
3745}
3746
3747unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3748 return ((ExprEvalResult *)E)->IsUnsignedInt;
3749}
3750
3751unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3752 if (!E) {
3753 return 0;
3754 }
3755
3756 ExprEvalResult *Result = (ExprEvalResult*)E;
3757 if (Result->IsUnsignedInt)
3758 return Result->EvalData.unsignedVal;
3759 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003760}
3761
3762double clang_EvalResult_getAsDouble(CXEvalResult E) {
3763 if (!E) {
3764 return 0;
3765 }
3766 return ((ExprEvalResult *)E)->EvalData.floatVal;
3767}
3768
3769const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3770 if (!E) {
3771 return nullptr;
3772 }
3773 return ((ExprEvalResult *)E)->EvalData.stringVal;
3774}
3775
3776static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3777 Expr::EvalResult ER;
3778 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003779 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003780 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003781
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003782 expr = expr->IgnoreParens();
Emilio Cobos Alvarez74375452019-07-09 14:27:01 +00003783 if (expr->isValueDependent())
3784 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003785 if (!expr->EvaluateAsRValue(ER, ctx))
3786 return nullptr;
3787
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003788 QualType rettype;
3789 CallExpr *callExpr;
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00003790 auto result = std::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003791 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003792 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003793
David Blaikiebbc00882016-04-13 18:36:19 +00003794 if (ER.Val.isInt()) {
3795 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003796
3797 auto& val = ER.Val.getInt();
3798 if (val.isUnsigned()) {
3799 result->IsUnsignedInt = true;
3800 result->EvalData.unsignedVal = val.getZExtValue();
3801 } else {
3802 result->EvalData.intVal = val.getExtValue();
3803 }
3804
David Blaikiebbc00882016-04-13 18:36:19 +00003805 return result.release();
3806 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003807
David Blaikiebbc00882016-04-13 18:36:19 +00003808 if (ER.Val.isFloat()) {
3809 llvm::SmallVector<char, 100> Buffer;
3810 ER.Val.getFloat().toString(Buffer);
3811 std::string floatStr(Buffer.data(), Buffer.size());
3812 result->EvalType = CXEval_Float;
3813 bool ignored;
3814 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003815 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003816 llvm::APFloat::rmNearestTiesToEven, &ignored);
3817 result->EvalData.floatVal = apFloat.convertToDouble();
3818 return result.release();
3819 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003820
David Blaikiebbc00882016-04-13 18:36:19 +00003821 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3822 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3823 auto *subExpr = I->getSubExprAsWritten();
3824 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3825 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003826 const StringLiteral *StrE = nullptr;
3827 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003828 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003829
3830 if (ObjCExpr) {
3831 StrE = ObjCExpr->getString();
3832 result->EvalType = CXEval_ObjCStrLiteral;
3833 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003834 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003835 result->EvalType = CXEval_StrLiteral;
3836 }
3837
3838 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003839 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003840 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3841 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003842 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003843 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003844 }
3845 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3846 expr->getStmtClass() == Stmt::StringLiteralClass) {
3847 const StringLiteral *StrE = nullptr;
3848 const ObjCStringLiteral *ObjCExpr;
3849 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003850
David Blaikiebbc00882016-04-13 18:36:19 +00003851 if (ObjCExpr) {
3852 StrE = ObjCExpr->getString();
3853 result->EvalType = CXEval_ObjCStrLiteral;
3854 } else {
3855 StrE = cast<StringLiteral>(expr);
3856 result->EvalType = CXEval_StrLiteral;
3857 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003858
David Blaikiebbc00882016-04-13 18:36:19 +00003859 std::string strRef(StrE->getString().str());
3860 result->EvalData.stringVal = new char[strRef.size() + 1];
3861 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3862 result->EvalData.stringVal[strRef.size()] = '\0';
3863 return result.release();
3864 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003865
David Blaikiebbc00882016-04-13 18:36:19 +00003866 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3867 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003868
David Blaikiebbc00882016-04-13 18:36:19 +00003869 rettype = CC->getType();
3870 if (rettype.getAsString() == "CFStringRef" &&
3871 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003872
David Blaikiebbc00882016-04-13 18:36:19 +00003873 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3874 StringLiteral *S = getCFSTR_value(callExpr);
3875 if (S) {
3876 std::string strLiteral(S->getString().str());
3877 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003878
David Blaikiebbc00882016-04-13 18:36:19 +00003879 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3880 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3881 strLiteral.size());
3882 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003883 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003884 }
3885 }
3886
David Blaikiebbc00882016-04-13 18:36:19 +00003887 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3888 callExpr = static_cast<CallExpr *>(expr);
3889 rettype = callExpr->getCallReturnType(ctx);
3890
3891 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3892 return nullptr;
3893
3894 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3895 if (callExpr->getNumArgs() == 1 &&
3896 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3897 return nullptr;
3898 } else if (rettype.getAsString() == "CFStringRef") {
3899
3900 StringLiteral *S = getCFSTR_value(callExpr);
3901 if (S) {
3902 std::string strLiteral(S->getString().str());
3903 result->EvalType = CXEval_CFStr;
3904 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3905 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3906 strLiteral.size());
3907 result->EvalData.stringVal[strLiteral.size()] = '\0';
3908 return result.release();
3909 }
3910 }
3911 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3912 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3913 ValueDecl *V = D->getDecl();
3914 if (V->getKind() == Decl::Function) {
3915 std::string strName = V->getNameAsString();
3916 result->EvalType = CXEval_Other;
3917 result->EvalData.stringVal = new char[strName.size() + 1];
3918 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3919 result->EvalData.stringVal[strName.size()] = '\0';
3920 return result.release();
3921 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003922 }
3923
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003924 return nullptr;
3925}
3926
Alex Lorenz65317e12019-01-08 22:32:51 +00003927static const Expr *evaluateDeclExpr(const Decl *D) {
3928 if (!D)
Evgeniy Stepanov9b871492018-07-10 19:48:53 +00003929 return nullptr;
Alex Lorenz65317e12019-01-08 22:32:51 +00003930 if (auto *Var = dyn_cast<VarDecl>(D))
3931 return Var->getInit();
3932 else if (auto *Field = dyn_cast<FieldDecl>(D))
3933 return Field->getInClassInitializer();
3934 return nullptr;
3935}
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003936
Alex Lorenz65317e12019-01-08 22:32:51 +00003937static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
3938 assert(CS && "invalid compound statement");
3939 for (auto *bodyIterator : CS->body()) {
3940 if (const auto *E = dyn_cast<Expr>(bodyIterator))
3941 return E;
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003942 }
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00003943 return nullptr;
3944}
3945
Alex Lorenz65317e12019-01-08 22:32:51 +00003946CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3947 if (const Expr *E =
3948 clang_getCursorKind(C) == CXCursor_CompoundStmt
3949 ? evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)))
3950 : evaluateDeclExpr(getCursorDecl(C)))
3951 return const_cast<CXEvalResult>(
3952 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
3953 return nullptr;
3954}
3955
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003956unsigned clang_Cursor_hasAttrs(CXCursor C) {
3957 const Decl *D = getCursorDecl(C);
3958 if (!D) {
3959 return 0;
3960 }
3961
3962 if (D->hasAttrs()) {
3963 return 1;
3964 }
3965
3966 return 0;
3967}
Guy Benyei11169dd2012-12-18 14:30:41 +00003968unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3969 return CXSaveTranslationUnit_None;
3970}
3971
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003972static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3973 const char *FileName,
3974 unsigned options) {
3975 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003976 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3977 setThreadBackgroundPriority();
3978
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003979 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3980 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003981}
3982
3983int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3984 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003985 LOG_FUNC_SECTION {
3986 *Log << TU << ' ' << FileName;
3987 }
3988
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003989 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003990 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003991 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003992 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003993
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003994 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003995 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3996 if (!CXXUnit->hasSema())
3997 return CXSaveError_InvalidTU;
3998
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003999 CXSaveError result;
4000 auto SaveTranslationUnitImpl = [=, &result]() {
4001 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
4002 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004003
Erik Verbruggen3cc39112017-11-14 09:34:39 +00004004 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004005 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00004006
4007 if (getenv("LIBCLANG_RESOURCE_USAGE"))
4008 PrintLibclangResourceUsage(TU);
4009
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004010 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004011 }
4012
4013 // We have an AST that has invalid nodes due to compiler errors.
4014 // Use a crash recovery thread for protection.
4015
4016 llvm::CrashRecoveryContext CRC;
4017
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004018 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004019 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
4020 fprintf(stderr, " 'filename' : '%s'\n", FileName);
4021 fprintf(stderr, " 'options' : %d,\n", options);
4022 fprintf(stderr, "}\n");
4023
4024 return CXSaveError_Unknown;
4025
4026 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4027 PrintLibclangResourceUsage(TU);
4028 }
4029
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004030 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004031}
4032
4033void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4034 if (CTUnit) {
4035 // If the translation unit has been marked as unsafe to free, just discard
4036 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004037 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4038 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004039 return;
4040
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004041 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004042 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004043 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4044 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004045 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004046 delete CTUnit;
4047 }
4048}
4049
Erik Verbruggen346066b2017-05-30 14:25:54 +00004050unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4051 if (CTUnit) {
4052 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4053
4054 if (Unit && Unit->isUnsafeToFree())
4055 return false;
4056
4057 Unit->ResetForParse();
4058 return true;
4059 }
4060
4061 return false;
4062}
4063
Guy Benyei11169dd2012-12-18 14:30:41 +00004064unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4065 return CXReparse_None;
4066}
4067
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004068static CXErrorCode
4069clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4070 ArrayRef<CXUnsavedFile> unsaved_files,
4071 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004072 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004073 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004074 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004075 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004076 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004077
4078 // Reset the associated diagnostics.
4079 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004080 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004081
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004082 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004083 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4084 setThreadBackgroundPriority();
4085
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004086 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004087 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004088
4089 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4090 new std::vector<ASTUnit::RemappedFile>());
4091
Guy Benyei11169dd2012-12-18 14:30:41 +00004092 // Recover resources if we crash before exiting this function.
4093 llvm::CrashRecoveryContextCleanupRegistrar<
4094 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004095
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004096 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004097 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004098 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004099 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004100 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004101
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004102 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4103 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004104 return CXError_Success;
4105 if (isASTReadError(CXXUnit))
4106 return CXError_ASTReadError;
4107 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004108}
4109
4110int clang_reparseTranslationUnit(CXTranslationUnit TU,
4111 unsigned num_unsaved_files,
4112 struct CXUnsavedFile *unsaved_files,
4113 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004114 LOG_FUNC_SECTION {
4115 *Log << TU;
4116 }
4117
Alp Toker9d85b182014-07-07 01:23:14 +00004118 if (num_unsaved_files && !unsaved_files)
4119 return CXError_InvalidArguments;
4120
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004121 CXErrorCode result;
4122 auto ReparseTranslationUnitImpl = [=, &result]() {
4123 result = clang_reparseTranslationUnit_Impl(
4124 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4125 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004126
Guy Benyei11169dd2012-12-18 14:30:41 +00004127 llvm::CrashRecoveryContext CRC;
4128
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004129 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004130 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004131 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004132 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004133 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4134 PrintLibclangResourceUsage(TU);
4135
Alp Toker5c532982014-07-07 22:42:03 +00004136 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004137}
4138
4139
4140CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004141 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004142 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004143 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004144 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004145
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004146 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004147 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004148}
4149
4150CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004151 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004152 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004153 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004154 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004155
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004156 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004157 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4158}
4159
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004160CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4161 if (isNotUsableTU(CTUnit)) {
4162 LOG_BAD_TU(CTUnit);
4163 return nullptr;
4164 }
4165
4166 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4167 impl->TranslationUnit = CTUnit;
4168 return impl;
4169}
4170
4171CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4172 if (!TargetInfo)
4173 return cxstring::createEmpty();
4174
4175 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4176 assert(!isNotUsableTU(CTUnit) &&
4177 "Unexpected unusable translation unit in TargetInfo");
4178
4179 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4180 std::string Triple =
4181 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4182 return cxstring::createDup(Triple);
4183}
4184
4185int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4186 if (!TargetInfo)
4187 return -1;
4188
4189 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4190 assert(!isNotUsableTU(CTUnit) &&
4191 "Unexpected unusable translation unit in TargetInfo");
4192
4193 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4194 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4195}
4196
4197void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4198 if (!TargetInfo)
4199 return;
4200
4201 delete TargetInfo;
4202}
4203
Guy Benyei11169dd2012-12-18 14:30:41 +00004204//===----------------------------------------------------------------------===//
4205// CXFile Operations.
4206//===----------------------------------------------------------------------===//
4207
Guy Benyei11169dd2012-12-18 14:30:41 +00004208CXString clang_getFileName(CXFile SFile) {
4209 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004210 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004211
4212 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004213 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004214}
4215
4216time_t clang_getFileTime(CXFile SFile) {
4217 if (!SFile)
4218 return 0;
4219
4220 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4221 return FEnt->getModificationTime();
4222}
4223
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004224CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004225 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004226 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004227 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004228 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004229
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004230 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004231
4232 FileManager &FMgr = CXXUnit->getFileManager();
Harlan Haskins8d323d12019-08-01 21:31:56 +00004233 auto File = FMgr.getFile(file_name);
4234 if (!File)
4235 return nullptr;
4236 return const_cast<FileEntry *>(*File);
Guy Benyei11169dd2012-12-18 14:30:41 +00004237}
4238
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004239const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4240 size_t *size) {
4241 if (isNotUsableTU(TU)) {
4242 LOG_BAD_TU(TU);
4243 return nullptr;
4244 }
4245
4246 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4247 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4248 bool Invalid = true;
Nico Weber04347d82019-04-04 21:06:41 +00004249 const llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004250 if (Invalid) {
4251 if (size)
4252 *size = 0;
4253 return nullptr;
4254 }
4255 if (size)
4256 *size = buf->getBufferSize();
4257 return buf->getBufferStart();
4258}
4259
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004260unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4261 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004262 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004263 LOG_BAD_TU(TU);
4264 return 0;
4265 }
4266
4267 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004268 return 0;
4269
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004270 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004271 FileEntry *FEnt = static_cast<FileEntry *>(file);
4272 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4273 .isFileMultipleIncludeGuarded(FEnt);
4274}
4275
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004276int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4277 if (!file || !outID)
4278 return 1;
4279
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004280 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004281 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4282 outID->data[0] = ID.getDevice();
4283 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004284 outID->data[2] = FEnt->getModificationTime();
4285 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004286}
4287
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004288int clang_File_isEqual(CXFile file1, CXFile file2) {
4289 if (file1 == file2)
4290 return true;
4291
4292 if (!file1 || !file2)
4293 return false;
4294
4295 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4296 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4297 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4298}
4299
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004300CXString clang_File_tryGetRealPathName(CXFile SFile) {
4301 if (!SFile)
4302 return cxstring::createNull();
4303
4304 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4305 return cxstring::createRef(FEnt->tryGetRealPathName());
4306}
4307
Guy Benyei11169dd2012-12-18 14:30:41 +00004308//===----------------------------------------------------------------------===//
4309// CXCursor Operations.
4310//===----------------------------------------------------------------------===//
4311
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004312static const Decl *getDeclFromExpr(const Stmt *E) {
4313 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004314 return getDeclFromExpr(CE->getSubExpr());
4315
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004316 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004317 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004318 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004319 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004320 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004321 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004322 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004323 if (PRE->isExplicitProperty())
4324 return PRE->getExplicitProperty();
4325 // It could be messaging both getter and setter as in:
4326 // ++myobj.myprop;
4327 // in which case prefer to associate the setter since it is less obvious
4328 // from inspecting the source that the setter is going to get called.
4329 if (PRE->isMessagingSetter())
4330 return PRE->getImplicitPropertySetter();
4331 return PRE->getImplicitPropertyGetter();
4332 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004333 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004334 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004335 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004336 if (Expr *Src = OVE->getSourceExpr())
4337 return getDeclFromExpr(Src);
4338
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004339 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004340 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004341 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004342 if (!CE->isElidable())
4343 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004344 if (const CXXInheritedCtorInitExpr *CE =
4345 dyn_cast<CXXInheritedCtorInitExpr>(E))
4346 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004347 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004348 return OME->getMethodDecl();
4349
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004350 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004351 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004352 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004353 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4354 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004355 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004356 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4357 isa<ParmVarDecl>(SizeOfPack->getPack()))
4358 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004359
4360 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004361}
4362
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004363static SourceLocation getLocationFromExpr(const Expr *E) {
4364 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004365 return getLocationFromExpr(CE->getSubExpr());
4366
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004367 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004368 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004369 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004370 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004371 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004372 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004373 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004374 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004375 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004376 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004377 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004378 return PropRef->getLocation();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004379
4380 return E->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00004381}
4382
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004383extern "C" {
4384
Guy Benyei11169dd2012-12-18 14:30:41 +00004385unsigned clang_visitChildren(CXCursor parent,
4386 CXCursorVisitor visitor,
4387 CXClientData client_data) {
4388 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4389 /*VisitPreprocessorLast=*/false);
4390 return CursorVis.VisitChildren(parent);
4391}
4392
4393#ifndef __has_feature
4394#define __has_feature(x) 0
4395#endif
4396#if __has_feature(blocks)
4397typedef enum CXChildVisitResult
4398 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4399
4400static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4401 CXClientData client_data) {
4402 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4403 return block(cursor, parent);
4404}
4405#else
4406// If we are compiled with a compiler that doesn't have native blocks support,
4407// define and call the block manually, so the
4408typedef struct _CXChildVisitResult
4409{
4410 void *isa;
4411 int flags;
4412 int reserved;
4413 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4414 CXCursor);
4415} *CXCursorVisitorBlock;
4416
4417static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4418 CXClientData client_data) {
4419 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4420 return block->invoke(block, cursor, parent);
4421}
4422#endif
4423
4424
4425unsigned clang_visitChildrenWithBlock(CXCursor parent,
4426 CXCursorVisitorBlock block) {
4427 return clang_visitChildren(parent, visitWithBlock, block);
4428}
4429
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004430static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004431 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004432 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004433
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004434 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004435 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004436 if (const ObjCPropertyImplDecl *PropImpl =
4437 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004438 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004439 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004440
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004441 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004442 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004443 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004444
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004445 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004446 }
4447
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004448 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004449 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004450
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004451 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004452 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4453 // and returns different names. NamedDecl returns the class name and
4454 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004455 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004456
4457 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004458 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004459
4460 SmallString<1024> S;
4461 llvm::raw_svector_ostream os(S);
4462 ND->printName(os);
4463
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004464 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004465}
4466
4467CXString clang_getCursorSpelling(CXCursor C) {
4468 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004469 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004470
4471 if (clang_isReference(C.kind)) {
4472 switch (C.kind) {
4473 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004474 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004475 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004476 }
4477 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004478 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004479 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004480 }
4481 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004482 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004483 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004484 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004485 }
4486 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004487 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004488 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004489 }
4490 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004491 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004492 assert(Type && "Missing type decl");
4493
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004494 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004495 getAsString());
4496 }
4497 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004498 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004499 assert(Template && "Missing template decl");
4500
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004501 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004502 }
4503
4504 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004505 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004506 assert(NS && "Missing namespace decl");
4507
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004508 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004509 }
4510
4511 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004512 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004513 assert(Field && "Missing member decl");
4514
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004515 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004516 }
4517
4518 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004519 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004520 assert(Label && "Missing label");
4521
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004522 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004523 }
4524
4525 case CXCursor_OverloadedDeclRef: {
4526 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004527 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4528 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004529 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004530 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004531 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004532 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004533 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004534 OverloadedTemplateStorage *Ovl
4535 = Storage.get<OverloadedTemplateStorage*>();
4536 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004537 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004538 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004539 }
4540
4541 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004542 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004543 assert(Var && "Missing variable decl");
4544
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004545 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004546 }
4547
4548 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004549 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004550 }
4551 }
4552
4553 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004554 const Expr *E = getCursorExpr(C);
4555
4556 if (C.kind == CXCursor_ObjCStringLiteral ||
4557 C.kind == CXCursor_StringLiteral) {
4558 const StringLiteral *SLit;
4559 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4560 SLit = OSL->getString();
4561 } else {
4562 SLit = cast<StringLiteral>(E);
4563 }
4564 SmallString<256> Buf;
4565 llvm::raw_svector_ostream OS(Buf);
4566 SLit->outputString(OS);
4567 return cxstring::createDup(OS.str());
4568 }
4569
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004570 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004571 if (D)
4572 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004573 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004574 }
4575
4576 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004577 const Stmt *S = getCursorStmt(C);
4578 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004579 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004580
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004581 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004582 }
4583
4584 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004585 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004586 ->getNameStart());
4587
4588 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004589 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004590 ->getNameStart());
4591
4592 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004593 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004594
4595 if (clang_isDeclaration(C.kind))
4596 return getDeclSpelling(getCursorDecl(C));
4597
4598 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004599 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004600 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004601 }
4602
4603 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004604 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004605 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004606 }
4607
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004608 if (C.kind == CXCursor_PackedAttr) {
4609 return cxstring::createRef("packed");
4610 }
4611
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004612 if (C.kind == CXCursor_VisibilityAttr) {
4613 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4614 switch (AA->getVisibility()) {
4615 case VisibilityAttr::VisibilityType::Default:
4616 return cxstring::createRef("default");
4617 case VisibilityAttr::VisibilityType::Hidden:
4618 return cxstring::createRef("hidden");
4619 case VisibilityAttr::VisibilityType::Protected:
4620 return cxstring::createRef("protected");
4621 }
4622 llvm_unreachable("unknown visibility type");
4623 }
4624
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004625 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004626}
4627
4628CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4629 unsigned pieceIndex,
4630 unsigned options) {
4631 if (clang_Cursor_isNull(C))
4632 return clang_getNullRange();
4633
4634 ASTContext &Ctx = getCursorContext(C);
4635
4636 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004637 const Stmt *S = getCursorStmt(C);
4638 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004639 if (pieceIndex > 0)
4640 return clang_getNullRange();
4641 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4642 }
4643
4644 return clang_getNullRange();
4645 }
4646
4647 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004648 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004649 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4650 if (pieceIndex >= ME->getNumSelectorLocs())
4651 return clang_getNullRange();
4652 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4653 }
4654 }
4655
4656 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4657 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004658 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004659 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4660 if (pieceIndex >= MD->getNumSelectorLocs())
4661 return clang_getNullRange();
4662 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4663 }
4664 }
4665
4666 if (C.kind == CXCursor_ObjCCategoryDecl ||
4667 C.kind == CXCursor_ObjCCategoryImplDecl) {
4668 if (pieceIndex > 0)
4669 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004670 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004671 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4672 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004673 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004674 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4675 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4676 }
4677
4678 if (C.kind == CXCursor_ModuleImportDecl) {
4679 if (pieceIndex > 0)
4680 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004681 if (const ImportDecl *ImportD =
4682 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004683 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4684 if (!Locs.empty())
4685 return cxloc::translateSourceRange(Ctx,
4686 SourceRange(Locs.front(), Locs.back()));
4687 }
4688 return clang_getNullRange();
4689 }
4690
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004691 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004692 C.kind == CXCursor_ConversionFunction ||
4693 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004694 if (pieceIndex > 0)
4695 return clang_getNullRange();
4696 if (const FunctionDecl *FD =
4697 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4698 DeclarationNameInfo FunctionName = FD->getNameInfo();
4699 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4700 }
4701 return clang_getNullRange();
4702 }
4703
Guy Benyei11169dd2012-12-18 14:30:41 +00004704 // FIXME: A CXCursor_InclusionDirective should give the location of the
4705 // filename, but we don't keep track of this.
4706
4707 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4708 // but we don't keep track of this.
4709
4710 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4711 // but we don't keep track of this.
4712
4713 // Default handling, give the location of the cursor.
4714
4715 if (pieceIndex > 0)
4716 return clang_getNullRange();
4717
4718 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4719 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4720 return cxloc::translateSourceRange(Ctx, Loc);
4721}
4722
Eli Bendersky44a206f2014-07-31 18:04:56 +00004723CXString clang_Cursor_getMangling(CXCursor C) {
4724 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4725 return cxstring::createEmpty();
4726
Eli Bendersky44a206f2014-07-31 18:04:56 +00004727 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004728 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004729 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4730 return cxstring::createEmpty();
4731
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004732 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004733 ASTNameGenerator ASTNameGen(Ctx);
4734 return cxstring::createDup(ASTNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004735}
4736
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004737CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4738 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4739 return nullptr;
4740
4741 const Decl *D = getCursorDecl(C);
4742 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4743 return nullptr;
4744
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004745 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004746 ASTNameGenerator ASTNameGen(Ctx);
4747 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004748 return cxstring::createSet(Manglings);
4749}
4750
Dave Lee1a532c92017-09-22 16:58:57 +00004751CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4752 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4753 return nullptr;
4754
4755 const Decl *D = getCursorDecl(C);
4756 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4757 return nullptr;
4758
4759 ASTContext &Ctx = D->getASTContext();
Jan Korous7e36ecd2019-09-05 20:33:52 +00004760 ASTNameGenerator ASTNameGen(Ctx);
4761 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
Dave Lee1a532c92017-09-22 16:58:57 +00004762 return cxstring::createSet(Manglings);
4763}
4764
Jonathan Coe45ef5032018-01-16 10:19:56 +00004765CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4766 if (clang_Cursor_isNull(C))
4767 return 0;
4768 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4769}
4770
4771void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4772 if (Policy)
4773 delete static_cast<PrintingPolicy *>(Policy);
4774}
4775
4776unsigned
4777clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4778 enum CXPrintingPolicyProperty Property) {
4779 if (!Policy)
4780 return 0;
4781
4782 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4783 switch (Property) {
4784 case CXPrintingPolicy_Indentation:
4785 return P->Indentation;
4786 case CXPrintingPolicy_SuppressSpecifiers:
4787 return P->SuppressSpecifiers;
4788 case CXPrintingPolicy_SuppressTagKeyword:
4789 return P->SuppressTagKeyword;
4790 case CXPrintingPolicy_IncludeTagDefinition:
4791 return P->IncludeTagDefinition;
4792 case CXPrintingPolicy_SuppressScope:
4793 return P->SuppressScope;
4794 case CXPrintingPolicy_SuppressUnwrittenScope:
4795 return P->SuppressUnwrittenScope;
4796 case CXPrintingPolicy_SuppressInitializers:
4797 return P->SuppressInitializers;
4798 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4799 return P->ConstantArraySizeAsWritten;
4800 case CXPrintingPolicy_AnonymousTagLocations:
4801 return P->AnonymousTagLocations;
4802 case CXPrintingPolicy_SuppressStrongLifetime:
4803 return P->SuppressStrongLifetime;
4804 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4805 return P->SuppressLifetimeQualifiers;
4806 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4807 return P->SuppressTemplateArgsInCXXConstructors;
4808 case CXPrintingPolicy_Bool:
4809 return P->Bool;
4810 case CXPrintingPolicy_Restrict:
4811 return P->Restrict;
4812 case CXPrintingPolicy_Alignof:
4813 return P->Alignof;
4814 case CXPrintingPolicy_UnderscoreAlignof:
4815 return P->UnderscoreAlignof;
4816 case CXPrintingPolicy_UseVoidForZeroParams:
4817 return P->UseVoidForZeroParams;
4818 case CXPrintingPolicy_TerseOutput:
4819 return P->TerseOutput;
4820 case CXPrintingPolicy_PolishForDeclaration:
4821 return P->PolishForDeclaration;
4822 case CXPrintingPolicy_Half:
4823 return P->Half;
4824 case CXPrintingPolicy_MSWChar:
4825 return P->MSWChar;
4826 case CXPrintingPolicy_IncludeNewlines:
4827 return P->IncludeNewlines;
4828 case CXPrintingPolicy_MSVCFormatting:
4829 return P->MSVCFormatting;
4830 case CXPrintingPolicy_ConstantsAsWritten:
4831 return P->ConstantsAsWritten;
4832 case CXPrintingPolicy_SuppressImplicitBase:
4833 return P->SuppressImplicitBase;
4834 case CXPrintingPolicy_FullyQualifiedName:
4835 return P->FullyQualifiedName;
4836 }
4837
4838 assert(false && "Invalid CXPrintingPolicyProperty");
4839 return 0;
4840}
4841
4842void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4843 enum CXPrintingPolicyProperty Property,
4844 unsigned Value) {
4845 if (!Policy)
4846 return;
4847
4848 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4849 switch (Property) {
4850 case CXPrintingPolicy_Indentation:
4851 P->Indentation = Value;
4852 return;
4853 case CXPrintingPolicy_SuppressSpecifiers:
4854 P->SuppressSpecifiers = Value;
4855 return;
4856 case CXPrintingPolicy_SuppressTagKeyword:
4857 P->SuppressTagKeyword = Value;
4858 return;
4859 case CXPrintingPolicy_IncludeTagDefinition:
4860 P->IncludeTagDefinition = Value;
4861 return;
4862 case CXPrintingPolicy_SuppressScope:
4863 P->SuppressScope = Value;
4864 return;
4865 case CXPrintingPolicy_SuppressUnwrittenScope:
4866 P->SuppressUnwrittenScope = Value;
4867 return;
4868 case CXPrintingPolicy_SuppressInitializers:
4869 P->SuppressInitializers = Value;
4870 return;
4871 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4872 P->ConstantArraySizeAsWritten = Value;
4873 return;
4874 case CXPrintingPolicy_AnonymousTagLocations:
4875 P->AnonymousTagLocations = Value;
4876 return;
4877 case CXPrintingPolicy_SuppressStrongLifetime:
4878 P->SuppressStrongLifetime = Value;
4879 return;
4880 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4881 P->SuppressLifetimeQualifiers = Value;
4882 return;
4883 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4884 P->SuppressTemplateArgsInCXXConstructors = Value;
4885 return;
4886 case CXPrintingPolicy_Bool:
4887 P->Bool = Value;
4888 return;
4889 case CXPrintingPolicy_Restrict:
4890 P->Restrict = Value;
4891 return;
4892 case CXPrintingPolicy_Alignof:
4893 P->Alignof = Value;
4894 return;
4895 case CXPrintingPolicy_UnderscoreAlignof:
4896 P->UnderscoreAlignof = Value;
4897 return;
4898 case CXPrintingPolicy_UseVoidForZeroParams:
4899 P->UseVoidForZeroParams = Value;
4900 return;
4901 case CXPrintingPolicy_TerseOutput:
4902 P->TerseOutput = Value;
4903 return;
4904 case CXPrintingPolicy_PolishForDeclaration:
4905 P->PolishForDeclaration = Value;
4906 return;
4907 case CXPrintingPolicy_Half:
4908 P->Half = Value;
4909 return;
4910 case CXPrintingPolicy_MSWChar:
4911 P->MSWChar = Value;
4912 return;
4913 case CXPrintingPolicy_IncludeNewlines:
4914 P->IncludeNewlines = Value;
4915 return;
4916 case CXPrintingPolicy_MSVCFormatting:
4917 P->MSVCFormatting = Value;
4918 return;
4919 case CXPrintingPolicy_ConstantsAsWritten:
4920 P->ConstantsAsWritten = Value;
4921 return;
4922 case CXPrintingPolicy_SuppressImplicitBase:
4923 P->SuppressImplicitBase = Value;
4924 return;
4925 case CXPrintingPolicy_FullyQualifiedName:
4926 P->FullyQualifiedName = Value;
4927 return;
4928 }
4929
4930 assert(false && "Invalid CXPrintingPolicyProperty");
4931}
4932
4933CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4934 if (clang_Cursor_isNull(C))
4935 return cxstring::createEmpty();
4936
4937 if (clang_isDeclaration(C.kind)) {
4938 const Decl *D = getCursorDecl(C);
4939 if (!D)
4940 return cxstring::createEmpty();
4941
4942 SmallString<128> Str;
4943 llvm::raw_svector_ostream OS(Str);
4944 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4945 D->print(OS, UserPolicy ? *UserPolicy
4946 : getCursorContext(C).getPrintingPolicy());
4947
4948 return cxstring::createDup(OS.str());
4949 }
4950
4951 return cxstring::createEmpty();
4952}
4953
Guy Benyei11169dd2012-12-18 14:30:41 +00004954CXString clang_getCursorDisplayName(CXCursor C) {
4955 if (!clang_isDeclaration(C.kind))
4956 return clang_getCursorSpelling(C);
4957
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004958 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004959 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004960 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004961
4962 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004963 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004964 D = FunTmpl->getTemplatedDecl();
4965
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004966 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004967 SmallString<64> Str;
4968 llvm::raw_svector_ostream OS(Str);
4969 OS << *Function;
4970 if (Function->getPrimaryTemplate())
4971 OS << "<>";
4972 OS << "(";
4973 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4974 if (I)
4975 OS << ", ";
4976 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4977 }
4978
4979 if (Function->isVariadic()) {
4980 if (Function->getNumParams())
4981 OS << ", ";
4982 OS << "...";
4983 }
4984 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004985 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004986 }
4987
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004988 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004989 SmallString<64> Str;
4990 llvm::raw_svector_ostream OS(Str);
4991 OS << *ClassTemplate;
4992 OS << "<";
4993 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4994 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4995 if (I)
4996 OS << ", ";
4997
4998 NamedDecl *Param = Params->getParam(I);
4999 if (Param->getIdentifier()) {
5000 OS << Param->getIdentifier()->getName();
5001 continue;
5002 }
5003
5004 // There is no parameter name, which makes this tricky. Try to come up
5005 // with something useful that isn't too long.
5006 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5007 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
5008 else if (NonTypeTemplateParmDecl *NTTP
5009 = dyn_cast<NonTypeTemplateParmDecl>(Param))
5010 OS << NTTP->getType().getAsString(Policy);
5011 else
5012 OS << "template<...> class";
5013 }
5014
5015 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005016 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005017 }
5018
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005019 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00005020 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
5021 // If the type was explicitly written, use that.
5022 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005023 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00005024
Benjamin Kramer9170e912013-02-22 15:46:01 +00005025 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00005026 llvm::raw_svector_ostream OS(Str);
5027 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00005028 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5029 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005030 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005031 }
5032
5033 return clang_getCursorSpelling(C);
5034}
5035
5036CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5037 switch (Kind) {
5038 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005039 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005040 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005041 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005042 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005043 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005044 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005045 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005046 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005047 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005048 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005049 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005050 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005051 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005052 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005053 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005054 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005055 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005056 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005057 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005058 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005059 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005060 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005061 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005062 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005063 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005064 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005065 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005066 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005067 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005068 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005069 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005070 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005071 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005072 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005073 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005074 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005075 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005076 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005077 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005078 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005079 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005080 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005081 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005082 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005083 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005084 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005085 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005086 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005087 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005088 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005089 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005090 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005091 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005092 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005093 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005094 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005095 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005096 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005097 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005098 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005099 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005100 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005101 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005102 case CXCursor_FixedPointLiteral:
5103 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005104 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005105 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005106 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005107 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005108 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005109 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005110 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005111 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005112 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005113 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005114 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005115 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005116 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005117 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005118 case CXCursor_OMPArraySectionExpr:
5119 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005120 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005121 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005122 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005123 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005124 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005125 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005126 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005127 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005128 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005129 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005130 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005131 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005132 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005133 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005134 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005135 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005136 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005137 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005138 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005139 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005140 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005141 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005142 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005143 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005144 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005145 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005146 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005147 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005148 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005149 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005150 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005151 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005152 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005153 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005154 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005155 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005156 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005157 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005158 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005159 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005160 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005161 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005162 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005163 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005164 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005165 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005166 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005167 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005168 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005169 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005170 case CXCursor_ObjCAvailabilityCheckExpr:
5171 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005172 case CXCursor_ObjCSelfExpr:
5173 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005174 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005175 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005176 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005177 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005178 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005179 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005180 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005181 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005182 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005183 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005184 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005185 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005186 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005187 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005188 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005189 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005190 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005191 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005192 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005193 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005194 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005195 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005196 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005197 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005198 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005199 return cxstring::createRef("ObjCMessageExpr");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005200 case CXCursor_BuiltinBitCastExpr:
5201 return cxstring::createRef("BuiltinBitCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005202 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005203 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005204 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005205 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005206 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005207 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005208 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005209 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005210 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005211 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005212 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005213 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005214 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005215 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005216 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005217 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005218 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005219 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005220 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005221 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005222 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005223 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005224 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005225 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005226 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005227 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005228 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005229 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005230 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005231 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005232 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005233 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005234 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005235 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005236 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005237 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005238 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005239 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005240 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005241 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005242 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005243 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005244 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005245 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005246 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005247 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005248 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005249 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005250 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005251 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005252 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005253 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005254 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005255 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005256 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005257 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005258 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005259 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005260 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005261 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005262 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005263 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005264 case CXCursor_SEHLeaveStmt:
5265 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005266 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005267 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005268 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005269 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005270 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005271 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005272 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005273 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005274 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005275 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005276 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005277 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005278 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005279 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005280 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005281 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005282 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005283 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005284 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005285 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005286 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005287 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005288 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005289 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005290 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005291 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005292 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005293 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005294 case CXCursor_PackedAttr:
5295 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005296 case CXCursor_PureAttr:
5297 return cxstring::createRef("attribute(pure)");
5298 case CXCursor_ConstAttr:
5299 return cxstring::createRef("attribute(const)");
5300 case CXCursor_NoDuplicateAttr:
5301 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005302 case CXCursor_CUDAConstantAttr:
5303 return cxstring::createRef("attribute(constant)");
5304 case CXCursor_CUDADeviceAttr:
5305 return cxstring::createRef("attribute(device)");
5306 case CXCursor_CUDAGlobalAttr:
5307 return cxstring::createRef("attribute(global)");
5308 case CXCursor_CUDAHostAttr:
5309 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005310 case CXCursor_CUDASharedAttr:
5311 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005312 case CXCursor_VisibilityAttr:
5313 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005314 case CXCursor_DLLExport:
5315 return cxstring::createRef("attribute(dllexport)");
5316 case CXCursor_DLLImport:
5317 return cxstring::createRef("attribute(dllimport)");
Michael Wud092d0b2018-08-03 05:03:22 +00005318 case CXCursor_NSReturnsRetained:
5319 return cxstring::createRef("attribute(ns_returns_retained)");
5320 case CXCursor_NSReturnsNotRetained:
5321 return cxstring::createRef("attribute(ns_returns_not_retained)");
5322 case CXCursor_NSReturnsAutoreleased:
5323 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5324 case CXCursor_NSConsumesSelf:
5325 return cxstring::createRef("attribute(ns_consumes_self)");
5326 case CXCursor_NSConsumed:
5327 return cxstring::createRef("attribute(ns_consumed)");
5328 case CXCursor_ObjCException:
5329 return cxstring::createRef("attribute(objc_exception)");
5330 case CXCursor_ObjCNSObject:
5331 return cxstring::createRef("attribute(NSObject)");
5332 case CXCursor_ObjCIndependentClass:
5333 return cxstring::createRef("attribute(objc_independent_class)");
5334 case CXCursor_ObjCPreciseLifetime:
5335 return cxstring::createRef("attribute(objc_precise_lifetime)");
5336 case CXCursor_ObjCReturnsInnerPointer:
5337 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5338 case CXCursor_ObjCRequiresSuper:
5339 return cxstring::createRef("attribute(objc_requires_super)");
5340 case CXCursor_ObjCRootClass:
5341 return cxstring::createRef("attribute(objc_root_class)");
5342 case CXCursor_ObjCSubclassingRestricted:
5343 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5344 case CXCursor_ObjCExplicitProtocolImpl:
5345 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5346 case CXCursor_ObjCDesignatedInitializer:
5347 return cxstring::createRef("attribute(objc_designated_initializer)");
5348 case CXCursor_ObjCRuntimeVisible:
5349 return cxstring::createRef("attribute(objc_runtime_visible)");
5350 case CXCursor_ObjCBoxable:
5351 return cxstring::createRef("attribute(objc_boxable)");
Michael Wu58d837d2018-08-03 05:55:40 +00005352 case CXCursor_FlagEnum:
5353 return cxstring::createRef("attribute(flag_enum)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005354 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005355 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005356 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005357 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005358 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005359 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005360 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005361 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005362 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005363 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005364 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005365 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005366 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005367 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005368 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005369 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005370 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005371 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005372 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005373 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005374 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005375 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005376 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005377 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005378 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005379 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005380 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005381 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005382 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005383 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005384 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005385 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005386 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005387 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005388 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005389 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005390 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005391 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005392 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005393 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005394 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005395 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005396 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005397 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005398 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005399 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005400 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005401 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005402 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005403 return cxstring::createRef("OMPParallelDirective");
5404 case CXCursor_OMPSimdDirective:
5405 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005406 case CXCursor_OMPForDirective:
5407 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005408 case CXCursor_OMPForSimdDirective:
5409 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005410 case CXCursor_OMPSectionsDirective:
5411 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005412 case CXCursor_OMPSectionDirective:
5413 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005414 case CXCursor_OMPSingleDirective:
5415 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005416 case CXCursor_OMPMasterDirective:
5417 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005418 case CXCursor_OMPCriticalDirective:
5419 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005420 case CXCursor_OMPParallelForDirective:
5421 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005422 case CXCursor_OMPParallelForSimdDirective:
5423 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005424 case CXCursor_OMPParallelSectionsDirective:
5425 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005426 case CXCursor_OMPTaskDirective:
5427 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005428 case CXCursor_OMPTaskyieldDirective:
5429 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005430 case CXCursor_OMPBarrierDirective:
5431 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005432 case CXCursor_OMPTaskwaitDirective:
5433 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005434 case CXCursor_OMPTaskgroupDirective:
5435 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005436 case CXCursor_OMPFlushDirective:
5437 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005438 case CXCursor_OMPOrderedDirective:
5439 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005440 case CXCursor_OMPAtomicDirective:
5441 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005442 case CXCursor_OMPTargetDirective:
5443 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005444 case CXCursor_OMPTargetDataDirective:
5445 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005446 case CXCursor_OMPTargetEnterDataDirective:
5447 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005448 case CXCursor_OMPTargetExitDataDirective:
5449 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005450 case CXCursor_OMPTargetParallelDirective:
5451 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005452 case CXCursor_OMPTargetParallelForDirective:
5453 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005454 case CXCursor_OMPTargetUpdateDirective:
5455 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005456 case CXCursor_OMPTeamsDirective:
5457 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005458 case CXCursor_OMPCancellationPointDirective:
5459 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005460 case CXCursor_OMPCancelDirective:
5461 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005462 case CXCursor_OMPTaskLoopDirective:
5463 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005464 case CXCursor_OMPTaskLoopSimdDirective:
5465 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005466 case CXCursor_OMPDistributeDirective:
5467 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005468 case CXCursor_OMPDistributeParallelForDirective:
5469 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005470 case CXCursor_OMPDistributeParallelForSimdDirective:
5471 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005472 case CXCursor_OMPDistributeSimdDirective:
5473 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005474 case CXCursor_OMPTargetParallelForSimdDirective:
5475 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005476 case CXCursor_OMPTargetSimdDirective:
5477 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005478 case CXCursor_OMPTeamsDistributeDirective:
5479 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005480 case CXCursor_OMPTeamsDistributeSimdDirective:
5481 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005482 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5483 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005484 case CXCursor_OMPTeamsDistributeParallelForDirective:
5485 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005486 case CXCursor_OMPTargetTeamsDirective:
5487 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005488 case CXCursor_OMPTargetTeamsDistributeDirective:
5489 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005490 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5491 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005492 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5493 return cxstring::createRef(
5494 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005495 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5496 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005497 case CXCursor_OverloadCandidate:
5498 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005499 case CXCursor_TypeAliasTemplateDecl:
5500 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005501 case CXCursor_StaticAssert:
5502 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005503 case CXCursor_FriendDecl:
Sven van Haastregtdc2c9302019-02-11 11:00:56 +00005504 return cxstring::createRef("FriendDecl");
5505 case CXCursor_ConvergentAttr:
5506 return cxstring::createRef("attribute(convergent)");
Emilio Cobos Alvarez0a3fe502019-02-25 21:24:52 +00005507 case CXCursor_WarnUnusedAttr:
5508 return cxstring::createRef("attribute(warn_unused)");
5509 case CXCursor_WarnUnusedResultAttr:
5510 return cxstring::createRef("attribute(warn_unused_result)");
Emilio Cobos Alvarezcd741272019-03-13 16:16:54 +00005511 case CXCursor_AlignedAttr:
5512 return cxstring::createRef("attribute(aligned)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005513 }
5514
5515 llvm_unreachable("Unhandled CXCursorKind");
5516}
5517
5518struct GetCursorData {
5519 SourceLocation TokenBeginLoc;
5520 bool PointsAtMacroArgExpansion;
5521 bool VisitedObjCPropertyImplDecl;
5522 SourceLocation VisitedDeclaratorDeclStartLoc;
5523 CXCursor &BestCursor;
5524
5525 GetCursorData(SourceManager &SM,
5526 SourceLocation tokenBegin, CXCursor &outputCursor)
5527 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5528 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5529 VisitedObjCPropertyImplDecl = false;
5530 }
5531};
5532
5533static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5534 CXCursor parent,
5535 CXClientData client_data) {
5536 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5537 CXCursor *BestCursor = &Data->BestCursor;
5538
5539 // If we point inside a macro argument we should provide info of what the
5540 // token is so use the actual cursor, don't replace it with a macro expansion
5541 // cursor.
5542 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5543 return CXChildVisit_Recurse;
5544
5545 if (clang_isDeclaration(cursor.kind)) {
5546 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005547 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005548 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5549 if (MD->isImplicit())
5550 return CXChildVisit_Break;
5551
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005552 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005553 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5554 // Check that when we have multiple @class references in the same line,
5555 // that later ones do not override the previous ones.
5556 // If we have:
5557 // @class Foo, Bar;
5558 // source ranges for both start at '@', so 'Bar' will end up overriding
5559 // 'Foo' even though the cursor location was at 'Foo'.
5560 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5561 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005562 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005563 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5564 if (PrevID != ID &&
5565 !PrevID->isThisDeclarationADefinition() &&
5566 !ID->isThisDeclarationADefinition())
5567 return CXChildVisit_Break;
5568 }
5569
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005570 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005571 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5572 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5573 // Check that when we have multiple declarators in the same line,
5574 // that later ones do not override the previous ones.
5575 // If we have:
5576 // int Foo, Bar;
5577 // source ranges for both start at 'int', so 'Bar' will end up overriding
5578 // 'Foo' even though the cursor location was at 'Foo'.
5579 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5580 return CXChildVisit_Break;
5581 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5582
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005583 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005584 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5585 (void)PropImp;
5586 // Check that when we have multiple @synthesize in the same line,
5587 // that later ones do not override the previous ones.
5588 // If we have:
5589 // @synthesize Foo, Bar;
5590 // source ranges for both start at '@', so 'Bar' will end up overriding
5591 // 'Foo' even though the cursor location was at 'Foo'.
5592 if (Data->VisitedObjCPropertyImplDecl)
5593 return CXChildVisit_Break;
5594 Data->VisitedObjCPropertyImplDecl = true;
5595 }
5596 }
5597
5598 if (clang_isExpression(cursor.kind) &&
5599 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005600 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005601 // Avoid having the cursor of an expression replace the declaration cursor
5602 // when the expression source range overlaps the declaration range.
5603 // This can happen for C++ constructor expressions whose range generally
5604 // include the variable declaration, e.g.:
5605 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5606 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5607 D->getLocation() == Data->TokenBeginLoc)
5608 return CXChildVisit_Break;
5609 }
5610 }
5611
5612 // If our current best cursor is the construction of a temporary object,
5613 // don't replace that cursor with a type reference, because we want
5614 // clang_getCursor() to point at the constructor.
5615 if (clang_isExpression(BestCursor->kind) &&
5616 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5617 cursor.kind == CXCursor_TypeRef) {
5618 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5619 // as having the actual point on the type reference.
5620 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5621 return CXChildVisit_Recurse;
5622 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005623
5624 // If we already have an Objective-C superclass reference, don't
5625 // update it further.
5626 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5627 return CXChildVisit_Break;
5628
Guy Benyei11169dd2012-12-18 14:30:41 +00005629 *BestCursor = cursor;
5630 return CXChildVisit_Recurse;
5631}
5632
5633CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005634 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005635 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005636 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005637 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005638
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005639 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005640 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5641
5642 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5643 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5644
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005645 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005646 CXFile SearchFile;
5647 unsigned SearchLine, SearchColumn;
5648 CXFile ResultFile;
5649 unsigned ResultLine, ResultColumn;
5650 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5651 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5652 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005653
5654 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5655 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005656 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005657 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005658 SearchFileName = clang_getFileName(SearchFile);
5659 ResultFileName = clang_getFileName(ResultFile);
5660 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5661 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005662 *Log << llvm::format("(%s:%d:%d) = %s",
5663 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5664 clang_getCString(KindSpelling))
5665 << llvm::format("(%s:%d:%d):%s%s",
5666 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5667 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005668 clang_disposeString(SearchFileName);
5669 clang_disposeString(ResultFileName);
5670 clang_disposeString(KindSpelling);
5671 clang_disposeString(USR);
5672
5673 CXCursor Definition = clang_getCursorDefinition(Result);
5674 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5675 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5676 CXString DefinitionKindSpelling
5677 = clang_getCursorKindSpelling(Definition.kind);
5678 CXFile DefinitionFile;
5679 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005680 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005681 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005682 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005683 *Log << llvm::format(" -> %s(%s:%d:%d)",
5684 clang_getCString(DefinitionKindSpelling),
5685 clang_getCString(DefinitionFileName),
5686 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005687 clang_disposeString(DefinitionFileName);
5688 clang_disposeString(DefinitionKindSpelling);
5689 }
5690 }
5691
5692 return Result;
5693}
5694
5695CXCursor clang_getNullCursor(void) {
5696 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5697}
5698
5699unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005700 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5701 // can't set consistently. For example, when visiting a DeclStmt we will set
5702 // it but we don't set it on the result of clang_getCursorDefinition for
5703 // a reference of the same declaration.
5704 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5705 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5706 // to provide that kind of info.
5707 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005708 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005709 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005710 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005711
Guy Benyei11169dd2012-12-18 14:30:41 +00005712 return X == Y;
5713}
5714
5715unsigned clang_hashCursor(CXCursor C) {
5716 unsigned Index = 0;
5717 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5718 Index = 1;
5719
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005720 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005721 std::make_pair(C.kind, C.data[Index]));
5722}
5723
5724unsigned clang_isInvalid(enum CXCursorKind K) {
5725 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5726}
5727
5728unsigned clang_isDeclaration(enum CXCursorKind K) {
5729 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005730 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5731}
5732
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005733unsigned clang_isInvalidDeclaration(CXCursor C) {
5734 if (clang_isDeclaration(C.kind)) {
5735 if (const Decl *D = getCursorDecl(C))
5736 return D->isInvalidDecl();
5737 }
5738
5739 return 0;
5740}
5741
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005742unsigned clang_isReference(enum CXCursorKind K) {
5743 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5744}
Guy Benyei11169dd2012-12-18 14:30:41 +00005745
5746unsigned clang_isExpression(enum CXCursorKind K) {
5747 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5748}
5749
5750unsigned clang_isStatement(enum CXCursorKind K) {
5751 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5752}
5753
5754unsigned clang_isAttribute(enum CXCursorKind K) {
5755 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5756}
5757
5758unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5759 return K == CXCursor_TranslationUnit;
5760}
5761
5762unsigned clang_isPreprocessing(enum CXCursorKind K) {
5763 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5764}
5765
5766unsigned clang_isUnexposed(enum CXCursorKind K) {
5767 switch (K) {
5768 case CXCursor_UnexposedDecl:
5769 case CXCursor_UnexposedExpr:
5770 case CXCursor_UnexposedStmt:
5771 case CXCursor_UnexposedAttr:
5772 return true;
5773 default:
5774 return false;
5775 }
5776}
5777
5778CXCursorKind clang_getCursorKind(CXCursor C) {
5779 return C.kind;
5780}
5781
5782CXSourceLocation clang_getCursorLocation(CXCursor C) {
5783 if (clang_isReference(C.kind)) {
5784 switch (C.kind) {
5785 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005786 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005787 = getCursorObjCSuperClassRef(C);
5788 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5789 }
5790
5791 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005792 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005793 = getCursorObjCProtocolRef(C);
5794 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5795 }
5796
5797 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005798 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005799 = getCursorObjCClassRef(C);
5800 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5801 }
5802
5803 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005804 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005805 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5806 }
5807
5808 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005809 std::pair<const TemplateDecl *, SourceLocation> P =
5810 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005811 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5812 }
5813
5814 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005815 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005816 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5817 }
5818
5819 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005820 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005821 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5822 }
5823
5824 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005825 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005826 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5827 }
5828
5829 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005830 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005831 if (!BaseSpec)
5832 return clang_getNullLocation();
5833
5834 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5835 return cxloc::translateSourceLocation(getCursorContext(C),
5836 TSInfo->getTypeLoc().getBeginLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005837
Guy Benyei11169dd2012-12-18 14:30:41 +00005838 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005839 BaseSpec->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005840 }
5841
5842 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005843 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005844 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5845 }
5846
5847 case CXCursor_OverloadedDeclRef:
5848 return cxloc::translateSourceLocation(getCursorContext(C),
5849 getCursorOverloadedDeclRef(C).second);
5850
5851 default:
5852 // FIXME: Need a way to enumerate all non-reference cases.
5853 llvm_unreachable("Missed a reference kind");
5854 }
5855 }
5856
5857 if (clang_isExpression(C.kind))
5858 return cxloc::translateSourceLocation(getCursorContext(C),
5859 getLocationFromExpr(getCursorExpr(C)));
5860
5861 if (clang_isStatement(C.kind))
5862 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005863 getCursorStmt(C)->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005864
5865 if (C.kind == CXCursor_PreprocessingDirective) {
5866 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5867 return cxloc::translateSourceLocation(getCursorContext(C), L);
5868 }
5869
5870 if (C.kind == CXCursor_MacroExpansion) {
5871 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005872 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005873 return cxloc::translateSourceLocation(getCursorContext(C), L);
5874 }
5875
5876 if (C.kind == CXCursor_MacroDefinition) {
5877 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5878 return cxloc::translateSourceLocation(getCursorContext(C), L);
5879 }
5880
5881 if (C.kind == CXCursor_InclusionDirective) {
5882 SourceLocation L
5883 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5884 return cxloc::translateSourceLocation(getCursorContext(C), L);
5885 }
5886
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005887 if (clang_isAttribute(C.kind)) {
5888 SourceLocation L
5889 = cxcursor::getCursorAttr(C)->getLocation();
5890 return cxloc::translateSourceLocation(getCursorContext(C), L);
5891 }
5892
Guy Benyei11169dd2012-12-18 14:30:41 +00005893 if (!clang_isDeclaration(C.kind))
5894 return clang_getNullLocation();
5895
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005896 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005897 if (!D)
5898 return clang_getNullLocation();
5899
5900 SourceLocation Loc = D->getLocation();
5901 // FIXME: Multiple variables declared in a single declaration
5902 // currently lack the information needed to correctly determine their
5903 // ranges when accounting for the type-specifier. We use context
5904 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5905 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005906 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005907 if (!cxcursor::isFirstInDeclGroup(C))
5908 Loc = VD->getLocation();
5909 }
5910
5911 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005912 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005913 Loc = MD->getSelectorStartLoc();
5914
5915 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5916}
5917
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005918} // end extern "C"
5919
Guy Benyei11169dd2012-12-18 14:30:41 +00005920CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5921 assert(TU);
5922
5923 // Guard against an invalid SourceLocation, or we may assert in one
5924 // of the following calls.
5925 if (SLoc.isInvalid())
5926 return clang_getNullCursor();
5927
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005928 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005929
5930 // Translate the given source location to make it point at the beginning of
5931 // the token under the cursor.
5932 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5933 CXXUnit->getASTContext().getLangOpts());
5934
5935 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5936 if (SLoc.isValid()) {
5937 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5938 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5939 /*VisitPreprocessorLast=*/true,
5940 /*VisitIncludedEntities=*/false,
5941 SourceLocation(SLoc));
5942 CursorVis.visitFileRegion();
5943 }
5944
5945 return Result;
5946}
5947
5948static SourceRange getRawCursorExtent(CXCursor C) {
5949 if (clang_isReference(C.kind)) {
5950 switch (C.kind) {
5951 case CXCursor_ObjCSuperClassRef:
5952 return getCursorObjCSuperClassRef(C).second;
5953
5954 case CXCursor_ObjCProtocolRef:
5955 return getCursorObjCProtocolRef(C).second;
5956
5957 case CXCursor_ObjCClassRef:
5958 return getCursorObjCClassRef(C).second;
5959
5960 case CXCursor_TypeRef:
5961 return getCursorTypeRef(C).second;
5962
5963 case CXCursor_TemplateRef:
5964 return getCursorTemplateRef(C).second;
5965
5966 case CXCursor_NamespaceRef:
5967 return getCursorNamespaceRef(C).second;
5968
5969 case CXCursor_MemberRef:
5970 return getCursorMemberRef(C).second;
5971
5972 case CXCursor_CXXBaseSpecifier:
5973 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5974
5975 case CXCursor_LabelRef:
5976 return getCursorLabelRef(C).second;
5977
5978 case CXCursor_OverloadedDeclRef:
5979 return getCursorOverloadedDeclRef(C).second;
5980
5981 case CXCursor_VariableRef:
5982 return getCursorVariableRef(C).second;
5983
5984 default:
5985 // FIXME: Need a way to enumerate all non-reference cases.
5986 llvm_unreachable("Missed a reference kind");
5987 }
5988 }
5989
5990 if (clang_isExpression(C.kind))
5991 return getCursorExpr(C)->getSourceRange();
5992
5993 if (clang_isStatement(C.kind))
5994 return getCursorStmt(C)->getSourceRange();
5995
5996 if (clang_isAttribute(C.kind))
5997 return getCursorAttr(C)->getRange();
5998
5999 if (C.kind == CXCursor_PreprocessingDirective)
6000 return cxcursor::getCursorPreprocessingDirective(C);
6001
6002 if (C.kind == CXCursor_MacroExpansion) {
6003 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006004 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006005 return TU->mapRangeFromPreamble(Range);
6006 }
6007
6008 if (C.kind == CXCursor_MacroDefinition) {
6009 ASTUnit *TU = getCursorASTUnit(C);
6010 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
6011 return TU->mapRangeFromPreamble(Range);
6012 }
6013
6014 if (C.kind == CXCursor_InclusionDirective) {
6015 ASTUnit *TU = getCursorASTUnit(C);
6016 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
6017 return TU->mapRangeFromPreamble(Range);
6018 }
6019
6020 if (C.kind == CXCursor_TranslationUnit) {
6021 ASTUnit *TU = getCursorASTUnit(C);
6022 FileID MainID = TU->getSourceManager().getMainFileID();
6023 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
6024 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
6025 return SourceRange(Start, End);
6026 }
6027
6028 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006029 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006030 if (!D)
6031 return SourceRange();
6032
6033 SourceRange R = D->getSourceRange();
6034 // FIXME: Multiple variables declared in a single declaration
6035 // currently lack the information needed to correctly determine their
6036 // ranges when accounting for the type-specifier. We use context
6037 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6038 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006039 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006040 if (!cxcursor::isFirstInDeclGroup(C))
6041 R.setBegin(VD->getLocation());
6042 }
6043 return R;
6044 }
6045 return SourceRange();
6046}
6047
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006048/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00006049/// the decl-specifier-seq for declarations.
6050static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6051 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006052 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006053 if (!D)
6054 return SourceRange();
6055
6056 SourceRange R = D->getSourceRange();
6057
6058 // Adjust the start of the location for declarations preceded by
6059 // declaration specifiers.
6060 SourceLocation StartLoc;
6061 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6062 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006063 StartLoc = TI->getTypeLoc().getBeginLoc();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006064 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006065 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006066 StartLoc = TI->getTypeLoc().getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006067 }
6068
6069 if (StartLoc.isValid() && R.getBegin().isValid() &&
6070 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6071 R.setBegin(StartLoc);
6072
6073 // FIXME: Multiple variables declared in a single declaration
6074 // currently lack the information needed to correctly determine their
6075 // ranges when accounting for the type-specifier. We use context
6076 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6077 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006078 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006079 if (!cxcursor::isFirstInDeclGroup(C))
6080 R.setBegin(VD->getLocation());
6081 }
6082
6083 return R;
6084 }
6085
6086 return getRawCursorExtent(C);
6087}
6088
Guy Benyei11169dd2012-12-18 14:30:41 +00006089CXSourceRange clang_getCursorExtent(CXCursor C) {
6090 SourceRange R = getRawCursorExtent(C);
6091 if (R.isInvalid())
6092 return clang_getNullRange();
6093
6094 return cxloc::translateSourceRange(getCursorContext(C), R);
6095}
6096
6097CXCursor clang_getCursorReferenced(CXCursor C) {
6098 if (clang_isInvalid(C.kind))
6099 return clang_getNullCursor();
6100
6101 CXTranslationUnit tu = getCursorTU(C);
6102 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006103 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006104 if (!D)
6105 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006106 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006107 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006108 if (const ObjCPropertyImplDecl *PropImpl =
6109 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006110 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6111 return MakeCXCursor(Property, tu);
6112
6113 return C;
6114 }
6115
6116 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006117 const Expr *E = getCursorExpr(C);
6118 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006119 if (D) {
6120 CXCursor declCursor = MakeCXCursor(D, tu);
6121 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6122 declCursor);
6123 return declCursor;
6124 }
6125
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006126 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006127 return MakeCursorOverloadedDeclRef(Ovl, tu);
6128
6129 return clang_getNullCursor();
6130 }
6131
6132 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006133 const Stmt *S = getCursorStmt(C);
6134 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006135 if (LabelDecl *label = Goto->getLabel())
6136 if (LabelStmt *labelS = label->getStmt())
6137 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6138
6139 return clang_getNullCursor();
6140 }
Richard Smith66a81862015-05-04 02:25:31 +00006141
Guy Benyei11169dd2012-12-18 14:30:41 +00006142 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006143 if (const MacroDefinitionRecord *Def =
6144 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006145 return MakeMacroDefinitionCursor(Def, tu);
6146 }
6147
6148 if (!clang_isReference(C.kind))
6149 return clang_getNullCursor();
6150
6151 switch (C.kind) {
6152 case CXCursor_ObjCSuperClassRef:
6153 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6154
6155 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006156 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6157 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006158 return MakeCXCursor(Def, tu);
6159
6160 return MakeCXCursor(Prot, tu);
6161 }
6162
6163 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006164 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6165 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006166 return MakeCXCursor(Def, tu);
6167
6168 return MakeCXCursor(Class, tu);
6169 }
6170
6171 case CXCursor_TypeRef:
6172 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6173
6174 case CXCursor_TemplateRef:
6175 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6176
6177 case CXCursor_NamespaceRef:
6178 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6179
6180 case CXCursor_MemberRef:
6181 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6182
6183 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006184 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006185 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6186 tu ));
6187 }
6188
6189 case CXCursor_LabelRef:
6190 // FIXME: We end up faking the "parent" declaration here because we
6191 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006192 return MakeCXCursor(getCursorLabelRef(C).first,
6193 cxtu::getASTUnit(tu)->getASTContext()
6194 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006195 tu);
6196
6197 case CXCursor_OverloadedDeclRef:
6198 return C;
6199
6200 case CXCursor_VariableRef:
6201 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6202
6203 default:
6204 // We would prefer to enumerate all non-reference cursor kinds here.
6205 llvm_unreachable("Unhandled reference cursor kind");
6206 }
6207}
6208
6209CXCursor clang_getCursorDefinition(CXCursor C) {
6210 if (clang_isInvalid(C.kind))
6211 return clang_getNullCursor();
6212
6213 CXTranslationUnit TU = getCursorTU(C);
6214
6215 bool WasReference = false;
6216 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6217 C = clang_getCursorReferenced(C);
6218 WasReference = true;
6219 }
6220
6221 if (C.kind == CXCursor_MacroExpansion)
6222 return clang_getCursorReferenced(C);
6223
6224 if (!clang_isDeclaration(C.kind))
6225 return clang_getNullCursor();
6226
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006227 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006228 if (!D)
6229 return clang_getNullCursor();
6230
6231 switch (D->getKind()) {
6232 // Declaration kinds that don't really separate the notions of
6233 // declaration and definition.
6234 case Decl::Namespace:
6235 case Decl::Typedef:
6236 case Decl::TypeAlias:
6237 case Decl::TypeAliasTemplate:
6238 case Decl::TemplateTypeParm:
6239 case Decl::EnumConstant:
6240 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006241 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006242 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006243 case Decl::IndirectField:
6244 case Decl::ObjCIvar:
6245 case Decl::ObjCAtDefsField:
6246 case Decl::ImplicitParam:
6247 case Decl::ParmVar:
6248 case Decl::NonTypeTemplateParm:
6249 case Decl::TemplateTemplateParm:
6250 case Decl::ObjCCategoryImpl:
6251 case Decl::ObjCImplementation:
6252 case Decl::AccessSpec:
6253 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006254 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006255 case Decl::ObjCPropertyImpl:
6256 case Decl::FileScopeAsm:
6257 case Decl::StaticAssert:
6258 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006259 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006260 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006261 case Decl::Label: // FIXME: Is this right??
6262 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006263 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006264 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006265 case Decl::OMPThreadPrivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00006266 case Decl::OMPAllocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006267 case Decl::OMPDeclareReduction:
Michael Kruse251e1482019-02-01 20:25:04 +00006268 case Decl::OMPDeclareMapper:
Kelvin Li1408f912018-09-26 04:28:39 +00006269 case Decl::OMPRequires:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006270 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006271 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006272 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006273 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006274 case Decl::UsingPack:
Saar Razd7aae332019-07-10 21:25:49 +00006275 case Decl::Concept:
Guy Benyei11169dd2012-12-18 14:30:41 +00006276 return C;
6277
6278 // Declaration kinds that don't make any sense here, but are
6279 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006280 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006281 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006282 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006283 break;
6284
6285 // Declaration kinds for which the definition is not resolvable.
6286 case Decl::UnresolvedUsingTypename:
6287 case Decl::UnresolvedUsingValue:
6288 break;
6289
6290 case Decl::UsingDirective:
6291 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6292 TU);
6293
6294 case Decl::NamespaceAlias:
6295 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6296
6297 case Decl::Enum:
6298 case Decl::Record:
6299 case Decl::CXXRecord:
6300 case Decl::ClassTemplateSpecialization:
6301 case Decl::ClassTemplatePartialSpecialization:
6302 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6303 return MakeCXCursor(Def, TU);
6304 return clang_getNullCursor();
6305
6306 case Decl::Function:
6307 case Decl::CXXMethod:
6308 case Decl::CXXConstructor:
6309 case Decl::CXXDestructor:
6310 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006311 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006312 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006313 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006314 return clang_getNullCursor();
6315 }
6316
Larisse Voufo39a1e502013-08-06 01:03:05 +00006317 case Decl::Var:
6318 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006319 case Decl::VarTemplatePartialSpecialization:
6320 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006321 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006322 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006323 return MakeCXCursor(Def, TU);
6324 return clang_getNullCursor();
6325 }
6326
6327 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006328 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006329 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6330 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6331 return clang_getNullCursor();
6332 }
6333
6334 case Decl::ClassTemplate: {
6335 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6336 ->getDefinition())
6337 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6338 TU);
6339 return clang_getNullCursor();
6340 }
6341
Larisse Voufo39a1e502013-08-06 01:03:05 +00006342 case Decl::VarTemplate: {
6343 if (VarDecl *Def =
6344 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6345 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6346 return clang_getNullCursor();
6347 }
6348
Guy Benyei11169dd2012-12-18 14:30:41 +00006349 case Decl::Using:
6350 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6351 D->getLocation(), TU);
6352
6353 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006354 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006355 return clang_getCursorDefinition(
6356 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6357 TU));
6358
6359 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006360 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006361 if (Method->isThisDeclarationADefinition())
6362 return C;
6363
6364 // Dig out the method definition in the associated
6365 // @implementation, if we have it.
6366 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006367 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006368 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6369 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6370 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6371 Method->isInstanceMethod()))
6372 if (Def->isThisDeclarationADefinition())
6373 return MakeCXCursor(Def, TU);
6374
6375 return clang_getNullCursor();
6376 }
6377
6378 case Decl::ObjCCategory:
6379 if (ObjCCategoryImplDecl *Impl
6380 = cast<ObjCCategoryDecl>(D)->getImplementation())
6381 return MakeCXCursor(Impl, TU);
6382 return clang_getNullCursor();
6383
6384 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006385 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006386 return MakeCXCursor(Def, TU);
6387 return clang_getNullCursor();
6388
6389 case Decl::ObjCInterface: {
6390 // There are two notions of a "definition" for an Objective-C
6391 // class: the interface and its implementation. When we resolved a
6392 // reference to an Objective-C class, produce the @interface as
6393 // the definition; when we were provided with the interface,
6394 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006395 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006396 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006397 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006398 return MakeCXCursor(Def, TU);
6399 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6400 return MakeCXCursor(Impl, TU);
6401 return clang_getNullCursor();
6402 }
6403
6404 case Decl::ObjCProperty:
6405 // FIXME: We don't really know where to find the
6406 // ObjCPropertyImplDecls that implement this property.
6407 return clang_getNullCursor();
6408
6409 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006410 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006411 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006412 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006413 return MakeCXCursor(Def, TU);
6414
6415 return clang_getNullCursor();
6416
6417 case Decl::Friend:
6418 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6419 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6420 return clang_getNullCursor();
6421
6422 case Decl::FriendTemplate:
6423 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6424 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6425 return clang_getNullCursor();
6426 }
6427
6428 return clang_getNullCursor();
6429}
6430
6431unsigned clang_isCursorDefinition(CXCursor C) {
6432 if (!clang_isDeclaration(C.kind))
6433 return 0;
6434
6435 return clang_getCursorDefinition(C) == C;
6436}
6437
6438CXCursor clang_getCanonicalCursor(CXCursor C) {
6439 if (!clang_isDeclaration(C.kind))
6440 return C;
6441
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006442 if (const Decl *D = getCursorDecl(C)) {
6443 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006444 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6445 return MakeCXCursor(CatD, getCursorTU(C));
6446
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006447 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6448 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006449 return MakeCXCursor(IFD, getCursorTU(C));
6450
6451 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6452 }
6453
6454 return C;
6455}
6456
6457int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6458 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6459}
6460
6461unsigned clang_getNumOverloadedDecls(CXCursor C) {
6462 if (C.kind != CXCursor_OverloadedDeclRef)
6463 return 0;
6464
6465 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006466 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006467 return E->getNumDecls();
6468
6469 if (OverloadedTemplateStorage *S
6470 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6471 return S->size();
6472
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006473 const Decl *D = Storage.get<const Decl *>();
6474 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006475 return Using->shadow_size();
6476
6477 return 0;
6478}
6479
6480CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6481 if (cursor.kind != CXCursor_OverloadedDeclRef)
6482 return clang_getNullCursor();
6483
6484 if (index >= clang_getNumOverloadedDecls(cursor))
6485 return clang_getNullCursor();
6486
6487 CXTranslationUnit TU = getCursorTU(cursor);
6488 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006489 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006490 return MakeCXCursor(E->decls_begin()[index], TU);
6491
6492 if (OverloadedTemplateStorage *S
6493 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6494 return MakeCXCursor(S->begin()[index], TU);
6495
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006496 const Decl *D = Storage.get<const Decl *>();
6497 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006498 // FIXME: This is, unfortunately, linear time.
6499 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6500 std::advance(Pos, index);
6501 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6502 }
6503
6504 return clang_getNullCursor();
6505}
6506
6507void clang_getDefinitionSpellingAndExtent(CXCursor C,
6508 const char **startBuf,
6509 const char **endBuf,
6510 unsigned *startLine,
6511 unsigned *startColumn,
6512 unsigned *endLine,
6513 unsigned *endColumn) {
6514 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006515 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006516 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6517
6518 SourceManager &SM = FD->getASTContext().getSourceManager();
6519 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6520 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6521 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6522 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6523 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6524 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6525}
6526
6527
6528CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6529 unsigned PieceIndex) {
6530 RefNamePieces Pieces;
6531
6532 switch (C.kind) {
6533 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006534 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006535 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6536 E->getQualifierLoc().getSourceRange());
6537 break;
6538
6539 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006540 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6541 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6542 Pieces =
6543 buildPieces(NameFlags, false, E->getNameInfo(),
6544 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6545 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006546 break;
6547
6548 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006549 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006550 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006551 const Expr *Callee = OCE->getCallee();
6552 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006553 Callee = ICE->getSubExpr();
6554
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006555 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006556 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6557 DRE->getQualifierLoc().getSourceRange());
6558 }
6559 break;
6560
6561 default:
6562 break;
6563 }
6564
6565 if (Pieces.empty()) {
6566 if (PieceIndex == 0)
6567 return clang_getCursorExtent(C);
6568 } else if (PieceIndex < Pieces.size()) {
6569 SourceRange R = Pieces[PieceIndex];
6570 if (R.isValid())
6571 return cxloc::translateSourceRange(getCursorContext(C), R);
6572 }
6573
6574 return clang_getNullRange();
6575}
6576
6577void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006578 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6579 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006580}
6581
6582void clang_executeOnThread(void (*fn)(void*), void *user_data,
6583 unsigned stack_size) {
6584 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6585}
6586
Guy Benyei11169dd2012-12-18 14:30:41 +00006587//===----------------------------------------------------------------------===//
6588// Token-based Operations.
6589//===----------------------------------------------------------------------===//
6590
6591/* CXToken layout:
6592 * int_data[0]: a CXTokenKind
6593 * int_data[1]: starting token location
6594 * int_data[2]: token length
6595 * int_data[3]: reserved
6596 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6597 * otherwise unused.
6598 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006599CXTokenKind clang_getTokenKind(CXToken CXTok) {
6600 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6601}
6602
6603CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6604 switch (clang_getTokenKind(CXTok)) {
6605 case CXToken_Identifier:
6606 case CXToken_Keyword:
6607 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006608 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006609 ->getNameStart());
6610
6611 case CXToken_Literal: {
6612 // We have stashed the starting pointer in the ptr_data field. Use it.
6613 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006614 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006615 }
6616
6617 case CXToken_Punctuation:
6618 case CXToken_Comment:
6619 break;
6620 }
6621
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006622 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006623 LOG_BAD_TU(TU);
6624 return cxstring::createEmpty();
6625 }
6626
Guy Benyei11169dd2012-12-18 14:30:41 +00006627 // We have to find the starting buffer pointer the hard way, by
6628 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006629 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006630 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006631 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006632
6633 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6634 std::pair<FileID, unsigned> LocInfo
6635 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6636 bool Invalid = false;
6637 StringRef Buffer
6638 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6639 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006640 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006641
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006642 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006643}
6644
6645CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006646 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006647 LOG_BAD_TU(TU);
6648 return clang_getNullLocation();
6649 }
6650
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006651 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006652 if (!CXXUnit)
6653 return clang_getNullLocation();
6654
6655 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6656 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6657}
6658
6659CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006660 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006661 LOG_BAD_TU(TU);
6662 return clang_getNullRange();
6663 }
6664
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006665 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006666 if (!CXXUnit)
6667 return clang_getNullRange();
6668
6669 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6670 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6671}
6672
6673static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6674 SmallVectorImpl<CXToken> &CXTokens) {
6675 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6676 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006677 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006678 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006679 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006680
6681 // Cannot tokenize across files.
6682 if (BeginLocInfo.first != EndLocInfo.first)
6683 return;
6684
6685 // Create a lexer
6686 bool Invalid = false;
6687 StringRef Buffer
6688 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6689 if (Invalid)
6690 return;
6691
6692 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6693 CXXUnit->getASTContext().getLangOpts(),
6694 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6695 Lex.SetCommentRetentionState(true);
6696
6697 // Lex tokens until we hit the end of the range.
6698 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6699 Token Tok;
6700 bool previousWasAt = false;
6701 do {
6702 // Lex the next token
6703 Lex.LexFromRawLexer(Tok);
6704 if (Tok.is(tok::eof))
6705 break;
6706
6707 // Initialize the CXToken.
6708 CXToken CXTok;
6709
6710 // - Common fields
6711 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6712 CXTok.int_data[2] = Tok.getLength();
6713 CXTok.int_data[3] = 0;
6714
6715 // - Kind-specific fields
6716 if (Tok.isLiteral()) {
6717 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006718 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006719 } else if (Tok.is(tok::raw_identifier)) {
6720 // Lookup the identifier to determine whether we have a keyword.
6721 IdentifierInfo *II
6722 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6723
6724 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6725 CXTok.int_data[0] = CXToken_Keyword;
6726 }
6727 else {
6728 CXTok.int_data[0] = Tok.is(tok::identifier)
6729 ? CXToken_Identifier
6730 : CXToken_Keyword;
6731 }
6732 CXTok.ptr_data = II;
6733 } else if (Tok.is(tok::comment)) {
6734 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006735 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006736 } else {
6737 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006738 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006739 }
6740 CXTokens.push_back(CXTok);
6741 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006742 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006743}
6744
Ivan Donchevskii3957e482018-06-13 12:37:08 +00006745CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6746 LOG_FUNC_SECTION {
6747 *Log << TU << ' ' << Location;
6748 }
6749
6750 if (isNotUsableTU(TU)) {
6751 LOG_BAD_TU(TU);
6752 return NULL;
6753 }
6754
6755 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6756 if (!CXXUnit)
6757 return NULL;
6758
6759 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6760 if (Begin.isInvalid())
6761 return NULL;
6762 SourceManager &SM = CXXUnit->getSourceManager();
6763 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6764 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6765
6766 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6767
6768 SmallVector<CXToken, 32> CXTokens;
6769 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6770
6771 if (CXTokens.empty())
6772 return NULL;
6773
6774 CXTokens.resize(1);
6775 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6776
6777 memmove(Token, CXTokens.data(), sizeof(CXToken));
6778 return Token;
6779}
6780
Guy Benyei11169dd2012-12-18 14:30:41 +00006781void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6782 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006783 LOG_FUNC_SECTION {
6784 *Log << TU << ' ' << Range;
6785 }
6786
Guy Benyei11169dd2012-12-18 14:30:41 +00006787 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006788 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006789 if (NumTokens)
6790 *NumTokens = 0;
6791
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006792 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006793 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006794 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006795 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006796
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006797 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006798 if (!CXXUnit || !Tokens || !NumTokens)
6799 return;
6800
6801 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6802
6803 SourceRange R = cxloc::translateCXSourceRange(Range);
6804 if (R.isInvalid())
6805 return;
6806
6807 SmallVector<CXToken, 32> CXTokens;
6808 getTokens(CXXUnit, R, CXTokens);
6809
6810 if (CXTokens.empty())
6811 return;
6812
Serge Pavlov52525732018-02-21 02:02:39 +00006813 *Tokens = static_cast<CXToken *>(
6814 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006815 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6816 *NumTokens = CXTokens.size();
6817}
6818
6819void clang_disposeTokens(CXTranslationUnit TU,
6820 CXToken *Tokens, unsigned NumTokens) {
6821 free(Tokens);
6822}
6823
Guy Benyei11169dd2012-12-18 14:30:41 +00006824//===----------------------------------------------------------------------===//
6825// Token annotation APIs.
6826//===----------------------------------------------------------------------===//
6827
Guy Benyei11169dd2012-12-18 14:30:41 +00006828static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6829 CXCursor parent,
6830 CXClientData client_data);
6831static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6832 CXClientData client_data);
6833
6834namespace {
6835class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006836 CXToken *Tokens;
6837 CXCursor *Cursors;
6838 unsigned NumTokens;
6839 unsigned TokIdx;
6840 unsigned PreprocessingTokIdx;
6841 CursorVisitor AnnotateVis;
6842 SourceManager &SrcMgr;
6843 bool HasContextSensitiveKeywords;
6844
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006845 struct PostChildrenAction {
6846 CXCursor cursor;
6847 enum Action { Invalid, Ignore, Postpone } action;
6848 };
6849 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
6850
Guy Benyei11169dd2012-12-18 14:30:41 +00006851 struct PostChildrenInfo {
6852 CXCursor Cursor;
6853 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006854 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006855 unsigned BeforeChildrenTokenIdx;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006856 PostChildrenActions ChildActions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006857 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006858 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006859
6860 CXToken &getTok(unsigned Idx) {
6861 assert(Idx < NumTokens);
6862 return Tokens[Idx];
6863 }
6864 const CXToken &getTok(unsigned Idx) const {
6865 assert(Idx < NumTokens);
6866 return Tokens[Idx];
6867 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006868 bool MoreTokens() const { return TokIdx < NumTokens; }
6869 unsigned NextToken() const { return TokIdx; }
6870 void AdvanceToken() { ++TokIdx; }
6871 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006872 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006873 }
6874 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006875 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006876 }
6877 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006878 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006879 }
6880
6881 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006882 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006883 SourceRange);
6884
6885public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006886 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006887 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006888 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006889 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006890 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006891 AnnotateTokensVisitor, this,
6892 /*VisitPreprocessorLast=*/true,
6893 /*VisitIncludedEntities=*/false,
6894 RegionOfInterest,
6895 /*VisitDeclsOnly=*/false,
6896 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006897 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006898 HasContextSensitiveKeywords(false) { }
6899
6900 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6901 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006902 bool IsIgnoredChildCursor(CXCursor cursor) const;
6903 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
6904
Guy Benyei11169dd2012-12-18 14:30:41 +00006905 bool postVisitChildren(CXCursor cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006906 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
6907 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
6908
Guy Benyei11169dd2012-12-18 14:30:41 +00006909 void AnnotateTokens();
6910
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006911 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00006912 /// context-sensitive keywords.
6913 bool hasContextSensitiveKeywords() const {
6914 return HasContextSensitiveKeywords;
6915 }
6916
6917 ~AnnotateTokensWorker() {
6918 assert(PostChildrenInfos.empty());
6919 }
6920};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006921}
Guy Benyei11169dd2012-12-18 14:30:41 +00006922
6923void AnnotateTokensWorker::AnnotateTokens() {
6924 // Walk the AST within the region of interest, annotating tokens
6925 // along the way.
6926 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006927}
Guy Benyei11169dd2012-12-18 14:30:41 +00006928
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006929bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
6930 if (PostChildrenInfos.empty())
6931 return false;
6932
6933 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
6934 if (ChildAction.cursor == cursor &&
6935 ChildAction.action == PostChildrenAction::Ignore) {
6936 return true;
6937 }
6938 }
6939
6940 return false;
6941}
6942
6943const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
6944 if (!clang_isExpression(Cursor.kind))
6945 return nullptr;
6946
6947 const Expr *E = getCursorExpr(Cursor);
6948 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
6949 const OverloadedOperatorKind Kind = OCE->getOperator();
6950 if (Kind == OO_Call || Kind == OO_Subscript)
6951 return OCE;
6952 }
6953
6954 return nullptr;
6955}
6956
6957AnnotateTokensWorker::PostChildrenActions
6958AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
6959 PostChildrenActions actions;
6960
6961 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
6962 // visited before the arguments to the operator call. For the Call and
6963 // Subscript operator the range of this DeclRefExpr includes the whole call
6964 // expression, so that all tokens in that range would be mapped to the
6965 // operator function, including the tokens of the arguments. To avoid that,
6966 // ensure to visit this DeclRefExpr as last node.
6967 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
6968 const Expr *Callee = OCE->getCallee();
6969 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
6970 const Expr *SubExpr = ICE->getSubExpr();
6971 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
Fangrui Songcabb36d2018-11-20 08:00:00 +00006972 const Decl *parentDecl = getCursorDecl(Cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006973 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
6974
6975 // Visit the DeclRefExpr as last.
6976 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
6977 actions.push_back({cxChild, PostChildrenAction::Postpone});
6978
6979 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
6980 // wide range as the DeclRefExpr. We can skip visiting this entirely.
6981 cxChild = MakeCXCursor(ICE, parentDecl, TU);
6982 actions.push_back({cxChild, PostChildrenAction::Ignore});
6983 }
6984 }
6985 }
6986
6987 return actions;
6988}
6989
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006990static inline void updateCursorAnnotation(CXCursor &Cursor,
6991 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006992 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006993 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006994 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006995}
6996
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006997/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00006998//// between the cursor location and the source range is the same as
6999/// \arg compResult.
7000///
7001/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
7002/// Pass RangeOverlap to annotate tokens inside a range.
7003void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
7004 RangeComparisonResult compResult,
7005 SourceRange range) {
7006 while (MoreTokens()) {
7007 const unsigned I = NextToken();
7008 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007009 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
7010 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00007011
7012 SourceLocation TokLoc = GetTokenLoc(I);
7013 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007014 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007015 AdvanceToken();
7016 continue;
7017 }
7018 break;
7019 }
7020}
7021
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007022/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007023/// \returns true if it advanced beyond all macro tokens, false otherwise.
7024bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00007025 CXCursor updateC,
7026 RangeComparisonResult compResult,
7027 SourceRange range) {
7028 assert(MoreTokens());
7029 assert(isFunctionMacroToken(NextToken()) &&
7030 "Should be called only for macro arg tokens");
7031
7032 // This works differently than annotateAndAdvanceTokens; because expanded
7033 // macro arguments can have arbitrary translation-unit source order, we do not
7034 // advance the token index one by one until a token fails the range test.
7035 // We only advance once past all of the macro arg tokens if all of them
7036 // pass the range test. If one of them fails we keep the token index pointing
7037 // at the start of the macro arg tokens so that the failing token will be
7038 // annotated by a subsequent annotation try.
7039
7040 bool atLeastOneCompFail = false;
7041
7042 unsigned I = NextToken();
7043 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7044 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7045 if (TokLoc.isFileID())
7046 continue; // not macro arg token, it's parens or comma.
7047 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7048 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7049 Cursors[I] = updateC;
7050 } else
7051 atLeastOneCompFail = true;
7052 }
7053
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007054 if (atLeastOneCompFail)
7055 return false;
7056
7057 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7058 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00007059}
7060
7061enum CXChildVisitResult
7062AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007063 SourceRange cursorRange = getRawCursorExtent(cursor);
7064 if (cursorRange.isInvalid())
7065 return CXChildVisit_Recurse;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007066
7067 if (IsIgnoredChildCursor(cursor))
7068 return CXChildVisit_Continue;
7069
Guy Benyei11169dd2012-12-18 14:30:41 +00007070 if (!HasContextSensitiveKeywords) {
7071 // Objective-C properties can have context-sensitive keywords.
7072 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007073 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007074 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7075 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7076 }
7077 // Objective-C methods can have context-sensitive keywords.
7078 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7079 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007080 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007081 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7082 if (Method->getObjCDeclQualifier())
7083 HasContextSensitiveKeywords = true;
7084 else {
David Majnemer59f77922016-06-24 04:05:48 +00007085 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00007086 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007087 HasContextSensitiveKeywords = true;
7088 break;
7089 }
7090 }
7091 }
7092 }
7093 }
7094 // C++ methods can have context-sensitive keywords.
7095 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007096 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007097 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7098 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7099 HasContextSensitiveKeywords = true;
7100 }
7101 }
7102 // C++ classes can have context-sensitive keywords.
7103 else if (cursor.kind == CXCursor_StructDecl ||
7104 cursor.kind == CXCursor_ClassDecl ||
7105 cursor.kind == CXCursor_ClassTemplate ||
7106 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007107 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007108 if (D->hasAttr<FinalAttr>())
7109 HasContextSensitiveKeywords = true;
7110 }
7111 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00007112
7113 // Don't override a property annotation with its getter/setter method.
7114 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7115 parent.kind == CXCursor_ObjCPropertyDecl)
7116 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007117
7118 if (clang_isPreprocessing(cursor.kind)) {
7119 // Items in the preprocessing record are kept separate from items in
7120 // declarations, so we keep a separate token index.
7121 unsigned SavedTokIdx = TokIdx;
7122 TokIdx = PreprocessingTokIdx;
7123
7124 // Skip tokens up until we catch up to the beginning of the preprocessing
7125 // entry.
7126 while (MoreTokens()) {
7127 const unsigned I = NextToken();
7128 SourceLocation TokLoc = GetTokenLoc(I);
7129 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7130 case RangeBefore:
7131 AdvanceToken();
7132 continue;
7133 case RangeAfter:
7134 case RangeOverlap:
7135 break;
7136 }
7137 break;
7138 }
7139
7140 // Look at all of the tokens within this range.
7141 while (MoreTokens()) {
7142 const unsigned I = NextToken();
7143 SourceLocation TokLoc = GetTokenLoc(I);
7144 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7145 case RangeBefore:
7146 llvm_unreachable("Infeasible");
7147 case RangeAfter:
7148 break;
7149 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007150 // For macro expansions, just note where the beginning of the macro
7151 // expansion occurs.
7152 if (cursor.kind == CXCursor_MacroExpansion) {
7153 if (TokLoc == cursorRange.getBegin())
7154 Cursors[I] = cursor;
7155 AdvanceToken();
7156 break;
7157 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007158 // We may have already annotated macro names inside macro definitions.
7159 if (Cursors[I].kind != CXCursor_MacroExpansion)
7160 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007161 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007162 continue;
7163 }
7164 break;
7165 }
7166
7167 // Save the preprocessing token index; restore the non-preprocessing
7168 // token index.
7169 PreprocessingTokIdx = TokIdx;
7170 TokIdx = SavedTokIdx;
7171 return CXChildVisit_Recurse;
7172 }
7173
7174 if (cursorRange.isInvalid())
7175 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007176
7177 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007178 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007179 const enum CXCursorKind K = clang_getCursorKind(parent);
7180 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007181 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7182 // Attributes are annotated out-of-order, skip tokens until we reach it.
7183 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007184 ? clang_getNullCursor() : parent;
7185
7186 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7187
7188 // Avoid having the cursor of an expression "overwrite" the annotation of the
7189 // variable declaration that it belongs to.
7190 // This can happen for C++ constructor expressions whose range generally
7191 // include the variable declaration, e.g.:
7192 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007193 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00007194 const Expr *E = getCursorExpr(cursor);
Fangrui Songcabb36d2018-11-20 08:00:00 +00007195 if (const Decl *D = getCursorDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007196 const unsigned I = NextToken();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007197 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7198 E->getBeginLoc() == D->getLocation() &&
7199 E->getBeginLoc() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007200 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007201 AdvanceToken();
7202 }
7203 }
7204 }
7205
7206 // Before recursing into the children keep some state that we are going
7207 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7208 // extra work after the child nodes are visited.
7209 // Note that we don't call VisitChildren here to avoid traversing statements
7210 // code-recursively which can blow the stack.
7211
7212 PostChildrenInfo Info;
7213 Info.Cursor = cursor;
7214 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007215 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007216 Info.BeforeChildrenTokenIdx = NextToken();
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007217 Info.ChildActions = DetermineChildActions(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007218 PostChildrenInfos.push_back(Info);
7219
7220 return CXChildVisit_Recurse;
7221}
7222
7223bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7224 if (PostChildrenInfos.empty())
7225 return false;
7226 const PostChildrenInfo &Info = PostChildrenInfos.back();
7227 if (!clang_equalCursors(Info.Cursor, cursor))
7228 return false;
7229
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007230 HandlePostPonedChildCursors(Info);
7231
Guy Benyei11169dd2012-12-18 14:30:41 +00007232 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7233 const unsigned AfterChildren = NextToken();
7234 SourceRange cursorRange = Info.CursorRange;
7235
7236 // Scan the tokens that are at the end of the cursor, but are not captured
7237 // but the child cursors.
7238 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7239
7240 // Scan the tokens that are at the beginning of the cursor, but are not
7241 // capture by the child cursors.
7242 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7243 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7244 break;
7245
7246 Cursors[I] = cursor;
7247 }
7248
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007249 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7250 // encountered the attribute cursor.
7251 if (clang_isAttribute(cursor.kind))
7252 TokIdx = Info.BeforeReachingCursorIdx;
7253
Guy Benyei11169dd2012-12-18 14:30:41 +00007254 PostChildrenInfos.pop_back();
7255 return false;
7256}
7257
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007258void AnnotateTokensWorker::HandlePostPonedChildCursors(
7259 const PostChildrenInfo &Info) {
7260 for (const auto &ChildAction : Info.ChildActions) {
7261 if (ChildAction.action == PostChildrenAction::Postpone) {
7262 HandlePostPonedChildCursor(ChildAction.cursor,
7263 Info.BeforeChildrenTokenIdx);
7264 }
7265 }
7266}
7267
7268void AnnotateTokensWorker::HandlePostPonedChildCursor(
7269 CXCursor Cursor, unsigned StartTokenIndex) {
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007270 unsigned I = StartTokenIndex;
7271
7272 // The bracket tokens of a Call or Subscript operator are mapped to
7273 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7274 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7275 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
Nikolai Kosjar2a647e72019-05-08 13:19:29 +00007276 const CXSourceRange CXRefNameRange = clang_getCursorReferenceNameRange(
7277 Cursor, CXNameRange_WantQualifier, RefNameRangeNr);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007278 if (clang_Range_isNull(CXRefNameRange))
7279 break; // All ranges handled.
7280
7281 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7282 while (I < NumTokens) {
7283 const SourceLocation TokenLocation = GetTokenLoc(I);
7284 if (!TokenLocation.isValid())
7285 break;
7286
7287 // Adapt the end range, because LocationCompare() reports
7288 // RangeOverlap even for the not-inclusive end location.
7289 const SourceLocation fixedEnd =
7290 RefNameRange.getEnd().getLocWithOffset(-1);
7291 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7292
7293 const RangeComparisonResult ComparisonResult =
7294 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7295
7296 if (ComparisonResult == RangeOverlap) {
7297 Cursors[I++] = Cursor;
7298 } else if (ComparisonResult == RangeBefore) {
7299 ++I; // Not relevant token, check next one.
7300 } else if (ComparisonResult == RangeAfter) {
7301 break; // All tokens updated for current range, check next.
7302 }
7303 }
7304 }
7305}
7306
Guy Benyei11169dd2012-12-18 14:30:41 +00007307static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7308 CXCursor parent,
7309 CXClientData client_data) {
7310 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7311}
7312
7313static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7314 CXClientData client_data) {
7315 return static_cast<AnnotateTokensWorker*>(client_data)->
7316 postVisitChildren(cursor);
7317}
7318
7319namespace {
7320
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007321/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007322/// and mark tokens that are macro arguments. This info is used by the
7323/// AnnotateTokensWorker.
7324class MarkMacroArgTokensVisitor {
7325 SourceManager &SM;
7326 CXToken *Tokens;
7327 unsigned NumTokens;
7328 unsigned CurIdx;
7329
7330public:
7331 MarkMacroArgTokensVisitor(SourceManager &SM,
7332 CXToken *tokens, unsigned numTokens)
7333 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7334
7335 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7336 if (cursor.kind != CXCursor_MacroExpansion)
7337 return CXChildVisit_Continue;
7338
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007339 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007340 if (macroRange.getBegin() == macroRange.getEnd())
7341 return CXChildVisit_Continue; // it's not a function macro.
7342
7343 for (; CurIdx < NumTokens; ++CurIdx) {
7344 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7345 macroRange.getBegin()))
7346 break;
7347 }
7348
7349 if (CurIdx == NumTokens)
7350 return CXChildVisit_Break;
7351
7352 for (; CurIdx < NumTokens; ++CurIdx) {
7353 SourceLocation tokLoc = getTokenLoc(CurIdx);
7354 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7355 break;
7356
7357 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7358 }
7359
7360 if (CurIdx == NumTokens)
7361 return CXChildVisit_Break;
7362
7363 return CXChildVisit_Continue;
7364 }
7365
7366private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007367 CXToken &getTok(unsigned Idx) {
7368 assert(Idx < NumTokens);
7369 return Tokens[Idx];
7370 }
7371 const CXToken &getTok(unsigned Idx) const {
7372 assert(Idx < NumTokens);
7373 return Tokens[Idx];
7374 }
7375
Guy Benyei11169dd2012-12-18 14:30:41 +00007376 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007377 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007378 }
7379
7380 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7381 // The third field is reserved and currently not used. Use it here
7382 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007383 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007384 }
7385};
7386
7387} // end anonymous namespace
7388
7389static CXChildVisitResult
7390MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7391 CXClientData client_data) {
7392 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7393 parent);
7394}
7395
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007396/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007397/// \returns true if lexing was finished, false otherwise.
7398static bool lexNext(Lexer &Lex, Token &Tok,
7399 unsigned &NextIdx, unsigned NumTokens) {
7400 if (NextIdx >= NumTokens)
7401 return true;
7402
7403 ++NextIdx;
7404 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007405 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007406}
7407
Guy Benyei11169dd2012-12-18 14:30:41 +00007408static void annotatePreprocessorTokens(CXTranslationUnit TU,
7409 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007410 CXCursor *Cursors,
7411 CXToken *Tokens,
7412 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007413 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007414
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007415 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007416 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7417 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007418 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007419 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007420 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007421
7422 if (BeginLocInfo.first != EndLocInfo.first)
7423 return;
7424
7425 StringRef Buffer;
7426 bool Invalid = false;
7427 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7428 if (Buffer.empty() || Invalid)
7429 return;
7430
7431 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7432 CXXUnit->getASTContext().getLangOpts(),
7433 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7434 Buffer.end());
7435 Lex.SetCommentRetentionState(true);
7436
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007437 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007438 // Lex tokens in raw mode until we hit the end of the range, to avoid
7439 // entering #includes or expanding macros.
7440 while (true) {
7441 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007442 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7443 break;
7444 unsigned TokIdx = NextIdx-1;
7445 assert(Tok.getLocation() ==
7446 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007447
7448 reprocess:
7449 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007450 // We have found a preprocessing directive. Annotate the tokens
7451 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007452 //
7453 // FIXME: Some simple tests here could identify macro definitions and
7454 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007455
7456 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007457 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7458 break;
7459
Craig Topper69186e72014-06-08 08:38:04 +00007460 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007461 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007462 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7463 break;
7464
7465 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007466 IdentifierInfo &II =
7467 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007468 SourceLocation MappedTokLoc =
7469 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7470 MI = getMacroInfo(II, MappedTokLoc, TU);
7471 }
7472 }
7473
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007474 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007475 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007476 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7477 finished = true;
7478 break;
7479 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007480 // If we are in a macro definition, check if the token was ever a
7481 // macro name and annotate it if that's the case.
7482 if (MI) {
7483 SourceLocation SaveLoc = Tok.getLocation();
7484 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007485 MacroDefinitionRecord *MacroDef =
7486 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007487 Tok.setLocation(SaveLoc);
7488 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007489 Cursors[NextIdx - 1] =
7490 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007491 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007492 } while (!Tok.isAtStartOfLine());
7493
7494 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7495 assert(TokIdx <= LastIdx);
7496 SourceLocation EndLoc =
7497 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7498 CXCursor Cursor =
7499 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7500
7501 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007502 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007503
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007504 if (finished)
7505 break;
7506 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007507 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007508 }
7509}
7510
7511// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007512static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7513 CXToken *Tokens, unsigned NumTokens,
7514 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007515 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007516 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7517 setThreadBackgroundPriority();
7518
7519 // Determine the region of interest, which contains all of the tokens.
7520 SourceRange RegionOfInterest;
7521 RegionOfInterest.setBegin(
7522 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7523 RegionOfInterest.setEnd(
7524 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7525 Tokens[NumTokens-1])));
7526
Guy Benyei11169dd2012-12-18 14:30:41 +00007527 // Relex the tokens within the source range to look for preprocessing
7528 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007529 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007530
7531 // If begin location points inside a macro argument, set it to the expansion
7532 // location so we can have the full context when annotating semantically.
7533 {
7534 SourceManager &SM = CXXUnit->getSourceManager();
7535 SourceLocation Loc =
7536 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7537 if (Loc.isMacroID())
7538 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7539 }
7540
Guy Benyei11169dd2012-12-18 14:30:41 +00007541 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7542 // Search and mark tokens that are macro argument expansions.
7543 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7544 Tokens, NumTokens);
7545 CursorVisitor MacroArgMarker(TU,
7546 MarkMacroArgTokensVisitorDelegate, &Visitor,
7547 /*VisitPreprocessorLast=*/true,
7548 /*VisitIncludedEntities=*/false,
7549 RegionOfInterest);
7550 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7551 }
7552
7553 // Annotate all of the source locations in the region of interest that map to
7554 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007555 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007556
7557 // FIXME: We use a ridiculous stack size here because the data-recursion
7558 // algorithm uses a large stack frame than the non-data recursive version,
7559 // and AnnotationTokensWorker currently transforms the data-recursion
7560 // algorithm back into a traditional recursion by explicitly calling
7561 // VisitChildren(). We will need to remove this explicit recursive call.
7562 W.AnnotateTokens();
7563
7564 // If we ran into any entities that involve context-sensitive keywords,
7565 // take another pass through the tokens to mark them as such.
7566 if (W.hasContextSensitiveKeywords()) {
7567 for (unsigned I = 0; I != NumTokens; ++I) {
7568 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7569 continue;
7570
7571 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7572 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007573 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007574 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7575 if (Property->getPropertyAttributesAsWritten() != 0 &&
7576 llvm::StringSwitch<bool>(II->getName())
7577 .Case("readonly", true)
7578 .Case("assign", true)
7579 .Case("unsafe_unretained", true)
7580 .Case("readwrite", true)
7581 .Case("retain", true)
7582 .Case("copy", true)
7583 .Case("nonatomic", true)
7584 .Case("atomic", true)
7585 .Case("getter", true)
7586 .Case("setter", true)
7587 .Case("strong", true)
7588 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007589 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007590 .Default(false))
7591 Tokens[I].int_data[0] = CXToken_Keyword;
7592 }
7593 continue;
7594 }
7595
7596 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7597 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7598 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7599 if (llvm::StringSwitch<bool>(II->getName())
7600 .Case("in", true)
7601 .Case("out", true)
7602 .Case("inout", true)
7603 .Case("oneway", true)
7604 .Case("bycopy", true)
7605 .Case("byref", true)
7606 .Default(false))
7607 Tokens[I].int_data[0] = CXToken_Keyword;
7608 continue;
7609 }
7610
7611 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7612 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7613 Tokens[I].int_data[0] = CXToken_Keyword;
7614 continue;
7615 }
7616 }
7617 }
7618}
7619
Guy Benyei11169dd2012-12-18 14:30:41 +00007620void clang_annotateTokens(CXTranslationUnit TU,
7621 CXToken *Tokens, unsigned NumTokens,
7622 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007623 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007624 LOG_BAD_TU(TU);
7625 return;
7626 }
7627 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007628 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007629 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007630 }
7631
7632 LOG_FUNC_SECTION {
7633 *Log << TU << ' ';
7634 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7635 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7636 *Log << clang_getRange(bloc, eloc);
7637 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007638
7639 // Any token we don't specifically annotate will have a NULL cursor.
7640 CXCursor C = clang_getNullCursor();
7641 for (unsigned I = 0; I != NumTokens; ++I)
7642 Cursors[I] = C;
7643
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007644 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007645 if (!CXXUnit)
7646 return;
7647
7648 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007649
7650 auto AnnotateTokensImpl = [=]() {
7651 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7652 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007653 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007654 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007655 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7656 }
7657}
7658
Guy Benyei11169dd2012-12-18 14:30:41 +00007659//===----------------------------------------------------------------------===//
7660// Operations for querying linkage of a cursor.
7661//===----------------------------------------------------------------------===//
7662
Guy Benyei11169dd2012-12-18 14:30:41 +00007663CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7664 if (!clang_isDeclaration(cursor.kind))
7665 return CXLinkage_Invalid;
7666
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007667 const Decl *D = cxcursor::getCursorDecl(cursor);
7668 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007669 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007670 case NoLinkage:
7671 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007672 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007673 case InternalLinkage: return CXLinkage_Internal;
7674 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007675 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007676 case ExternalLinkage: return CXLinkage_External;
7677 };
7678
7679 return CXLinkage_Invalid;
7680}
Guy Benyei11169dd2012-12-18 14:30:41 +00007681
7682//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007683// Operations for querying visibility of a cursor.
7684//===----------------------------------------------------------------------===//
7685
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007686CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7687 if (!clang_isDeclaration(cursor.kind))
7688 return CXVisibility_Invalid;
7689
7690 const Decl *D = cxcursor::getCursorDecl(cursor);
7691 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7692 switch (ND->getVisibility()) {
7693 case HiddenVisibility: return CXVisibility_Hidden;
7694 case ProtectedVisibility: return CXVisibility_Protected;
7695 case DefaultVisibility: return CXVisibility_Default;
7696 };
7697
7698 return CXVisibility_Invalid;
7699}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007700
7701//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007702// Operations for querying language of a cursor.
7703//===----------------------------------------------------------------------===//
7704
7705static CXLanguageKind getDeclLanguage(const Decl *D) {
7706 if (!D)
7707 return CXLanguage_C;
7708
7709 switch (D->getKind()) {
7710 default:
7711 break;
7712 case Decl::ImplicitParam:
7713 case Decl::ObjCAtDefsField:
7714 case Decl::ObjCCategory:
7715 case Decl::ObjCCategoryImpl:
7716 case Decl::ObjCCompatibleAlias:
7717 case Decl::ObjCImplementation:
7718 case Decl::ObjCInterface:
7719 case Decl::ObjCIvar:
7720 case Decl::ObjCMethod:
7721 case Decl::ObjCProperty:
7722 case Decl::ObjCPropertyImpl:
7723 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007724 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007725 return CXLanguage_ObjC;
7726 case Decl::CXXConstructor:
7727 case Decl::CXXConversion:
7728 case Decl::CXXDestructor:
7729 case Decl::CXXMethod:
7730 case Decl::CXXRecord:
7731 case Decl::ClassTemplate:
7732 case Decl::ClassTemplatePartialSpecialization:
7733 case Decl::ClassTemplateSpecialization:
7734 case Decl::Friend:
7735 case Decl::FriendTemplate:
7736 case Decl::FunctionTemplate:
7737 case Decl::LinkageSpec:
7738 case Decl::Namespace:
7739 case Decl::NamespaceAlias:
7740 case Decl::NonTypeTemplateParm:
7741 case Decl::StaticAssert:
7742 case Decl::TemplateTemplateParm:
7743 case Decl::TemplateTypeParm:
7744 case Decl::UnresolvedUsingTypename:
7745 case Decl::UnresolvedUsingValue:
7746 case Decl::Using:
7747 case Decl::UsingDirective:
7748 case Decl::UsingShadow:
7749 return CXLanguage_CPlusPlus;
7750 }
7751
7752 return CXLanguage_C;
7753}
7754
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007755static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7756 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007757 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007758
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007759 switch (D->getAvailability()) {
7760 case AR_Available:
7761 case AR_NotYetIntroduced:
7762 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007763 return getCursorAvailabilityForDecl(
7764 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007765 return CXAvailability_Available;
7766
7767 case AR_Deprecated:
7768 return CXAvailability_Deprecated;
7769
7770 case AR_Unavailable:
7771 return CXAvailability_NotAvailable;
7772 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007773
7774 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007775}
7776
Guy Benyei11169dd2012-12-18 14:30:41 +00007777enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7778 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007779 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7780 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007781
7782 return CXAvailability_Available;
7783}
7784
7785static CXVersion convertVersion(VersionTuple In) {
7786 CXVersion Out = { -1, -1, -1 };
7787 if (In.empty())
7788 return Out;
7789
7790 Out.Major = In.getMajor();
7791
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007792 Optional<unsigned> Minor = In.getMinor();
7793 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007794 Out.Minor = *Minor;
7795 else
7796 return Out;
7797
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007798 Optional<unsigned> Subminor = In.getSubminor();
7799 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007800 Out.Subminor = *Subminor;
7801
7802 return Out;
7803}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007804
Alex Lorenz1345ea22017-06-12 19:06:30 +00007805static void getCursorPlatformAvailabilityForDecl(
7806 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7807 int *always_unavailable, CXString *unavailable_message,
7808 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007809 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007810 for (auto A : D->attrs()) {
7811 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007812 HadAvailAttr = true;
7813 if (always_deprecated)
7814 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007815 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007816 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007817 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007818 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007819 continue;
7820 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007821
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007822 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007823 HadAvailAttr = true;
7824 if (always_unavailable)
7825 *always_unavailable = 1;
7826 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007827 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007828 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7829 }
7830 continue;
7831 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007832
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007833 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007834 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007835 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007836 }
7837 }
7838
7839 if (!HadAvailAttr)
7840 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7841 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007842 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7843 deprecated_message, always_unavailable, unavailable_message,
7844 AvailabilityAttrs);
7845
7846 if (AvailabilityAttrs.empty())
7847 return;
7848
Fangrui Song55fab262018-09-26 22:16:28 +00007849 llvm::sort(AvailabilityAttrs,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007850 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7851 return LHS->getPlatform()->getName() <
7852 RHS->getPlatform()->getName();
Fangrui Song55fab262018-09-26 22:16:28 +00007853 });
Alex Lorenz1345ea22017-06-12 19:06:30 +00007854 ASTContext &Ctx = D->getASTContext();
7855 auto It = std::unique(
7856 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7857 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7858 if (LHS->getPlatform() != RHS->getPlatform())
7859 return false;
7860
7861 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7862 LHS->getDeprecated() == RHS->getDeprecated() &&
7863 LHS->getObsoleted() == RHS->getObsoleted() &&
7864 LHS->getMessage() == RHS->getMessage() &&
7865 LHS->getReplacement() == RHS->getReplacement())
7866 return true;
7867
7868 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7869 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7870 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7871 return false;
7872
7873 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7874 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7875
7876 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7877 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7878 if (LHS->getMessage().empty())
7879 LHS->setMessage(Ctx, RHS->getMessage());
7880 if (LHS->getReplacement().empty())
7881 LHS->setReplacement(Ctx, RHS->getReplacement());
7882 }
7883
7884 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7885 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7886 if (LHS->getMessage().empty())
7887 LHS->setMessage(Ctx, RHS->getMessage());
7888 if (LHS->getReplacement().empty())
7889 LHS->setReplacement(Ctx, RHS->getReplacement());
7890 }
7891
7892 return true;
7893 });
7894 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007895}
7896
Alex Lorenz1345ea22017-06-12 19:06:30 +00007897int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007898 CXString *deprecated_message,
7899 int *always_unavailable,
7900 CXString *unavailable_message,
7901 CXPlatformAvailability *availability,
7902 int availability_size) {
7903 if (always_deprecated)
7904 *always_deprecated = 0;
7905 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007906 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007907 if (always_unavailable)
7908 *always_unavailable = 0;
7909 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007910 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007911
Guy Benyei11169dd2012-12-18 14:30:41 +00007912 if (!clang_isDeclaration(cursor.kind))
7913 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007914
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007915 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007916 if (!D)
7917 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007918
Alex Lorenz1345ea22017-06-12 19:06:30 +00007919 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7920 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7921 always_unavailable, unavailable_message,
7922 AvailabilityAttrs);
7923 for (const auto &Avail :
7924 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7925 .take_front(availability_size))) {
7926 availability[Avail.index()].Platform =
7927 cxstring::createDup(Avail.value()->getPlatform()->getName());
7928 availability[Avail.index()].Introduced =
7929 convertVersion(Avail.value()->getIntroduced());
7930 availability[Avail.index()].Deprecated =
7931 convertVersion(Avail.value()->getDeprecated());
7932 availability[Avail.index()].Obsoleted =
7933 convertVersion(Avail.value()->getObsoleted());
7934 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7935 availability[Avail.index()].Message =
7936 cxstring::createDup(Avail.value()->getMessage());
7937 }
7938
7939 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007940}
Alex Lorenz1345ea22017-06-12 19:06:30 +00007941
Guy Benyei11169dd2012-12-18 14:30:41 +00007942void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7943 clang_disposeString(availability->Platform);
7944 clang_disposeString(availability->Message);
7945}
7946
7947CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7948 if (clang_isDeclaration(cursor.kind))
7949 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7950
7951 return CXLanguage_Invalid;
7952}
7953
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00007954CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7955 const Decl *D = cxcursor::getCursorDecl(cursor);
7956 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7957 switch (VD->getTLSKind()) {
7958 case VarDecl::TLS_None:
7959 return CXTLS_None;
7960 case VarDecl::TLS_Dynamic:
7961 return CXTLS_Dynamic;
7962 case VarDecl::TLS_Static:
7963 return CXTLS_Static;
7964 }
7965 }
7966
7967 return CXTLS_None;
7968}
7969
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007970 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007971 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00007972 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007973static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007974 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007975 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007976
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007977 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007978 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7979 return FunTmpl;
7980
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007981 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007982 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7983 return ClassTmpl;
7984
7985 return D;
7986}
7987
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007988
7989enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7990 StorageClass sc = SC_None;
7991 const Decl *D = getCursorDecl(C);
7992 if (D) {
7993 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7994 sc = FD->getStorageClass();
7995 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7996 sc = VD->getStorageClass();
7997 } else {
7998 return CX_SC_Invalid;
7999 }
8000 } else {
8001 return CX_SC_Invalid;
8002 }
8003 switch (sc) {
8004 case SC_None:
8005 return CX_SC_None;
8006 case SC_Extern:
8007 return CX_SC_Extern;
8008 case SC_Static:
8009 return CX_SC_Static;
8010 case SC_PrivateExtern:
8011 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008012 case SC_Auto:
8013 return CX_SC_Auto;
8014 case SC_Register:
8015 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008016 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00008017 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008018}
8019
Guy Benyei11169dd2012-12-18 14:30:41 +00008020CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
8021 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008022 if (const Decl *D = getCursorDecl(cursor)) {
8023 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008024 if (!DC)
8025 return clang_getNullCursor();
8026
8027 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8028 getCursorTU(cursor));
8029 }
8030 }
8031
8032 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008033 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00008034 return MakeCXCursor(D, getCursorTU(cursor));
8035 }
8036
8037 return clang_getNullCursor();
8038}
8039
8040CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8041 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008042 if (const Decl *D = getCursorDecl(cursor)) {
8043 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008044 if (!DC)
8045 return clang_getNullCursor();
8046
8047 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8048 getCursorTU(cursor));
8049 }
8050 }
8051
8052 // FIXME: Note that we can't easily compute the lexical context of a
8053 // statement or expression, so we return nothing.
8054 return clang_getNullCursor();
8055}
8056
8057CXFile clang_getIncludedFile(CXCursor cursor) {
8058 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00008059 return nullptr;
8060
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008061 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00008062 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00008063}
8064
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008065unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8066 if (C.kind != CXCursor_ObjCPropertyDecl)
8067 return CXObjCPropertyAttr_noattr;
8068
8069 unsigned Result = CXObjCPropertyAttr_noattr;
8070 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8071 ObjCPropertyDecl::PropertyAttributeKind Attr =
8072 PD->getPropertyAttributesAsWritten();
8073
8074#define SET_CXOBJCPROP_ATTR(A) \
8075 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8076 Result |= CXObjCPropertyAttr_##A
8077 SET_CXOBJCPROP_ATTR(readonly);
8078 SET_CXOBJCPROP_ATTR(getter);
8079 SET_CXOBJCPROP_ATTR(assign);
8080 SET_CXOBJCPROP_ATTR(readwrite);
8081 SET_CXOBJCPROP_ATTR(retain);
8082 SET_CXOBJCPROP_ATTR(copy);
8083 SET_CXOBJCPROP_ATTR(nonatomic);
8084 SET_CXOBJCPROP_ATTR(setter);
8085 SET_CXOBJCPROP_ATTR(atomic);
8086 SET_CXOBJCPROP_ATTR(weak);
8087 SET_CXOBJCPROP_ATTR(strong);
8088 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00008089 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008090#undef SET_CXOBJCPROP_ATTR
8091
8092 return Result;
8093}
8094
Michael Wu6e88f532018-08-03 05:38:29 +00008095CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8096 if (C.kind != CXCursor_ObjCPropertyDecl)
8097 return cxstring::createNull();
8098
8099 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8100 Selector sel = PD->getGetterName();
8101 if (sel.isNull())
8102 return cxstring::createNull();
8103
8104 return cxstring::createDup(sel.getAsString());
8105}
8106
8107CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8108 if (C.kind != CXCursor_ObjCPropertyDecl)
8109 return cxstring::createNull();
8110
8111 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8112 Selector sel = PD->getSetterName();
8113 if (sel.isNull())
8114 return cxstring::createNull();
8115
8116 return cxstring::createDup(sel.getAsString());
8117}
8118
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00008119unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8120 if (!clang_isDeclaration(C.kind))
8121 return CXObjCDeclQualifier_None;
8122
8123 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8124 const Decl *D = getCursorDecl(C);
8125 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8126 QT = MD->getObjCDeclQualifier();
8127 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8128 QT = PD->getObjCDeclQualifier();
8129 if (QT == Decl::OBJC_TQ_None)
8130 return CXObjCDeclQualifier_None;
8131
8132 unsigned Result = CXObjCDeclQualifier_None;
8133 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
8134 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
8135 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
8136 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
8137 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
8138 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
8139
8140 return Result;
8141}
8142
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00008143unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8144 if (!clang_isDeclaration(C.kind))
8145 return 0;
8146
8147 const Decl *D = getCursorDecl(C);
8148 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8149 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8150 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8151 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8152
8153 return 0;
8154}
8155
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00008156unsigned clang_Cursor_isVariadic(CXCursor C) {
8157 if (!clang_isDeclaration(C.kind))
8158 return 0;
8159
8160 const Decl *D = getCursorDecl(C);
8161 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8162 return FD->isVariadic();
8163 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8164 return MD->isVariadic();
8165
8166 return 0;
8167}
8168
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008169unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8170 CXString *language, CXString *definedIn,
8171 unsigned *isGenerated) {
8172 if (!clang_isDeclaration(C.kind))
8173 return 0;
8174
8175 const Decl *D = getCursorDecl(C);
8176
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00008177 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008178 if (language)
8179 *language = cxstring::createDup(attr->getLanguage());
8180 if (definedIn)
8181 *definedIn = cxstring::createDup(attr->getDefinedIn());
8182 if (isGenerated)
8183 *isGenerated = attr->getGeneratedDeclaration();
8184 return 1;
8185 }
8186 return 0;
8187}
8188
Guy Benyei11169dd2012-12-18 14:30:41 +00008189CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8190 if (!clang_isDeclaration(C.kind))
8191 return clang_getNullRange();
8192
8193 const Decl *D = getCursorDecl(C);
8194 ASTContext &Context = getCursorContext(C);
8195 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8196 if (!RC)
8197 return clang_getNullRange();
8198
8199 return cxloc::translateSourceRange(Context, RC->getSourceRange());
8200}
8201
8202CXString clang_Cursor_getRawCommentText(CXCursor C) {
8203 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008204 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008205
8206 const Decl *D = getCursorDecl(C);
8207 ASTContext &Context = getCursorContext(C);
8208 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8209 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8210 StringRef();
8211
8212 // Don't duplicate the string because RawText points directly into source
8213 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008214 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008215}
8216
8217CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8218 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008219 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008220
8221 const Decl *D = getCursorDecl(C);
8222 const ASTContext &Context = getCursorContext(C);
8223 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8224
8225 if (RC) {
8226 StringRef BriefText = RC->getBriefText(Context);
8227
8228 // Don't duplicate the string because RawComment ensures that this memory
8229 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008230 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008231 }
8232
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008233 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008234}
8235
Guy Benyei11169dd2012-12-18 14:30:41 +00008236CXModule clang_Cursor_getModule(CXCursor C) {
8237 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008238 if (const ImportDecl *ImportD =
8239 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00008240 return ImportD->getImportedModule();
8241 }
8242
Craig Topper69186e72014-06-08 08:38:04 +00008243 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008244}
8245
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008246CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8247 if (isNotUsableTU(TU)) {
8248 LOG_BAD_TU(TU);
8249 return nullptr;
8250 }
8251 if (!File)
8252 return nullptr;
8253 FileEntry *FE = static_cast<FileEntry *>(File);
8254
8255 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8256 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8257 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8258
Richard Smithfeb54b62014-10-23 02:01:19 +00008259 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008260}
8261
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008262CXFile clang_Module_getASTFile(CXModule CXMod) {
8263 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008264 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008265 Module *Mod = static_cast<Module*>(CXMod);
8266 return const_cast<FileEntry *>(Mod->getASTFile());
8267}
8268
Guy Benyei11169dd2012-12-18 14:30:41 +00008269CXModule clang_Module_getParent(CXModule CXMod) {
8270 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008271 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008272 Module *Mod = static_cast<Module*>(CXMod);
8273 return Mod->Parent;
8274}
8275
8276CXString clang_Module_getName(CXModule CXMod) {
8277 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008278 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008279 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008280 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00008281}
8282
8283CXString clang_Module_getFullName(CXModule CXMod) {
8284 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008285 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008286 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008287 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008288}
8289
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008290int clang_Module_isSystem(CXModule CXMod) {
8291 if (!CXMod)
8292 return 0;
8293 Module *Mod = static_cast<Module*>(CXMod);
8294 return Mod->IsSystem;
8295}
8296
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008297unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8298 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008299 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008300 LOG_BAD_TU(TU);
8301 return 0;
8302 }
8303 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008304 return 0;
8305 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008306 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8307 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8308 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008309}
8310
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008311CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8312 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008313 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008314 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008315 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008316 }
8317 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008318 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008319 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008320 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008321
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008322 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8323 if (Index < TopHeaders.size())
8324 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008325
Craig Topper69186e72014-06-08 08:38:04 +00008326 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008327}
8328
Guy Benyei11169dd2012-12-18 14:30:41 +00008329//===----------------------------------------------------------------------===//
8330// C++ AST instrospection.
8331//===----------------------------------------------------------------------===//
8332
Jonathan Coe29565352016-04-27 12:48:25 +00008333unsigned clang_CXXConstructor_isDefaultConstructor(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->isDefaultConstructor()) ? 1 : 0;
8341}
8342
8343unsigned clang_CXXConstructor_isCopyConstructor(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->isCopyConstructor()) ? 1 : 0;
8351}
8352
8353unsigned clang_CXXConstructor_isMoveConstructor(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 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8361}
8362
8363unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8364 if (!clang_isDeclaration(C.kind))
8365 return 0;
8366
8367 const Decl *D = cxcursor::getCursorDecl(C);
8368 const CXXConstructorDecl *Constructor =
8369 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8370 // Passing 'false' excludes constructors marked 'explicit'.
8371 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8372}
8373
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008374unsigned clang_CXXField_isMutable(CXCursor C) {
8375 if (!clang_isDeclaration(C.kind))
8376 return 0;
8377
8378 if (const auto D = cxcursor::getCursorDecl(C))
8379 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8380 return FD->isMutable() ? 1 : 0;
8381 return 0;
8382}
8383
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008384unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8385 if (!clang_isDeclaration(C.kind))
8386 return 0;
8387
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008388 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008389 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008390 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008391 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8392}
8393
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008394unsigned clang_CXXMethod_isConst(CXCursor C) {
8395 if (!clang_isDeclaration(C.kind))
8396 return 0;
8397
8398 const Decl *D = cxcursor::getCursorDecl(C);
8399 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008400 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008401 return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008402}
8403
Jonathan Coe29565352016-04-27 12:48:25 +00008404unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8405 if (!clang_isDeclaration(C.kind))
8406 return 0;
8407
8408 const Decl *D = cxcursor::getCursorDecl(C);
8409 const CXXMethodDecl *Method =
8410 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8411 return (Method && Method->isDefaulted()) ? 1 : 0;
8412}
8413
Guy Benyei11169dd2012-12-18 14:30:41 +00008414unsigned clang_CXXMethod_isStatic(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->isStatic()) ? 1 : 0;
8422}
8423
8424unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8425 if (!clang_isDeclaration(C.kind))
8426 return 0;
8427
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008428 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008429 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008430 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008431 return (Method && Method->isVirtual()) ? 1 : 0;
8432}
Guy Benyei11169dd2012-12-18 14:30:41 +00008433
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008434unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8435 if (!clang_isDeclaration(C.kind))
8436 return 0;
8437
8438 const auto *D = cxcursor::getCursorDecl(C);
8439 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8440 if (RD)
8441 RD = RD->getDefinition();
8442 return (RD && RD->isAbstract()) ? 1 : 0;
8443}
8444
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008445unsigned clang_EnumDecl_isScoped(CXCursor C) {
8446 if (!clang_isDeclaration(C.kind))
8447 return 0;
8448
8449 const Decl *D = cxcursor::getCursorDecl(C);
8450 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8451 return (Enum && Enum->isScoped()) ? 1 : 0;
8452}
8453
Guy Benyei11169dd2012-12-18 14:30:41 +00008454//===----------------------------------------------------------------------===//
8455// Attribute introspection.
8456//===----------------------------------------------------------------------===//
8457
Guy Benyei11169dd2012-12-18 14:30:41 +00008458CXType clang_getIBOutletCollectionType(CXCursor C) {
8459 if (C.kind != CXCursor_IBOutletCollectionAttr)
8460 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8461
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008462 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008463 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8464
8465 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8466}
Guy Benyei11169dd2012-12-18 14:30:41 +00008467
8468//===----------------------------------------------------------------------===//
8469// Inspecting memory usage.
8470//===----------------------------------------------------------------------===//
8471
8472typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8473
8474static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8475 enum CXTUResourceUsageKind k,
8476 unsigned long amount) {
8477 CXTUResourceUsageEntry entry = { k, amount };
8478 entries.push_back(entry);
8479}
8480
Guy Benyei11169dd2012-12-18 14:30:41 +00008481const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8482 const char *str = "";
8483 switch (kind) {
8484 case CXTUResourceUsage_AST:
8485 str = "ASTContext: expressions, declarations, and types";
8486 break;
8487 case CXTUResourceUsage_Identifiers:
8488 str = "ASTContext: identifiers";
8489 break;
8490 case CXTUResourceUsage_Selectors:
8491 str = "ASTContext: selectors";
8492 break;
8493 case CXTUResourceUsage_GlobalCompletionResults:
8494 str = "Code completion: cached global results";
8495 break;
8496 case CXTUResourceUsage_SourceManagerContentCache:
8497 str = "SourceManager: content cache allocator";
8498 break;
8499 case CXTUResourceUsage_AST_SideTables:
8500 str = "ASTContext: side tables";
8501 break;
8502 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8503 str = "SourceManager: malloc'ed memory buffers";
8504 break;
8505 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8506 str = "SourceManager: mmap'ed memory buffers";
8507 break;
8508 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8509 str = "ExternalASTSource: malloc'ed memory buffers";
8510 break;
8511 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8512 str = "ExternalASTSource: mmap'ed memory buffers";
8513 break;
8514 case CXTUResourceUsage_Preprocessor:
8515 str = "Preprocessor: malloc'ed memory";
8516 break;
8517 case CXTUResourceUsage_PreprocessingRecord:
8518 str = "Preprocessor: PreprocessingRecord";
8519 break;
8520 case CXTUResourceUsage_SourceManager_DataStructures:
8521 str = "SourceManager: data structures and tables";
8522 break;
8523 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8524 str = "Preprocessor: header search tables";
8525 break;
8526 }
8527 return str;
8528}
8529
8530CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008531 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008532 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008533 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008534 return usage;
8535 }
8536
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008537 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008538 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008539 ASTContext &astContext = astUnit->getASTContext();
8540
8541 // How much memory is used by AST nodes and types?
8542 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8543 (unsigned long) astContext.getASTAllocatedMemory());
8544
8545 // How much memory is used by identifiers?
8546 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8547 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8548
8549 // How much memory is used for selectors?
8550 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8551 (unsigned long) astContext.Selectors.getTotalMemory());
8552
8553 // How much memory is used by ASTContext's side tables?
8554 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8555 (unsigned long) astContext.getSideTableAllocatedMemory());
8556
8557 // How much memory is used for caching global code completion results?
8558 unsigned long completionBytes = 0;
8559 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008560 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008561 completionBytes = completionAllocator->getTotalMemory();
8562 }
8563 createCXTUResourceUsageEntry(*entries,
8564 CXTUResourceUsage_GlobalCompletionResults,
8565 completionBytes);
8566
8567 // How much memory is being used by SourceManager's content cache?
8568 createCXTUResourceUsageEntry(*entries,
8569 CXTUResourceUsage_SourceManagerContentCache,
8570 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8571
8572 // How much memory is being used by the MemoryBuffer's in SourceManager?
8573 const SourceManager::MemoryBufferSizes &srcBufs =
8574 astUnit->getSourceManager().getMemoryBufferSizes();
8575
8576 createCXTUResourceUsageEntry(*entries,
8577 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8578 (unsigned long) srcBufs.malloc_bytes);
8579 createCXTUResourceUsageEntry(*entries,
8580 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8581 (unsigned long) srcBufs.mmap_bytes);
8582 createCXTUResourceUsageEntry(*entries,
8583 CXTUResourceUsage_SourceManager_DataStructures,
8584 (unsigned long) astContext.getSourceManager()
8585 .getDataStructureSizes());
8586
8587 // How much memory is being used by the ExternalASTSource?
8588 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8589 const ExternalASTSource::MemoryBufferSizes &sizes =
8590 esrc->getMemoryBufferSizes();
8591
8592 createCXTUResourceUsageEntry(*entries,
8593 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8594 (unsigned long) sizes.malloc_bytes);
8595 createCXTUResourceUsageEntry(*entries,
8596 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8597 (unsigned long) sizes.mmap_bytes);
8598 }
8599
8600 // How much memory is being used by the Preprocessor?
8601 Preprocessor &pp = astUnit->getPreprocessor();
8602 createCXTUResourceUsageEntry(*entries,
8603 CXTUResourceUsage_Preprocessor,
8604 pp.getTotalMemory());
8605
8606 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8607 createCXTUResourceUsageEntry(*entries,
8608 CXTUResourceUsage_PreprocessingRecord,
8609 pRec->getTotalMemory());
8610 }
8611
8612 createCXTUResourceUsageEntry(*entries,
8613 CXTUResourceUsage_Preprocessor_HeaderSearch,
8614 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008615
Guy Benyei11169dd2012-12-18 14:30:41 +00008616 CXTUResourceUsage usage = { (void*) entries.get(),
8617 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008618 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008619 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008620 return usage;
8621}
8622
8623void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8624 if (usage.data)
8625 delete (MemUsageEntries*) usage.data;
8626}
8627
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008628CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8629 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008630 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008631 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008632
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008633 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008634 LOG_BAD_TU(TU);
8635 return skipped;
8636 }
8637
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008638 if (!file)
8639 return skipped;
8640
8641 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8642 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8643 if (!ppRec)
8644 return skipped;
8645
8646 ASTContext &Ctx = astUnit->getASTContext();
8647 SourceManager &sm = Ctx.getSourceManager();
8648 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8649 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008650 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008651
8652 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8653 std::vector<SourceRange> wantedRanges;
8654 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8655 i != ei; ++i) {
8656 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8657 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008658 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8659 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008660 }
8661
8662 skipped->count = wantedRanges.size();
8663 skipped->ranges = new CXSourceRange[skipped->count];
8664 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8665 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8666
8667 return skipped;
8668}
8669
Cameron Desrochersd8091282016-08-18 15:43:55 +00008670CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8671 CXSourceRangeList *skipped = new CXSourceRangeList;
8672 skipped->count = 0;
8673 skipped->ranges = nullptr;
8674
8675 if (isNotUsableTU(TU)) {
8676 LOG_BAD_TU(TU);
8677 return skipped;
8678 }
8679
8680 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8681 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8682 if (!ppRec)
8683 return skipped;
8684
8685 ASTContext &Ctx = astUnit->getASTContext();
8686
8687 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8688
8689 skipped->count = SkippedRanges.size();
8690 skipped->ranges = new CXSourceRange[skipped->count];
8691 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8692 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8693
8694 return skipped;
8695}
8696
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008697void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8698 if (ranges) {
8699 delete[] ranges->ranges;
8700 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008701 }
8702}
8703
Guy Benyei11169dd2012-12-18 14:30:41 +00008704void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8705 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8706 for (unsigned I = 0; I != Usage.numEntries; ++I)
8707 fprintf(stderr, " %s: %lu\n",
8708 clang_getTUResourceUsageName(Usage.entries[I].kind),
8709 Usage.entries[I].amount);
8710
8711 clang_disposeCXTUResourceUsage(Usage);
8712}
8713
8714//===----------------------------------------------------------------------===//
8715// Misc. utility functions.
8716//===----------------------------------------------------------------------===//
8717
Richard Smith0a7b2972018-07-03 21:34:13 +00008718/// Default to using our desired 8 MB stack size on "safety" threads.
8719static unsigned SafetyStackThreadSize = DesiredStackSize;
Guy Benyei11169dd2012-12-18 14:30:41 +00008720
8721namespace clang {
8722
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008723bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008724 unsigned Size) {
8725 if (!Size)
8726 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008727 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008728 return CRC.RunSafelyOnThread(Fn, Size);
8729 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008730}
8731
8732unsigned GetSafetyThreadStackSize() {
8733 return SafetyStackThreadSize;
8734}
8735
8736void SetSafetyThreadStackSize(unsigned Value) {
8737 SafetyStackThreadSize = Value;
8738}
8739
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008740}
Guy Benyei11169dd2012-12-18 14:30:41 +00008741
8742void clang::setThreadBackgroundPriority() {
8743 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8744 return;
8745
Nico Weber18cfd9f2019-04-21 19:18:41 +00008746#if LLVM_ENABLE_THREADS
Kadir Cetinkayab8f82ca2019-04-18 13:49:20 +00008747 llvm::set_thread_priority(llvm::ThreadPriority::Background);
Nico Weber18cfd9f2019-04-21 19:18:41 +00008748#endif
Guy Benyei11169dd2012-12-18 14:30:41 +00008749}
8750
8751void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8752 if (!Unit)
8753 return;
8754
8755 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8756 DEnd = Unit->stored_diag_end();
8757 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008758 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008759 CXString Msg = clang_formatDiagnostic(&Diag,
8760 clang_defaultDiagnosticDisplayOptions());
8761 fprintf(stderr, "%s\n", clang_getCString(Msg));
8762 clang_disposeString(Msg);
8763 }
Nico Weber1865df42018-04-27 19:11:14 +00008764#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008765 // On Windows, force a flush, since there may be multiple copies of
8766 // stderr and stdout in the file system, all with different buffers
8767 // but writing to the same device.
8768 fflush(stderr);
8769#endif
8770}
8771
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008772MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8773 SourceLocation MacroDefLoc,
8774 CXTranslationUnit TU){
8775 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008776 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008777 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008778 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008779
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008780 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008781 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008782 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008783 if (MD) {
8784 for (MacroDirective::DefInfo
8785 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8786 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8787 return Def.getMacroInfo();
8788 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008789 }
8790
Craig Topper69186e72014-06-08 08:38:04 +00008791 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008792}
8793
Richard Smith66a81862015-05-04 02:25:31 +00008794const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008795 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008796 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008797 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008798 const IdentifierInfo *II = MacroDef->getName();
8799 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008800 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008801
8802 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8803}
8804
Richard Smith66a81862015-05-04 02:25:31 +00008805MacroDefinitionRecord *
8806cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8807 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008808 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008809 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008810 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008811 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008812
8813 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008814 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008815 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8816 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008817 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008818
8819 // Check that the token is inside the definition and not its argument list.
8820 SourceManager &SM = Unit->getSourceManager();
8821 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008822 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008823 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008824 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008825
8826 Preprocessor &PP = Unit->getPreprocessor();
8827 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8828 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008829 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008830
Alp Toker2d57cea2014-05-17 04:53:25 +00008831 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008832 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008833 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008834
8835 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008836 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008837 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008838
Richard Smith20e883e2015-04-29 23:20:19 +00008839 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008840 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008841 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008842
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008843 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008844}
8845
Richard Smith66a81862015-05-04 02:25:31 +00008846MacroDefinitionRecord *
8847cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8848 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008849 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008850 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008851
8852 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008853 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008854 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008855 Preprocessor &PP = Unit->getPreprocessor();
8856 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008857 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008858 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8859 Token Tok;
8860 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008861 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008862
8863 return checkForMacroInMacroDefinition(MI, Tok, TU);
8864}
8865
Guy Benyei11169dd2012-12-18 14:30:41 +00008866CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008867 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008868}
8869
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008870Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8871 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008872 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008873 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008874 if (Unit->isMainFileAST())
8875 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008876 return *this;
8877 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008878 } else {
8879 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008880 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008881 return *this;
8882}
8883
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008884Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8885 *this << FE->getName();
8886 return *this;
8887}
8888
8889Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8890 CXString cursorName = clang_getCursorDisplayName(cursor);
8891 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8892 clang_disposeString(cursorName);
8893 return *this;
8894}
8895
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008896Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8897 CXFile File;
8898 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008899 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008900 CXString FileName = clang_getFileName(File);
8901 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8902 clang_disposeString(FileName);
8903 return *this;
8904}
8905
8906Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8907 CXSourceLocation BLoc = clang_getRangeStart(range);
8908 CXSourceLocation ELoc = clang_getRangeEnd(range);
8909
8910 CXFile BFile;
8911 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008912 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008913
8914 CXFile EFile;
8915 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008916 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008917
8918 CXString BFileName = clang_getFileName(BFile);
8919 if (BFile == EFile) {
8920 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8921 BLine, BColumn, ELine, EColumn);
8922 } else {
8923 CXString EFileName = clang_getFileName(EFile);
8924 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8925 BLine, BColumn)
8926 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8927 ELine, EColumn);
8928 clang_disposeString(EFileName);
8929 }
8930 clang_disposeString(BFileName);
8931 return *this;
8932}
8933
8934Logger &cxindex::Logger::operator<<(CXString Str) {
8935 *this << clang_getCString(Str);
8936 return *this;
8937}
8938
8939Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8940 LogOS << Fmt;
8941 return *this;
8942}
8943
Benjamin Kramer762bc332019-08-07 14:44:40 +00008944static llvm::ManagedStatic<std::mutex> LoggingMutex;
Chandler Carruth37ad2582014-06-27 15:14:39 +00008945
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008946cxindex::Logger::~Logger() {
Benjamin Kramer762bc332019-08-07 14:44:40 +00008947 std::lock_guard<std::mutex> L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008948
8949 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8950
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008951 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008952 OS << "[libclang:" << Name << ':';
8953
Alp Toker1a86ad22014-07-06 06:24:00 +00008954#ifdef USE_DARWIN_THREADS
8955 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008956 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8957 OS << tid << ':';
8958#endif
8959
8960 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8961 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008962 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008963
8964 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008965 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008966 OS << "--------------------------------------------------\n";
8967 }
8968}
Ivan Donchevskiic5929132018-12-10 15:58:50 +00008969
8970#ifdef CLANG_TOOL_EXTRA_BUILD
8971// This anchor is used to force the linker to link the clang-tidy plugin.
8972extern volatile int ClangTidyPluginAnchorSource;
8973static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8974 ClangTidyPluginAnchorSource;
8975
8976// This anchor is used to force the linker to link the clang-include-fixer
8977// plugin.
8978extern volatile int ClangIncludeFixerPluginAnchorSource;
8979static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8980 ClangIncludeFixerPluginAnchorSource;
8981#endif