blob: 78a1290de658ebde92e0e7c983562707b0962167 [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Guy Benyei11169dd2012-12-18 14:30:41 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the main API hooks in the Clang-C Source Indexing
10// library.
11//
12//===----------------------------------------------------------------------===//
13
Guy Benyei11169dd2012-12-18 14:30:41 +000014#include "CIndexDiagnostic.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000015#include "CIndexer.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000016#include "CLog.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000017#include "CXCursor.h"
18#include "CXSourceLocation.h"
19#include "CXString.h"
20#include "CXTranslationUnit.h"
21#include "CXType.h"
22#include "CursorVisitor.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000023#include "clang/AST/Attr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000024#include "clang/AST/StmtVisitor.h"
25#include "clang/Basic/Diagnostic.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000026#include "clang/Basic/DiagnosticCategories.h"
27#include "clang/Basic/DiagnosticIDs.h"
Richard Smith0a7b2972018-07-03 21:34:13 +000028#include "clang/Basic/Stack.h"
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +000029#include "clang/Basic/TargetInfo.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000030#include "clang/Basic/Version.h"
31#include "clang/Frontend/ASTUnit.h"
32#include "clang/Frontend/CompilerInstance.h"
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +000033#include "clang/Index/CodegenNameGenerator.h"
Dmitri Gribenko9e605112013-11-13 22:16:51 +000034#include "clang/Index/CommentToXML.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000035#include "clang/Lex/HeaderSearch.h"
36#include "clang/Lex/Lexer.h"
37#include "clang/Lex/PreprocessingRecord.h"
38#include "clang/Lex/Preprocessor.h"
39#include "llvm/ADT/Optional.h"
40#include "llvm/ADT/STLExtras.h"
41#include "llvm/ADT/StringSwitch.h"
Alp Toker1d257e12014-06-04 03:28:55 +000042#include "llvm/Config/llvm-config.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000043#include "llvm/Support/Compiler.h"
44#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000045#include "llvm/Support/Format.h"
Chandler Carruth37ad2582014-06-27 15:14:39 +000046#include "llvm/Support/ManagedStatic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000047#include "llvm/Support/MemoryBuffer.h"
48#include "llvm/Support/Mutex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000049#include "llvm/Support/Program.h"
50#include "llvm/Support/SaveAndRestore.h"
51#include "llvm/Support/Signals.h"
Adrian Prantlbc068582015-07-08 01:00:30 +000052#include "llvm/Support/TargetSelect.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000053#include "llvm/Support/Threading.h"
54#include "llvm/Support/Timer.h"
55#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000056
Alp Toker1a86ad22014-07-06 06:24:00 +000057#if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
58#define USE_DARWIN_THREADS
59#endif
60
61#ifdef USE_DARWIN_THREADS
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000062#include <pthread.h>
63#endif
Guy Benyei11169dd2012-12-18 14:30:41 +000064
65using namespace clang;
66using namespace clang::cxcursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000067using namespace clang::cxtu;
68using namespace clang::cxindex;
69
David Blaikieea4395e2017-01-06 19:49:01 +000070CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
71 std::unique_ptr<ASTUnit> AU) {
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000072 if (!AU)
Craig Topper69186e72014-06-08 08:38:04 +000073 return nullptr;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000074 assert(CIdx);
Guy Benyei11169dd2012-12-18 14:30:41 +000075 CXTranslationUnit D = new CXTranslationUnitImpl();
76 D->CIdx = CIdx;
David Blaikieea4395e2017-01-06 19:49:01 +000077 D->TheASTUnit = AU.release();
Dmitri Gribenko74895212013-02-03 13:52:47 +000078 D->StringPool = new cxstring::CXStringPool();
Craig Topper69186e72014-06-08 08:38:04 +000079 D->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000080 D->OverridenCursorsPool = createOverridenCXCursorsPool();
Craig Topper69186e72014-06-08 08:38:04 +000081 D->CommentToXML = nullptr;
Alex Lorenz690f0e22017-12-07 20:37:50 +000082 D->ParsingOptions = 0;
83 D->Arguments = {};
Guy Benyei11169dd2012-12-18 14:30:41 +000084 return D;
85}
86
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000087bool cxtu::isASTReadError(ASTUnit *AU) {
88 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
89 DEnd = AU->stored_diag_end();
90 D != DEnd; ++D) {
91 if (D->getLevel() >= DiagnosticsEngine::Error &&
92 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
93 diag::DiagCat_AST_Deserialization_Issue)
94 return true;
95 }
96 return false;
97}
98
Guy Benyei11169dd2012-12-18 14:30:41 +000099cxtu::CXTUOwner::~CXTUOwner() {
100 if (TU)
101 clang_disposeTranslationUnit(TU);
102}
103
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000104/// Compare two source ranges to determine their relative position in
Guy Benyei11169dd2012-12-18 14:30:41 +0000105/// the translation unit.
106static RangeComparisonResult RangeCompare(SourceManager &SM,
107 SourceRange R1,
108 SourceRange R2) {
109 assert(R1.isValid() && "First range is invalid?");
110 assert(R2.isValid() && "Second range is invalid?");
111 if (R1.getEnd() != R2.getBegin() &&
112 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
113 return RangeBefore;
114 if (R2.getEnd() != R1.getBegin() &&
115 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
116 return RangeAfter;
117 return RangeOverlap;
118}
119
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000120/// Determine if a source location falls within, before, or after a
Guy Benyei11169dd2012-12-18 14:30:41 +0000121/// a given source range.
122static RangeComparisonResult LocationCompare(SourceManager &SM,
123 SourceLocation L, SourceRange R) {
124 assert(R.isValid() && "First range is invalid?");
125 assert(L.isValid() && "Second range is invalid?");
126 if (L == R.getBegin() || L == R.getEnd())
127 return RangeOverlap;
128 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
129 return RangeBefore;
130 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
131 return RangeAfter;
132 return RangeOverlap;
133}
134
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000135/// Translate a Clang source range into a CIndex source range.
Guy Benyei11169dd2012-12-18 14:30:41 +0000136///
137/// Clang internally represents ranges where the end location points to the
138/// start of the token at the end. However, for external clients it is more
139/// useful to have a CXSourceRange be a proper half-open interval. This routine
140/// does the appropriate translation.
141CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
142 const LangOptions &LangOpts,
143 const CharSourceRange &R) {
144 // We want the last character in this location, so we will adjust the
145 // location accordingly.
146 SourceLocation EndLoc = R.getEnd();
Richard Smithb5f81712018-04-30 05:25:48 +0000147 bool IsTokenRange = R.isTokenRange();
148 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc)) {
149 CharSourceRange Expansion = SM.getExpansionRange(EndLoc);
150 EndLoc = Expansion.getEnd();
151 IsTokenRange = Expansion.isTokenRange();
152 }
153 if (IsTokenRange && EndLoc.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000154 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
155 SM, LangOpts);
156 EndLoc = EndLoc.getLocWithOffset(Length);
157 }
158
Bill Wendlingeade3622013-01-23 08:25:41 +0000159 CXSourceRange Result = {
Dmitri Gribenkof9304482013-01-23 15:56:07 +0000160 { &SM, &LangOpts },
Bill Wendlingeade3622013-01-23 08:25:41 +0000161 R.getBegin().getRawEncoding(),
162 EndLoc.getRawEncoding()
163 };
Guy Benyei11169dd2012-12-18 14:30:41 +0000164 return Result;
165}
166
167//===----------------------------------------------------------------------===//
168// Cursor visitor.
169//===----------------------------------------------------------------------===//
170
171static SourceRange getRawCursorExtent(CXCursor C);
172static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
173
174
175RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
176 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
177}
178
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000179/// Visit the given cursor and, if requested by the visitor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000180/// its children.
181///
182/// \param Cursor the cursor to visit.
183///
184/// \param CheckedRegionOfInterest if true, then the caller already checked
185/// that this cursor is within the region of interest.
186///
187/// \returns true if the visitation should be aborted, false if it
188/// should continue.
189bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
190 if (clang_isInvalid(Cursor.kind))
191 return false;
192
193 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000194 const Decl *D = getCursorDecl(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +0000195 if (!D) {
196 assert(0 && "Invalid declaration cursor");
197 return true; // abort.
198 }
199
200 // Ignore implicit declarations, unless it's an objc method because
201 // currently we should report implicit methods for properties when indexing.
202 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
203 return false;
204 }
205
206 // If we have a range of interest, and this cursor doesn't intersect with it,
207 // we're done.
208 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
209 SourceRange Range = getRawCursorExtent(Cursor);
210 if (Range.isInvalid() || CompareRegionOfInterest(Range))
211 return false;
212 }
213
214 switch (Visitor(Cursor, Parent, ClientData)) {
215 case CXChildVisit_Break:
216 return true;
217
218 case CXChildVisit_Continue:
219 return false;
220
221 case CXChildVisit_Recurse: {
222 bool ret = VisitChildren(Cursor);
223 if (PostChildrenVisitor)
224 if (PostChildrenVisitor(Cursor, ClientData))
225 return true;
226 return ret;
227 }
228 }
229
230 llvm_unreachable("Invalid CXChildVisitResult!");
231}
232
233static bool visitPreprocessedEntitiesInRange(SourceRange R,
234 PreprocessingRecord &PPRec,
235 CursorVisitor &Visitor) {
236 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
237 FileID FID;
238
239 if (!Visitor.shouldVisitIncludedEntities()) {
240 // If the begin/end of the range lie in the same FileID, do the optimization
241 // where we skip preprocessed entities that do not come from the same FileID.
242 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
243 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
244 FID = FileID();
245 }
246
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000247 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
248 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000249 PPRec, FID);
250}
251
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000252bool CursorVisitor::visitFileRegion() {
Guy Benyei11169dd2012-12-18 14:30:41 +0000253 if (RegionOfInterest.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000254 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000255
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000256 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000257 SourceManager &SM = Unit->getSourceManager();
258
259 std::pair<FileID, unsigned>
260 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
261 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
262
263 if (End.first != Begin.first) {
264 // If the end does not reside in the same file, try to recover by
265 // picking the end of the file of begin location.
266 End.first = Begin.first;
267 End.second = SM.getFileIDSize(Begin.first);
268 }
269
270 assert(Begin.first == End.first);
271 if (Begin.second > End.second)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000272 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000273
274 FileID File = Begin.first;
275 unsigned Offset = Begin.second;
276 unsigned Length = End.second - Begin.second;
277
278 if (!VisitDeclsOnly && !VisitPreprocessorLast)
279 if (visitPreprocessedEntitiesInRegion())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000280 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000281
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000282 if (visitDeclsFromFileRegion(File, Offset, Length))
283 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000284
285 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000286 return visitPreprocessedEntitiesInRegion();
287
288 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000289}
290
291static bool isInLexicalContext(Decl *D, DeclContext *DC) {
292 if (!DC)
293 return false;
294
295 for (DeclContext *DeclDC = D->getLexicalDeclContext();
296 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
297 if (DeclDC == DC)
298 return true;
299 }
300 return false;
301}
302
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000303bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
Guy Benyei11169dd2012-12-18 14:30:41 +0000304 unsigned Offset, unsigned Length) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000305 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000306 SourceManager &SM = Unit->getSourceManager();
307 SourceRange Range = RegionOfInterest;
308
309 SmallVector<Decl *, 16> Decls;
310 Unit->findFileRegionDecls(File, Offset, Length, Decls);
311
312 // If we didn't find any file level decls for the file, try looking at the
313 // file that it was included from.
314 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
315 bool Invalid = false;
316 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
317 if (Invalid)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000318 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000319
320 SourceLocation Outer;
321 if (SLEntry.isFile())
322 Outer = SLEntry.getFile().getIncludeLoc();
323 else
324 Outer = SLEntry.getExpansion().getExpansionLocStart();
325 if (Outer.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000326 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000327
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000328 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
Guy Benyei11169dd2012-12-18 14:30:41 +0000329 Length = 0;
330 Unit->findFileRegionDecls(File, Offset, Length, Decls);
331 }
332
333 assert(!Decls.empty());
334
335 bool VisitedAtLeastOnce = false;
Craig Topper69186e72014-06-08 08:38:04 +0000336 DeclContext *CurDC = nullptr;
Craig Topper2341c0d2013-07-04 03:08:24 +0000337 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
338 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000339 Decl *D = *DIt;
340 if (D->getSourceRange().isInvalid())
341 continue;
342
343 if (isInLexicalContext(D, CurDC))
344 continue;
345
346 CurDC = dyn_cast<DeclContext>(D);
347
348 if (TagDecl *TD = dyn_cast<TagDecl>(D))
349 if (!TD->isFreeStanding())
350 continue;
351
352 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
353 if (CompRes == RangeBefore)
354 continue;
355 if (CompRes == RangeAfter)
356 break;
357
358 assert(CompRes == RangeOverlap);
359 VisitedAtLeastOnce = true;
360
361 if (isa<ObjCContainerDecl>(D)) {
362 FileDI_current = &DIt;
363 FileDE_current = DE;
364 } else {
Craig Topper69186e72014-06-08 08:38:04 +0000365 FileDI_current = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000366 }
367
368 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000369 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000370 }
371
372 if (VisitedAtLeastOnce)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000373 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000374
375 // No Decls overlapped with the range. Move up the lexical context until there
376 // is a context that contains the range or we reach the translation unit
377 // level.
378 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
379 : (*(DIt-1))->getLexicalDeclContext();
380
381 while (DC && !DC->isTranslationUnit()) {
382 Decl *D = cast<Decl>(DC);
383 SourceRange CurDeclRange = D->getSourceRange();
384 if (CurDeclRange.isInvalid())
385 break;
386
387 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000388 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
389 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000390 }
391
392 DC = D->getLexicalDeclContext();
393 }
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000394
395 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000396}
397
398bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
399 if (!AU->getPreprocessor().getPreprocessingRecord())
400 return false;
401
402 PreprocessingRecord &PPRec
403 = *AU->getPreprocessor().getPreprocessingRecord();
404 SourceManager &SM = AU->getSourceManager();
405
406 if (RegionOfInterest.isValid()) {
407 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
408 SourceLocation B = MappedRange.getBegin();
409 SourceLocation E = MappedRange.getEnd();
410
411 if (AU->isInPreambleFileID(B)) {
412 if (SM.isLoadedSourceLocation(E))
413 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
414 PPRec, *this);
415
416 // Beginning of range lies in the preamble but it also extends beyond
417 // it into the main file. Split the range into 2 parts, one covering
418 // the preamble and another covering the main file. This allows subsequent
419 // calls to visitPreprocessedEntitiesInRange to accept a source range that
420 // lies in the same FileID, allowing it to skip preprocessed entities that
421 // do not come from the same FileID.
422 bool breaked =
423 visitPreprocessedEntitiesInRange(
424 SourceRange(B, AU->getEndOfPreambleFileID()),
425 PPRec, *this);
426 if (breaked) return true;
427 return visitPreprocessedEntitiesInRange(
428 SourceRange(AU->getStartOfMainFileID(), E),
429 PPRec, *this);
430 }
431
432 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
433 }
434
435 bool OnlyLocalDecls
436 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
437
438 if (OnlyLocalDecls)
439 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
440 PPRec);
441
442 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
443}
444
445template<typename InputIterator>
446bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
447 InputIterator Last,
448 PreprocessingRecord &PPRec,
449 FileID FID) {
450 for (; First != Last; ++First) {
451 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
452 continue;
453
454 PreprocessedEntity *PPE = *First;
Argyrios Kyrtzidis1030f262013-05-07 20:37:17 +0000455 if (!PPE)
456 continue;
457
Guy Benyei11169dd2012-12-18 14:30:41 +0000458 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
459 if (Visit(MakeMacroExpansionCursor(ME, TU)))
460 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000461
Guy Benyei11169dd2012-12-18 14:30:41 +0000462 continue;
463 }
Richard Smith66a81862015-05-04 02:25:31 +0000464
465 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000466 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
467 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000468
Guy Benyei11169dd2012-12-18 14:30:41 +0000469 continue;
470 }
471
472 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
473 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
474 return true;
475
476 continue;
477 }
478 }
479
480 return false;
481}
482
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000483/// Visit the children of the given cursor.
Guy Benyei11169dd2012-12-18 14:30:41 +0000484///
485/// \returns true if the visitation should be aborted, false if it
486/// should continue.
487bool CursorVisitor::VisitChildren(CXCursor Cursor) {
488 if (clang_isReference(Cursor.kind) &&
489 Cursor.kind != CXCursor_CXXBaseSpecifier) {
490 // By definition, references have no children.
491 return false;
492 }
493
494 // Set the Parent field to Cursor, then back to its old value once we're
495 // done.
496 SetParentRAII SetParent(Parent, StmtParent, Cursor);
497
498 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000499 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +0000500 if (!D)
501 return false;
502
503 return VisitAttributes(D) || Visit(D);
504 }
505
506 if (clang_isStatement(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000507 if (const Stmt *S = getCursorStmt(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000508 return Visit(S);
509
510 return false;
511 }
512
513 if (clang_isExpression(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000514 if (const Expr *E = getCursorExpr(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000515 return Visit(E);
516
517 return false;
518 }
519
520 if (clang_isTranslationUnit(Cursor.kind)) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000521 CXTranslationUnit TU = getCursorTU(Cursor);
522 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000523
524 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
525 for (unsigned I = 0; I != 2; ++I) {
526 if (VisitOrder[I]) {
527 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
528 RegionOfInterest.isInvalid()) {
529 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
530 TLEnd = CXXUnit->top_level_end();
531 TL != TLEnd; ++TL) {
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000532 const Optional<bool> V = handleDeclForVisitation(*TL);
533 if (!V.hasValue())
534 continue;
535 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000536 }
537 } else if (VisitDeclContext(
538 CXXUnit->getASTContext().getTranslationUnitDecl()))
539 return true;
540 continue;
541 }
542
543 // Walk the preprocessing record.
544 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
545 visitPreprocessedEntitiesInRegion();
546 }
547
548 return false;
549 }
550
551 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000552 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000553 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
554 return Visit(BaseTSInfo->getTypeLoc());
555 }
556 }
557 }
558
559 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +0000560 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +0000561 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
Richard Smithb1f9a282013-10-31 01:56:18 +0000562 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
Richard Smithb87c4652013-10-31 21:23:20 +0000563 return Visit(cxcursor::MakeCursorObjCClassRef(
564 ObjT->getInterface(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000565 A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +0000566 }
567
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000568 // If pointing inside a macro definition, check if the token is an identifier
569 // that was ever defined as a macro. In such a case, create a "pseudo" macro
570 // expansion cursor for that token.
571 SourceLocation BeginLoc = RegionOfInterest.getBegin();
572 if (Cursor.kind == CXCursor_MacroDefinition &&
573 BeginLoc == RegionOfInterest.getEnd()) {
574 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000575 const MacroInfo *MI =
576 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
Richard Smith66a81862015-05-04 02:25:31 +0000577 if (MacroDefinitionRecord *MacroDef =
578 checkForMacroInMacroDefinition(MI, Loc, TU))
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000579 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
580 }
581
Guy Benyei11169dd2012-12-18 14:30:41 +0000582 // Nothing to visit at the moment.
583 return false;
584}
585
586bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
587 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
588 if (Visit(TSInfo->getTypeLoc()))
589 return true;
590
591 if (Stmt *Body = B->getBody())
592 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
593
594 return false;
595}
596
Ted Kremenek03325582013-02-21 01:29:01 +0000597Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000598 if (RegionOfInterest.isValid()) {
599 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
600 if (Range.isInvalid())
David Blaikie7a30dc52013-02-21 01:47:18 +0000601 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000602
603 switch (CompareRegionOfInterest(Range)) {
604 case RangeBefore:
605 // This declaration comes before the region of interest; skip it.
David Blaikie7a30dc52013-02-21 01:47:18 +0000606 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000607
608 case RangeAfter:
609 // This declaration comes after the region of interest; we're done.
610 return false;
611
612 case RangeOverlap:
613 // This declaration overlaps the region of interest; visit it.
614 break;
615 }
616 }
617 return true;
618}
619
620bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
621 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
622
623 // FIXME: Eventually remove. This part of a hack to support proper
624 // iteration over all Decls contained lexically within an ObjC container.
625 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
626 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
627
628 for ( ; I != E; ++I) {
629 Decl *D = *I;
630 if (D->getLexicalDeclContext() != DC)
631 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000632 const Optional<bool> V = handleDeclForVisitation(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000633 if (!V.hasValue())
634 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000635 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000636 }
637 return false;
638}
639
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000640Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
641 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
642
643 // Ignore synthesized ivars here, otherwise if we have something like:
644 // @synthesize prop = _prop;
645 // and '_prop' is not declared, we will encounter a '_prop' ivar before
646 // encountering the 'prop' synthesize declaration and we will think that
647 // we passed the region-of-interest.
648 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
649 if (ivarD->getSynthesize())
650 return None;
651 }
652
653 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
654 // declarations is a mismatch with the compiler semantics.
655 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
656 auto *ID = cast<ObjCInterfaceDecl>(D);
657 if (!ID->isThisDeclarationADefinition())
658 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
659
660 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
661 auto *PD = cast<ObjCProtocolDecl>(D);
662 if (!PD->isThisDeclarationADefinition())
663 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
664 }
665
666 const Optional<bool> V = shouldVisitCursor(Cursor);
667 if (!V.hasValue())
668 return None;
669 if (!V.getValue())
670 return false;
671 if (Visit(Cursor, true))
672 return true;
673 return None;
674}
675
Guy Benyei11169dd2012-12-18 14:30:41 +0000676bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
677 llvm_unreachable("Translation units are visited directly by Visit()");
678}
679
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +0000680bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
681 if (VisitTemplateParameters(D->getTemplateParameters()))
682 return true;
683
684 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
685}
686
Guy Benyei11169dd2012-12-18 14:30:41 +0000687bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
688 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
689 return Visit(TSInfo->getTypeLoc());
690
691 return false;
692}
693
694bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
695 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
696 return Visit(TSInfo->getTypeLoc());
697
698 return false;
699}
700
701bool CursorVisitor::VisitTagDecl(TagDecl *D) {
702 return VisitDeclContext(D);
703}
704
705bool CursorVisitor::VisitClassTemplateSpecializationDecl(
706 ClassTemplateSpecializationDecl *D) {
707 bool ShouldVisitBody = false;
708 switch (D->getSpecializationKind()) {
709 case TSK_Undeclared:
710 case TSK_ImplicitInstantiation:
711 // Nothing to visit
712 return false;
713
714 case TSK_ExplicitInstantiationDeclaration:
715 case TSK_ExplicitInstantiationDefinition:
716 break;
717
718 case TSK_ExplicitSpecialization:
719 ShouldVisitBody = true;
720 break;
721 }
722
723 // Visit the template arguments used in the specialization.
724 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
725 TypeLoc TL = SpecType->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +0000726 if (TemplateSpecializationTypeLoc TSTLoc =
727 TL.getAs<TemplateSpecializationTypeLoc>()) {
728 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
729 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000730 return true;
731 }
732 }
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000733
734 return ShouldVisitBody && VisitCXXRecordDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000735}
736
737bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
738 ClassTemplatePartialSpecializationDecl *D) {
739 // FIXME: Visit the "outer" template parameter lists on the TagDecl
740 // before visiting these template parameters.
741 if (VisitTemplateParameters(D->getTemplateParameters()))
742 return true;
743
744 // Visit the partial specialization arguments.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +0000745 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
746 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
747 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +0000748 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
749 return true;
750
751 return VisitCXXRecordDecl(D);
752}
753
754bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
755 // Visit the default argument.
756 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
757 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
758 if (Visit(DefArg->getTypeLoc()))
759 return true;
760
761 return false;
762}
763
764bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
765 if (Expr *Init = D->getInitExpr())
766 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
767 return false;
768}
769
770bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000771 unsigned NumParamList = DD->getNumTemplateParameterLists();
772 for (unsigned i = 0; i < NumParamList; i++) {
773 TemplateParameterList* Params = DD->getTemplateParameterList(i);
774 if (VisitTemplateParameters(Params))
775 return true;
776 }
777
Guy Benyei11169dd2012-12-18 14:30:41 +0000778 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
779 if (Visit(TSInfo->getTypeLoc()))
780 return true;
781
782 // Visit the nested-name-specifier, if present.
783 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
784 if (VisitNestedNameSpecifierLoc(QualifierLoc))
785 return true;
786
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000787 return false;
788}
789
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000790static bool HasTrailingReturnType(FunctionDecl *ND) {
791 const QualType Ty = ND->getType();
792 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
793 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT))
794 return FT->hasTrailingReturn();
795 }
796
797 return false;
798}
799
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000800/// Compare two base or member initializers based on their source order.
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000801static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
802 CXXCtorInitializer *const *Y) {
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000803 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
804}
805
Guy Benyei11169dd2012-12-18 14:30:41 +0000806bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000807 unsigned NumParamList = ND->getNumTemplateParameterLists();
808 for (unsigned i = 0; i < NumParamList; i++) {
809 TemplateParameterList* Params = ND->getTemplateParameterList(i);
810 if (VisitTemplateParameters(Params))
811 return true;
812 }
813
Guy Benyei11169dd2012-12-18 14:30:41 +0000814 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
815 // Visit the function declaration's syntactic components in the order
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000816 // written. This requires a bit of work.
817 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
818 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000819 const bool HasTrailingRT = HasTrailingReturnType(ND);
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000820
821 // If we have a function declared directly (without the use of a typedef),
822 // visit just the return type. Otherwise, just visit the function's type
823 // now.
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000824 if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT &&
825 Visit(FTL.getReturnLoc())) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000826 (!FTL && Visit(TL)))
827 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000828
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000829 // Visit the nested-name-specifier, if present.
830 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
831 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Guy Benyei11169dd2012-12-18 14:30:41 +0000832 return true;
833
834 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000835 if (!isa<CXXDestructorDecl>(ND))
836 if (VisitDeclarationNameInfo(ND->getNameInfo()))
837 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000838
839 // FIXME: Visit explicitly-specified template arguments!
840
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000841 // Visit the function parameters, if we have a function type.
842 if (FTL && VisitFunctionTypeLoc(FTL, true))
843 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000844
845 // Visit the function's trailing return type.
846 if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc()))
847 return true;
848
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000849 // FIXME: Attributes?
850 }
851
Guy Benyei11169dd2012-12-18 14:30:41 +0000852 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
853 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
854 // Find the initializers that were written in the source.
855 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000856 for (auto *I : Constructor->inits()) {
857 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000858 continue;
859
Aaron Ballman0ad78302014-03-13 17:34:31 +0000860 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000861 }
862
863 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000864 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
865 &CompareCXXCtorInitializers);
866
Guy Benyei11169dd2012-12-18 14:30:41 +0000867 // Visit the initializers in source order
868 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
869 CXXCtorInitializer *Init = WrittenInits[I];
870 if (Init->isAnyMemberInitializer()) {
871 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
872 Init->getMemberLocation(), TU)))
873 return true;
874 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
875 if (Visit(TInfo->getTypeLoc()))
876 return true;
877 }
878
879 // Visit the initializer value.
880 if (Expr *Initializer = Init->getInit())
881 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
882 return true;
883 }
884 }
885
886 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
887 return true;
888 }
889
890 return false;
891}
892
893bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
894 if (VisitDeclaratorDecl(D))
895 return true;
896
897 if (Expr *BitWidth = D->getBitWidth())
898 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
899
Benjamin Kramer99f97592017-11-15 12:20:41 +0000900 if (Expr *Init = D->getInClassInitializer())
901 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
902
Guy Benyei11169dd2012-12-18 14:30:41 +0000903 return false;
904}
905
906bool CursorVisitor::VisitVarDecl(VarDecl *D) {
907 if (VisitDeclaratorDecl(D))
908 return true;
909
910 if (Expr *Init = D->getInit())
911 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
912
913 return false;
914}
915
916bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
917 if (VisitDeclaratorDecl(D))
918 return true;
919
920 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
921 if (Expr *DefArg = D->getDefaultArgument())
922 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
923
924 return false;
925}
926
927bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
928 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
929 // before visiting these template parameters.
930 if (VisitTemplateParameters(D->getTemplateParameters()))
931 return true;
932
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000933 auto* FD = D->getTemplatedDecl();
934 return VisitAttributes(FD) || VisitFunctionDecl(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000935}
936
937bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
938 // FIXME: Visit the "outer" template parameter lists on the TagDecl
939 // before visiting these template parameters.
940 if (VisitTemplateParameters(D->getTemplateParameters()))
941 return true;
942
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000943 auto* CD = D->getTemplatedDecl();
944 return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000945}
946
947bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
948 if (VisitTemplateParameters(D->getTemplateParameters()))
949 return true;
950
951 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
952 VisitTemplateArgumentLoc(D->getDefaultArgument()))
953 return true;
954
955 return false;
956}
957
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000958bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
959 // Visit the bound, if it's explicit.
960 if (D->hasExplicitBound()) {
961 if (auto TInfo = D->getTypeSourceInfo()) {
962 if (Visit(TInfo->getTypeLoc()))
963 return true;
964 }
965 }
966
967 return false;
968}
969
Guy Benyei11169dd2012-12-18 14:30:41 +0000970bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000971 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000972 if (Visit(TSInfo->getTypeLoc()))
973 return true;
974
David Majnemer59f77922016-06-24 04:05:48 +0000975 for (const auto *P : ND->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000976 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000977 return true;
978 }
979
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000980 return ND->isThisDeclarationADefinition() &&
981 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000982}
983
984template <typename DeclIt>
985static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
986 SourceManager &SM, SourceLocation EndLoc,
987 SmallVectorImpl<Decl *> &Decls) {
988 DeclIt next = *DI_current;
989 while (++next != DE_current) {
990 Decl *D_next = *next;
991 if (!D_next)
992 break;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000993 SourceLocation L = D_next->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +0000994 if (!L.isValid())
995 break;
996 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
997 *DI_current = next;
998 Decls.push_back(D_next);
999 continue;
1000 }
1001 break;
1002 }
1003}
1004
Guy Benyei11169dd2012-12-18 14:30:41 +00001005bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
1006 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
1007 // an @implementation can lexically contain Decls that are not properly
1008 // nested in the AST. When we identify such cases, we need to retrofit
1009 // this nesting here.
1010 if (!DI_current && !FileDI_current)
1011 return VisitDeclContext(D);
1012
1013 // Scan the Decls that immediately come after the container
1014 // in the current DeclContext. If any fall within the
1015 // container's lexical region, stash them into a vector
1016 // for later processing.
1017 SmallVector<Decl *, 24> DeclsInContainer;
1018 SourceLocation EndLoc = D->getSourceRange().getEnd();
1019 SourceManager &SM = AU->getSourceManager();
1020 if (EndLoc.isValid()) {
1021 if (DI_current) {
1022 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
1023 DeclsInContainer);
1024 } else {
1025 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1026 DeclsInContainer);
1027 }
1028 }
1029
1030 // The common case.
1031 if (DeclsInContainer.empty())
1032 return VisitDeclContext(D);
1033
1034 // Get all the Decls in the DeclContext, and sort them with the
1035 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +00001036 for (auto *SubDecl : D->decls()) {
1037 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001038 SubDecl->getBeginLoc().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001039 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001040 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001041 }
1042
1043 // Now sort the Decls so that they appear in lexical order.
Fangrui Song55fab262018-09-26 22:16:28 +00001044 llvm::sort(DeclsInContainer,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001045 [&SM](Decl *A, Decl *B) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001046 SourceLocation L_A = A->getBeginLoc();
1047 SourceLocation L_B = B->getBeginLoc();
1048 return L_A != L_B ? SM.isBeforeInTranslationUnit(L_A, L_B)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001049 : SM.isBeforeInTranslationUnit(A->getEndLoc(),
1050 B->getEndLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001051 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001052
1053 // Now visit the decls.
1054 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1055 E = DeclsInContainer.end(); I != E; ++I) {
1056 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001057 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001058 if (!V.hasValue())
1059 continue;
1060 if (!V.getValue())
1061 return false;
1062 if (Visit(Cursor, true))
1063 return true;
1064 }
1065 return false;
1066}
1067
1068bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1069 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1070 TU)))
1071 return true;
1072
Douglas Gregore9d95f12015-07-07 03:57:35 +00001073 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1074 return true;
1075
Guy Benyei11169dd2012-12-18 14:30:41 +00001076 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1077 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1078 E = ND->protocol_end(); I != E; ++I, ++PL)
1079 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1080 return true;
1081
1082 return VisitObjCContainerDecl(ND);
1083}
1084
1085bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1086 if (!PID->isThisDeclarationADefinition())
1087 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1088
1089 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1090 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1091 E = PID->protocol_end(); I != E; ++I, ++PL)
1092 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1093 return true;
1094
1095 return VisitObjCContainerDecl(PID);
1096}
1097
1098bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1099 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1100 return true;
1101
1102 // FIXME: This implements a workaround with @property declarations also being
1103 // installed in the DeclContext for the @interface. Eventually this code
1104 // should be removed.
1105 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1106 if (!CDecl || !CDecl->IsClassExtension())
1107 return false;
1108
1109 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1110 if (!ID)
1111 return false;
1112
1113 IdentifierInfo *PropertyId = PD->getIdentifier();
1114 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001115 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1116 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001117
1118 if (!prevDecl)
1119 return false;
1120
1121 // Visit synthesized methods since they will be skipped when visiting
1122 // the @interface.
1123 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1124 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1125 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1126 return true;
1127
1128 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1129 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1130 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1131 return true;
1132
1133 return false;
1134}
1135
Douglas Gregore9d95f12015-07-07 03:57:35 +00001136bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1137 if (!typeParamList)
1138 return false;
1139
1140 for (auto *typeParam : *typeParamList) {
1141 // Visit the type parameter.
1142 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1143 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001144 }
1145
1146 return false;
1147}
1148
Guy Benyei11169dd2012-12-18 14:30:41 +00001149bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1150 if (!D->isThisDeclarationADefinition()) {
1151 // Forward declaration is treated like a reference.
1152 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1153 }
1154
Douglas Gregore9d95f12015-07-07 03:57:35 +00001155 // Objective-C type parameters.
1156 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1157 return true;
1158
Guy Benyei11169dd2012-12-18 14:30:41 +00001159 // Issue callbacks for super class.
1160 if (D->getSuperClass() &&
1161 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1162 D->getSuperClassLoc(),
1163 TU)))
1164 return true;
1165
Douglas Gregore9d95f12015-07-07 03:57:35 +00001166 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1167 if (Visit(SuperClassTInfo->getTypeLoc()))
1168 return true;
1169
Guy Benyei11169dd2012-12-18 14:30:41 +00001170 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1171 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1172 E = D->protocol_end(); I != E; ++I, ++PL)
1173 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1174 return true;
1175
1176 return VisitObjCContainerDecl(D);
1177}
1178
1179bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1180 return VisitObjCContainerDecl(D);
1181}
1182
1183bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1184 // 'ID' could be null when dealing with invalid code.
1185 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1186 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1187 return true;
1188
1189 return VisitObjCImplDecl(D);
1190}
1191
1192bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1193#if 0
1194 // Issue callbacks for super class.
1195 // FIXME: No source location information!
1196 if (D->getSuperClass() &&
1197 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1198 D->getSuperClassLoc(),
1199 TU)))
1200 return true;
1201#endif
1202
1203 return VisitObjCImplDecl(D);
1204}
1205
1206bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1207 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1208 if (PD->isIvarNameSpecified())
1209 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1210
1211 return false;
1212}
1213
1214bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1215 return VisitDeclContext(D);
1216}
1217
1218bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1219 // Visit nested-name-specifier.
1220 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1221 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1222 return true;
1223
1224 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1225 D->getTargetNameLoc(), TU));
1226}
1227
1228bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1229 // Visit nested-name-specifier.
1230 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1231 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1232 return true;
1233 }
1234
1235 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1236 return true;
1237
1238 return VisitDeclarationNameInfo(D->getNameInfo());
1239}
1240
1241bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1242 // Visit nested-name-specifier.
1243 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1244 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1245 return true;
1246
1247 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1248 D->getIdentLocation(), TU));
1249}
1250
1251bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1252 // Visit nested-name-specifier.
1253 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1254 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1255 return true;
1256 }
1257
1258 return VisitDeclarationNameInfo(D->getNameInfo());
1259}
1260
1261bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1262 UnresolvedUsingTypenameDecl *D) {
1263 // Visit nested-name-specifier.
1264 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1265 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1266 return true;
1267
1268 return false;
1269}
1270
Olivier Goffart81978012016-06-09 16:15:55 +00001271bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1272 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1273 return true;
Richard Trieuf3b77662016-09-13 01:37:01 +00001274 if (StringLiteral *Message = D->getMessage())
1275 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1276 return true;
Olivier Goffart81978012016-06-09 16:15:55 +00001277 return false;
1278}
1279
Olivier Goffartd211c642016-11-04 06:29:27 +00001280bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1281 if (NamedDecl *FriendD = D->getFriendDecl()) {
1282 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1283 return true;
1284 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1285 if (Visit(TI->getTypeLoc()))
1286 return true;
1287 }
1288 return false;
1289}
1290
Guy Benyei11169dd2012-12-18 14:30:41 +00001291bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1292 switch (Name.getName().getNameKind()) {
1293 case clang::DeclarationName::Identifier:
1294 case clang::DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001295 case clang::DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001296 case clang::DeclarationName::CXXOperatorName:
1297 case clang::DeclarationName::CXXUsingDirective:
1298 return false;
Richard Smith35845152017-02-07 01:37:30 +00001299
Guy Benyei11169dd2012-12-18 14:30:41 +00001300 case clang::DeclarationName::CXXConstructorName:
1301 case clang::DeclarationName::CXXDestructorName:
1302 case clang::DeclarationName::CXXConversionFunctionName:
1303 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1304 return Visit(TSInfo->getTypeLoc());
1305 return false;
1306
1307 case clang::DeclarationName::ObjCZeroArgSelector:
1308 case clang::DeclarationName::ObjCOneArgSelector:
1309 case clang::DeclarationName::ObjCMultiArgSelector:
1310 // FIXME: Per-identifier location info?
1311 return false;
1312 }
1313
1314 llvm_unreachable("Invalid DeclarationName::Kind!");
1315}
1316
1317bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1318 SourceRange Range) {
1319 // FIXME: This whole routine is a hack to work around the lack of proper
1320 // source information in nested-name-specifiers (PR5791). Since we do have
1321 // a beginning source location, we can visit the first component of the
1322 // nested-name-specifier, if it's a single-token component.
1323 if (!NNS)
1324 return false;
1325
1326 // Get the first component in the nested-name-specifier.
1327 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1328 NNS = Prefix;
1329
1330 switch (NNS->getKind()) {
1331 case NestedNameSpecifier::Namespace:
1332 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1333 TU));
1334
1335 case NestedNameSpecifier::NamespaceAlias:
1336 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1337 Range.getBegin(), TU));
1338
1339 case NestedNameSpecifier::TypeSpec: {
1340 // If the type has a form where we know that the beginning of the source
1341 // range matches up with a reference cursor. Visit the appropriate reference
1342 // cursor.
1343 const Type *T = NNS->getAsType();
1344 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1345 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1346 if (const TagType *Tag = dyn_cast<TagType>(T))
1347 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1348 if (const TemplateSpecializationType *TST
1349 = dyn_cast<TemplateSpecializationType>(T))
1350 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1351 break;
1352 }
1353
1354 case NestedNameSpecifier::TypeSpecWithTemplate:
1355 case NestedNameSpecifier::Global:
1356 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001357 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001358 break;
1359 }
1360
1361 return false;
1362}
1363
1364bool
1365CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1366 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1367 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1368 Qualifiers.push_back(Qualifier);
1369
1370 while (!Qualifiers.empty()) {
1371 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1372 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1373 switch (NNS->getKind()) {
1374 case NestedNameSpecifier::Namespace:
1375 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1376 Q.getLocalBeginLoc(),
1377 TU)))
1378 return true;
1379
1380 break;
1381
1382 case NestedNameSpecifier::NamespaceAlias:
1383 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1384 Q.getLocalBeginLoc(),
1385 TU)))
1386 return true;
1387
1388 break;
1389
1390 case NestedNameSpecifier::TypeSpec:
1391 case NestedNameSpecifier::TypeSpecWithTemplate:
1392 if (Visit(Q.getTypeLoc()))
1393 return true;
1394
1395 break;
1396
1397 case NestedNameSpecifier::Global:
1398 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001399 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001400 break;
1401 }
1402 }
1403
1404 return false;
1405}
1406
1407bool CursorVisitor::VisitTemplateParameters(
1408 const TemplateParameterList *Params) {
1409 if (!Params)
1410 return false;
1411
1412 for (TemplateParameterList::const_iterator P = Params->begin(),
1413 PEnd = Params->end();
1414 P != PEnd; ++P) {
1415 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1416 return true;
1417 }
1418
1419 return false;
1420}
1421
1422bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1423 switch (Name.getKind()) {
1424 case TemplateName::Template:
1425 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1426
1427 case TemplateName::OverloadedTemplate:
1428 // Visit the overloaded template set.
1429 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1430 return true;
1431
1432 return false;
1433
1434 case TemplateName::DependentTemplate:
1435 // FIXME: Visit nested-name-specifier.
1436 return false;
1437
1438 case TemplateName::QualifiedTemplate:
1439 // FIXME: Visit nested-name-specifier.
1440 return Visit(MakeCursorTemplateRef(
1441 Name.getAsQualifiedTemplateName()->getDecl(),
1442 Loc, TU));
1443
1444 case TemplateName::SubstTemplateTemplateParm:
1445 return Visit(MakeCursorTemplateRef(
1446 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1447 Loc, TU));
1448
1449 case TemplateName::SubstTemplateTemplateParmPack:
1450 return Visit(MakeCursorTemplateRef(
1451 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1452 Loc, TU));
1453 }
1454
1455 llvm_unreachable("Invalid TemplateName::Kind!");
1456}
1457
1458bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1459 switch (TAL.getArgument().getKind()) {
1460 case TemplateArgument::Null:
1461 case TemplateArgument::Integral:
1462 case TemplateArgument::Pack:
1463 return false;
1464
1465 case TemplateArgument::Type:
1466 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1467 return Visit(TSInfo->getTypeLoc());
1468 return false;
1469
1470 case TemplateArgument::Declaration:
1471 if (Expr *E = TAL.getSourceDeclExpression())
1472 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1473 return false;
1474
1475 case TemplateArgument::NullPtr:
1476 if (Expr *E = TAL.getSourceNullPtrExpression())
1477 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1478 return false;
1479
1480 case TemplateArgument::Expression:
1481 if (Expr *E = TAL.getSourceExpression())
1482 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1483 return false;
1484
1485 case TemplateArgument::Template:
1486 case TemplateArgument::TemplateExpansion:
1487 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1488 return true;
1489
1490 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1491 TAL.getTemplateNameLoc());
1492 }
1493
1494 llvm_unreachable("Invalid TemplateArgument::Kind!");
1495}
1496
1497bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1498 return VisitDeclContext(D);
1499}
1500
1501bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1502 return Visit(TL.getUnqualifiedLoc());
1503}
1504
1505bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1506 ASTContext &Context = AU->getASTContext();
1507
1508 // Some builtin types (such as Objective-C's "id", "sel", and
1509 // "Class") have associated declarations. Create cursors for those.
1510 QualType VisitType;
1511 switch (TL.getTypePtr()->getKind()) {
1512
1513 case BuiltinType::Void:
1514 case BuiltinType::NullPtr:
1515 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001516#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1517 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001518#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001519#define EXT_OPAQUE_TYPE(ExtTYpe, Id, Ext) \
1520 case BuiltinType::Id:
1521#include "clang/Basic/OpenCLExtensionTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001522 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001523 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001524 case BuiltinType::OCLClkEvent:
1525 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001526 case BuiltinType::OCLReserveID:
Guy Benyei11169dd2012-12-18 14:30:41 +00001527#define BUILTIN_TYPE(Id, SingletonId)
1528#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1529#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1530#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1531#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1532#include "clang/AST/BuiltinTypes.def"
1533 break;
1534
1535 case BuiltinType::ObjCId:
1536 VisitType = Context.getObjCIdType();
1537 break;
1538
1539 case BuiltinType::ObjCClass:
1540 VisitType = Context.getObjCClassType();
1541 break;
1542
1543 case BuiltinType::ObjCSel:
1544 VisitType = Context.getObjCSelType();
1545 break;
1546 }
1547
1548 if (!VisitType.isNull()) {
1549 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1550 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1551 TU));
1552 }
1553
1554 return false;
1555}
1556
1557bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1558 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1559}
1560
1561bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1562 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1563}
1564
1565bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1566 if (TL.isDefinition())
1567 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1568
1569 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1570}
1571
1572bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1573 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1574}
1575
1576bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001577 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001578}
1579
Manman Rene6be26c2016-09-13 17:25:08 +00001580bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001581 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getBeginLoc(), TU)))
Manman Rene6be26c2016-09-13 17:25:08 +00001582 return true;
1583 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1584 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1585 TU)))
1586 return true;
1587 }
1588
1589 return false;
1590}
1591
Guy Benyei11169dd2012-12-18 14:30:41 +00001592bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1593 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1594 return true;
1595
Douglas Gregore9d95f12015-07-07 03:57:35 +00001596 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1597 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1598 return true;
1599 }
1600
Guy Benyei11169dd2012-12-18 14:30:41 +00001601 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1602 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1603 TU)))
1604 return true;
1605 }
1606
1607 return false;
1608}
1609
1610bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1611 return Visit(TL.getPointeeLoc());
1612}
1613
1614bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1615 return Visit(TL.getInnerLoc());
1616}
1617
1618bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1619 return Visit(TL.getPointeeLoc());
1620}
1621
1622bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1623 return Visit(TL.getPointeeLoc());
1624}
1625
1626bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1627 return Visit(TL.getPointeeLoc());
1628}
1629
1630bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1631 return Visit(TL.getPointeeLoc());
1632}
1633
1634bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1635 return Visit(TL.getPointeeLoc());
1636}
1637
1638bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1639 return Visit(TL.getModifiedLoc());
1640}
1641
1642bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1643 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001644 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001645 return true;
1646
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001647 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1648 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001649 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1650 return true;
1651
1652 return false;
1653}
1654
1655bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1656 if (Visit(TL.getElementLoc()))
1657 return true;
1658
1659 if (Expr *Size = TL.getSizeExpr())
1660 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1661
1662 return false;
1663}
1664
Reid Kleckner8a365022013-06-24 17:51:48 +00001665bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1666 return Visit(TL.getOriginalLoc());
1667}
1668
Reid Kleckner0503a872013-12-05 01:23:43 +00001669bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1670 return Visit(TL.getOriginalLoc());
1671}
1672
Richard Smith600b5262017-01-26 20:40:47 +00001673bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1674 DeducedTemplateSpecializationTypeLoc TL) {
1675 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1676 TL.getTemplateNameLoc()))
1677 return true;
1678
1679 return false;
1680}
1681
Guy Benyei11169dd2012-12-18 14:30:41 +00001682bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1683 TemplateSpecializationTypeLoc TL) {
1684 // Visit the template name.
1685 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1686 TL.getTemplateNameLoc()))
1687 return true;
1688
1689 // Visit the template arguments.
1690 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1691 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1692 return true;
1693
1694 return false;
1695}
1696
1697bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1698 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1699}
1700
1701bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1702 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1703 return Visit(TSInfo->getTypeLoc());
1704
1705 return false;
1706}
1707
1708bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1709 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1710 return Visit(TSInfo->getTypeLoc());
1711
1712 return false;
1713}
1714
1715bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001716 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001717}
1718
1719bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1720 DependentTemplateSpecializationTypeLoc TL) {
1721 // Visit the nested-name-specifier, if there is one.
1722 if (TL.getQualifierLoc() &&
1723 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1724 return true;
1725
1726 // Visit the template arguments.
1727 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1728 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1729 return true;
1730
1731 return false;
1732}
1733
1734bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1735 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1736 return true;
1737
1738 return Visit(TL.getNamedTypeLoc());
1739}
1740
1741bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1742 return Visit(TL.getPatternLoc());
1743}
1744
1745bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1746 if (Expr *E = TL.getUnderlyingExpr())
1747 return Visit(MakeCXCursor(E, StmtParent, TU));
1748
1749 return false;
1750}
1751
1752bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1753 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1754}
1755
1756bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1757 return Visit(TL.getValueLoc());
1758}
1759
Xiuli Pan9c14e282016-01-09 12:53:17 +00001760bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1761 return Visit(TL.getValueLoc());
1762}
1763
Guy Benyei11169dd2012-12-18 14:30:41 +00001764#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1765bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1766 return Visit##PARENT##Loc(TL); \
1767}
1768
1769DEFAULT_TYPELOC_IMPL(Complex, Type)
1770DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1771DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1772DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1773DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001774DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
Erich Keanef702b022018-07-13 19:46:04 +00001775DEFAULT_TYPELOC_IMPL(DependentVector, Type)
Guy Benyei11169dd2012-12-18 14:30:41 +00001776DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1777DEFAULT_TYPELOC_IMPL(Vector, Type)
1778DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1779DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1780DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1781DEFAULT_TYPELOC_IMPL(Record, TagType)
1782DEFAULT_TYPELOC_IMPL(Enum, TagType)
1783DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1784DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1785DEFAULT_TYPELOC_IMPL(Auto, Type)
1786
1787bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1788 // Visit the nested-name-specifier, if present.
1789 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1790 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1791 return true;
1792
1793 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001794 for (const auto &I : D->bases()) {
1795 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001796 return true;
1797 }
1798 }
1799
1800 return VisitTagDecl(D);
1801}
1802
1803bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001804 for (const auto *I : D->attrs())
Michael Wu40ff1052018-08-03 05:20:23 +00001805 if ((TU->ParsingOptions & CXTranslationUnit_VisitImplicitAttributes ||
1806 !I->isImplicit()) &&
1807 Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001808 return true;
1809
1810 return false;
1811}
1812
1813//===----------------------------------------------------------------------===//
1814// Data-recursive visitor methods.
1815//===----------------------------------------------------------------------===//
1816
1817namespace {
1818#define DEF_JOB(NAME, DATA, KIND)\
1819class NAME : public VisitorJob {\
1820public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001821 NAME(const DATA *d, CXCursor parent) : \
1822 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001823 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001824 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001825};
1826
1827DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1828DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1829DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1830DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001831DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1832DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1833DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1834#undef DEF_JOB
1835
James Y Knight04ec5bf2015-12-24 02:59:37 +00001836class ExplicitTemplateArgsVisit : public VisitorJob {
1837public:
1838 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1839 const TemplateArgumentLoc *End, CXCursor parent)
1840 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1841 End) {}
1842 static bool classof(const VisitorJob *VJ) {
1843 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1844 }
1845 const TemplateArgumentLoc *begin() const {
1846 return static_cast<const TemplateArgumentLoc *>(data[0]);
1847 }
1848 const TemplateArgumentLoc *end() {
1849 return static_cast<const TemplateArgumentLoc *>(data[1]);
1850 }
1851};
Guy Benyei11169dd2012-12-18 14:30:41 +00001852class DeclVisit : public VisitorJob {
1853public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001854 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001855 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001856 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001857 static bool classof(const VisitorJob *VJ) {
1858 return VJ->getKind() == DeclVisitKind;
1859 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001860 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001861 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001862};
1863class TypeLocVisit : public VisitorJob {
1864public:
1865 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1866 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1867 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1868
1869 static bool classof(const VisitorJob *VJ) {
1870 return VJ->getKind() == TypeLocVisitKind;
1871 }
1872
1873 TypeLoc get() const {
1874 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001875 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001876 }
1877};
1878
1879class LabelRefVisit : public VisitorJob {
1880public:
1881 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1882 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1883 labelLoc.getPtrEncoding()) {}
1884
1885 static bool classof(const VisitorJob *VJ) {
1886 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1887 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001888 const LabelDecl *get() const {
1889 return static_cast<const LabelDecl *>(data[0]);
1890 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001891 SourceLocation getLoc() const {
1892 return SourceLocation::getFromPtrEncoding(data[1]); }
1893};
1894
1895class NestedNameSpecifierLocVisit : public VisitorJob {
1896public:
1897 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1898 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1899 Qualifier.getNestedNameSpecifier(),
1900 Qualifier.getOpaqueData()) { }
1901
1902 static bool classof(const VisitorJob *VJ) {
1903 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1904 }
1905
1906 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001907 return NestedNameSpecifierLoc(
1908 const_cast<NestedNameSpecifier *>(
1909 static_cast<const NestedNameSpecifier *>(data[0])),
1910 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001911 }
1912};
1913
1914class DeclarationNameInfoVisit : public VisitorJob {
1915public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001916 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001917 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001918 static bool classof(const VisitorJob *VJ) {
1919 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1920 }
1921 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001922 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001923 switch (S->getStmtClass()) {
1924 default:
1925 llvm_unreachable("Unhandled Stmt");
1926 case clang::Stmt::MSDependentExistsStmtClass:
1927 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1928 case Stmt::CXXDependentScopeMemberExprClass:
1929 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1930 case Stmt::DependentScopeDeclRefExprClass:
1931 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001932 case Stmt::OMPCriticalDirectiveClass:
1933 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001934 }
1935 }
1936};
1937class MemberRefVisit : public VisitorJob {
1938public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001939 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001940 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1941 L.getPtrEncoding()) {}
1942 static bool classof(const VisitorJob *VJ) {
1943 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1944 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001945 const FieldDecl *get() const {
1946 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001947 }
1948 SourceLocation getLoc() const {
1949 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1950 }
1951};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001952class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001953 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001954 VisitorWorkList &WL;
1955 CXCursor Parent;
1956public:
1957 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1958 : WL(wl), Parent(parent) {}
1959
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001960 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1961 void VisitBlockExpr(const BlockExpr *B);
1962 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1963 void VisitCompoundStmt(const CompoundStmt *S);
1964 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1965 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1966 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1967 void VisitCXXNewExpr(const CXXNewExpr *E);
1968 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1969 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1970 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1971 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1972 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1973 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1974 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1975 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001976 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001977 void VisitDeclRefExpr(const DeclRefExpr *D);
1978 void VisitDeclStmt(const DeclStmt *S);
1979 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1980 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1981 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1982 void VisitForStmt(const ForStmt *FS);
1983 void VisitGotoStmt(const GotoStmt *GS);
1984 void VisitIfStmt(const IfStmt *If);
1985 void VisitInitListExpr(const InitListExpr *IE);
1986 void VisitMemberExpr(const MemberExpr *M);
1987 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1988 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1989 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1990 void VisitOverloadExpr(const OverloadExpr *E);
1991 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1992 void VisitStmt(const Stmt *S);
1993 void VisitSwitchStmt(const SwitchStmt *S);
1994 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001995 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1996 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1997 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1998 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1999 void VisitVAArgExpr(const VAArgExpr *E);
2000 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
2001 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
2002 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
2003 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002004 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00002005 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002006 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002007 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002008 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002009 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002010 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002011 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002012 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00002013 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002014 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002015 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002016 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002017 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002018 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00002019 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002020 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00002021 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002022 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002023 void
2024 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00002025 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00002026 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002027 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00002028 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002029 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00002030 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00002031 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00002032 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002033 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002034 void
2035 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002036 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002037 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002038 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002039 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002040 void VisitOMPDistributeParallelForDirective(
2041 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00002042 void VisitOMPDistributeParallelForSimdDirective(
2043 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002044 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002045 void VisitOMPTargetParallelForSimdDirective(
2046 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002047 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002048 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002049 void VisitOMPTeamsDistributeSimdDirective(
2050 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002051 void VisitOMPTeamsDistributeParallelForSimdDirective(
2052 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002053 void VisitOMPTeamsDistributeParallelForDirective(
2054 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002055 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002056 void VisitOMPTargetTeamsDistributeDirective(
2057 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002058 void VisitOMPTargetTeamsDistributeParallelForDirective(
2059 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002060 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2061 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002062 void VisitOMPTargetTeamsDistributeSimdDirective(
2063 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002064
Guy Benyei11169dd2012-12-18 14:30:41 +00002065private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002066 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002067 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002068 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2069 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002070 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2071 void AddStmt(const Stmt *S);
2072 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002073 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002074 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002075 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002076};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002077} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002078
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002079void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002080 // 'S' should always be non-null, since it comes from the
2081 // statement we are visiting.
2082 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2083}
2084
2085void
2086EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2087 if (Qualifier)
2088 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2089}
2090
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002091void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002092 if (S)
2093 WL.push_back(StmtVisit(S, Parent));
2094}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002095void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002096 if (D)
2097 WL.push_back(DeclVisit(D, Parent, isFirst));
2098}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002099void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2100 unsigned NumTemplateArgs) {
2101 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002102}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002103void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002104 if (D)
2105 WL.push_back(MemberRefVisit(D, L, Parent));
2106}
2107void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2108 if (TI)
2109 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2110 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002111void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002112 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002113 for (const Stmt *SubStmt : S->children()) {
2114 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002115 }
2116 if (size == WL.size())
2117 return;
2118 // Now reverse the entries we just added. This will match the DFS
2119 // ordering performed by the worklist.
2120 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2121 std::reverse(I, E);
2122}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002123namespace {
2124class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2125 EnqueueVisitor *Visitor;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002126 /// Process clauses with list of variables.
Alexey Bataev756c1962013-09-24 03:17:45 +00002127 template <typename T>
2128 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002129public:
2130 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2131#define OPENMP_CLAUSE(Name, Class) \
2132 void Visit##Class(const Class *C);
Roman Lebedev23019f92019-01-28 17:04:11 +00002133 OPENMP_CLAUSE(flush, OMPFlushClause)
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002134#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002135 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002136 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002137};
2138
Alexey Bataev3392d762016-02-16 11:18:12 +00002139void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2140 const OMPClauseWithPreInit *C) {
2141 Visitor->AddStmt(C->getPreInitStmt());
2142}
2143
Alexey Bataev005248a2016-02-25 05:25:57 +00002144void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2145 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002146 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002147 Visitor->AddStmt(C->getPostUpdateExpr());
2148}
2149
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002150void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002151 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002152 Visitor->AddStmt(C->getCondition());
2153}
2154
Alexey Bataev3778b602014-07-17 07:32:53 +00002155void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2156 Visitor->AddStmt(C->getCondition());
2157}
2158
Alexey Bataev568a8332014-03-06 06:15:19 +00002159void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002160 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002161 Visitor->AddStmt(C->getNumThreads());
2162}
2163
Alexey Bataev62c87d22014-03-21 04:51:18 +00002164void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2165 Visitor->AddStmt(C->getSafelen());
2166}
2167
Alexey Bataev66b15b52015-08-21 11:14:16 +00002168void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2169 Visitor->AddStmt(C->getSimdlen());
2170}
2171
Alexander Musman8bd31e62014-05-27 15:12:19 +00002172void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2173 Visitor->AddStmt(C->getNumForLoops());
2174}
2175
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002176void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002177
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002178void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2179
Alexey Bataev56dafe82014-06-20 07:16:17 +00002180void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002181 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002182 Visitor->AddStmt(C->getChunkSize());
2183}
2184
Alexey Bataev10e775f2015-07-30 11:36:16 +00002185void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2186 Visitor->AddStmt(C->getNumForLoops());
2187}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002188
Alexey Bataev236070f2014-06-20 11:19:47 +00002189void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2190
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002191void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2192
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002193void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2194
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002195void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2196
Alexey Bataevdea47612014-07-23 07:46:59 +00002197void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2198
Alexey Bataev67a4f222014-07-23 10:25:33 +00002199void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2200
Alexey Bataev459dec02014-07-24 06:46:57 +00002201void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2202
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002203void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2204
Alexey Bataev346265e2015-09-25 10:37:12 +00002205void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2206
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002207void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2208
Alexey Bataevb825de12015-12-07 10:51:44 +00002209void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2210
Kelvin Li1408f912018-09-26 04:28:39 +00002211void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2212 const OMPUnifiedAddressClause *) {}
2213
Patrick Lyster4a370b92018-10-01 13:47:43 +00002214void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2215 const OMPUnifiedSharedMemoryClause *) {}
2216
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00002217void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2218 const OMPReverseOffloadClause *) {}
2219
Patrick Lyster3fe9e392018-10-11 14:41:10 +00002220void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2221 const OMPDynamicAllocatorsClause *) {}
2222
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00002223void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2224 const OMPAtomicDefaultMemOrderClause *) {}
2225
Michael Wonge710d542015-08-07 16:16:36 +00002226void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2227 Visitor->AddStmt(C->getDevice());
2228}
2229
Kelvin Li099bb8c2015-11-24 20:50:12 +00002230void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002231 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002232 Visitor->AddStmt(C->getNumTeams());
2233}
2234
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002235void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002236 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002237 Visitor->AddStmt(C->getThreadLimit());
2238}
2239
Alexey Bataeva0569352015-12-01 10:17:31 +00002240void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2241 Visitor->AddStmt(C->getPriority());
2242}
2243
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002244void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2245 Visitor->AddStmt(C->getGrainsize());
2246}
2247
Alexey Bataev382967a2015-12-08 12:06:20 +00002248void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2249 Visitor->AddStmt(C->getNumTasks());
2250}
2251
Alexey Bataev28c75412015-12-15 08:19:24 +00002252void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2253 Visitor->AddStmt(C->getHint());
2254}
2255
Alexey Bataev756c1962013-09-24 03:17:45 +00002256template<typename T>
2257void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002258 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002259 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002260 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002261}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002262
2263void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002264 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002265 for (const auto *E : C->private_copies()) {
2266 Visitor->AddStmt(E);
2267 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002268}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002269void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2270 const OMPFirstprivateClause *C) {
2271 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002272 VisitOMPClauseWithPreInit(C);
2273 for (const auto *E : C->private_copies()) {
2274 Visitor->AddStmt(E);
2275 }
2276 for (const auto *E : C->inits()) {
2277 Visitor->AddStmt(E);
2278 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002279}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002280void OMPClauseEnqueue::VisitOMPLastprivateClause(
2281 const OMPLastprivateClause *C) {
2282 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002283 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002284 for (auto *E : C->private_copies()) {
2285 Visitor->AddStmt(E);
2286 }
2287 for (auto *E : C->source_exprs()) {
2288 Visitor->AddStmt(E);
2289 }
2290 for (auto *E : C->destination_exprs()) {
2291 Visitor->AddStmt(E);
2292 }
2293 for (auto *E : C->assignment_ops()) {
2294 Visitor->AddStmt(E);
2295 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002296}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002297void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002298 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002299}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002300void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2301 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002302 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002303 for (auto *E : C->privates()) {
2304 Visitor->AddStmt(E);
2305 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002306 for (auto *E : C->lhs_exprs()) {
2307 Visitor->AddStmt(E);
2308 }
2309 for (auto *E : C->rhs_exprs()) {
2310 Visitor->AddStmt(E);
2311 }
2312 for (auto *E : C->reduction_ops()) {
2313 Visitor->AddStmt(E);
2314 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002315}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002316void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2317 const OMPTaskReductionClause *C) {
2318 VisitOMPClauseList(C);
2319 VisitOMPClauseWithPostUpdate(C);
2320 for (auto *E : C->privates()) {
2321 Visitor->AddStmt(E);
2322 }
2323 for (auto *E : C->lhs_exprs()) {
2324 Visitor->AddStmt(E);
2325 }
2326 for (auto *E : C->rhs_exprs()) {
2327 Visitor->AddStmt(E);
2328 }
2329 for (auto *E : C->reduction_ops()) {
2330 Visitor->AddStmt(E);
2331 }
2332}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002333void OMPClauseEnqueue::VisitOMPInReductionClause(
2334 const OMPInReductionClause *C) {
2335 VisitOMPClauseList(C);
2336 VisitOMPClauseWithPostUpdate(C);
2337 for (auto *E : C->privates()) {
2338 Visitor->AddStmt(E);
2339 }
2340 for (auto *E : C->lhs_exprs()) {
2341 Visitor->AddStmt(E);
2342 }
2343 for (auto *E : C->rhs_exprs()) {
2344 Visitor->AddStmt(E);
2345 }
2346 for (auto *E : C->reduction_ops()) {
2347 Visitor->AddStmt(E);
2348 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002349 for (auto *E : C->taskgroup_descriptors())
2350 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002351}
Alexander Musman8dba6642014-04-22 13:09:42 +00002352void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2353 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002354 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002355 for (const auto *E : C->privates()) {
2356 Visitor->AddStmt(E);
2357 }
Alexander Musman3276a272015-03-21 10:12:56 +00002358 for (const auto *E : C->inits()) {
2359 Visitor->AddStmt(E);
2360 }
2361 for (const auto *E : C->updates()) {
2362 Visitor->AddStmt(E);
2363 }
2364 for (const auto *E : C->finals()) {
2365 Visitor->AddStmt(E);
2366 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002367 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002368 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002369}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002370void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2371 VisitOMPClauseList(C);
2372 Visitor->AddStmt(C->getAlignment());
2373}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002374void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2375 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002376 for (auto *E : C->source_exprs()) {
2377 Visitor->AddStmt(E);
2378 }
2379 for (auto *E : C->destination_exprs()) {
2380 Visitor->AddStmt(E);
2381 }
2382 for (auto *E : C->assignment_ops()) {
2383 Visitor->AddStmt(E);
2384 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002385}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002386void
2387OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2388 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002389 for (auto *E : C->source_exprs()) {
2390 Visitor->AddStmt(E);
2391 }
2392 for (auto *E : C->destination_exprs()) {
2393 Visitor->AddStmt(E);
2394 }
2395 for (auto *E : C->assignment_ops()) {
2396 Visitor->AddStmt(E);
2397 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002398}
Alexey Bataev6125da92014-07-21 11:26:11 +00002399void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2400 VisitOMPClauseList(C);
2401}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002402void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2403 VisitOMPClauseList(C);
2404}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002405void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2406 VisitOMPClauseList(C);
2407}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002408void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2409 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002410 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002411 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002412}
Alexey Bataev3392d762016-02-16 11:18:12 +00002413void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2414 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002415void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2416 VisitOMPClauseList(C);
2417}
Samuel Antaoec172c62016-05-26 17:49:04 +00002418void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2419 VisitOMPClauseList(C);
2420}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002421void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2422 VisitOMPClauseList(C);
2423}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002424void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2425 VisitOMPClauseList(C);
2426}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002427}
Alexey Bataev756c1962013-09-24 03:17:45 +00002428
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002429void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2430 unsigned size = WL.size();
2431 OMPClauseEnqueue Visitor(this);
2432 Visitor.Visit(S);
2433 if (size == WL.size())
2434 return;
2435 // Now reverse the entries we just added. This will match the DFS
2436 // ordering performed by the worklist.
2437 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2438 std::reverse(I, E);
2439}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002440void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002441 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2442}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002443void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002444 AddDecl(B->getBlockDecl());
2445}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002446void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002447 EnqueueChildren(E);
2448 AddTypeLoc(E->getTypeSourceInfo());
2449}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002450void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002451 for (auto &I : llvm::reverse(S->body()))
2452 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002453}
2454void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002455VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002456 AddStmt(S->getSubStmt());
2457 AddDeclarationNameInfo(S);
2458 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2459 AddNestedNameSpecifierLoc(QualifierLoc);
2460}
2461
2462void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002463VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002464 if (E->hasExplicitTemplateArgs())
2465 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002466 AddDeclarationNameInfo(E);
2467 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2468 AddNestedNameSpecifierLoc(QualifierLoc);
2469 if (!E->isImplicitAccess())
2470 AddStmt(E->getBase());
2471}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002472void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002473 // Enqueue the initializer , if any.
2474 AddStmt(E->getInitializer());
2475 // Enqueue the array size, if any.
2476 AddStmt(E->getArraySize());
2477 // Enqueue the allocated type.
2478 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2479 // Enqueue the placement arguments.
2480 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2481 AddStmt(E->getPlacementArg(I-1));
2482}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002483void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002484 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2485 AddStmt(CE->getArg(I-1));
2486 AddStmt(CE->getCallee());
2487 AddStmt(CE->getArg(0));
2488}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002489void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2490 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002491 // Visit the name of the type being destroyed.
2492 AddTypeLoc(E->getDestroyedTypeInfo());
2493 // Visit the scope type that looks disturbingly like the nested-name-specifier
2494 // but isn't.
2495 AddTypeLoc(E->getScopeTypeInfo());
2496 // Visit the nested-name-specifier.
2497 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2498 AddNestedNameSpecifierLoc(QualifierLoc);
2499 // Visit base expression.
2500 AddStmt(E->getBase());
2501}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002502void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2503 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002504 AddTypeLoc(E->getTypeSourceInfo());
2505}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002506void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2507 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002508 EnqueueChildren(E);
2509 AddTypeLoc(E->getTypeSourceInfo());
2510}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002511void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002512 EnqueueChildren(E);
2513 if (E->isTypeOperand())
2514 AddTypeLoc(E->getTypeOperandSourceInfo());
2515}
2516
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002517void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2518 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002519 EnqueueChildren(E);
2520 AddTypeLoc(E->getTypeSourceInfo());
2521}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002522void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002523 EnqueueChildren(E);
2524 if (E->isTypeOperand())
2525 AddTypeLoc(E->getTypeOperandSourceInfo());
2526}
2527
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002528void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002529 EnqueueChildren(S);
2530 AddDecl(S->getExceptionDecl());
2531}
2532
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002533void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002534 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002535 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002536 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002537}
2538
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002539void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002540 if (DR->hasExplicitTemplateArgs())
2541 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 WL.push_back(DeclRefExprParts(DR, Parent));
2543}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002544void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2545 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002546 if (E->hasExplicitTemplateArgs())
2547 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002548 AddDeclarationNameInfo(E);
2549 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2550}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002551void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002552 unsigned size = WL.size();
2553 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002554 for (const auto *D : S->decls()) {
2555 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002556 isFirst = false;
2557 }
2558 if (size == WL.size())
2559 return;
2560 // Now reverse the entries we just added. This will match the DFS
2561 // ordering performed by the worklist.
2562 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2563 std::reverse(I, E);
2564}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002565void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002566 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002567 for (const DesignatedInitExpr::Designator &D :
2568 llvm::reverse(E->designators())) {
2569 if (D.isFieldDesignator()) {
2570 if (FieldDecl *Field = D.getField())
2571 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 continue;
2573 }
David Majnemerf7e36092016-06-23 00:15:04 +00002574 if (D.isArrayDesignator()) {
2575 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002576 continue;
2577 }
David Majnemerf7e36092016-06-23 00:15:04 +00002578 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2579 AddStmt(E->getArrayRangeEnd(D));
2580 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002581 }
2582}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002583void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002584 EnqueueChildren(E);
2585 AddTypeLoc(E->getTypeInfoAsWritten());
2586}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002587void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002588 AddStmt(FS->getBody());
2589 AddStmt(FS->getInc());
2590 AddStmt(FS->getCond());
2591 AddDecl(FS->getConditionVariable());
2592 AddStmt(FS->getInit());
2593}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002594void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2596}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002597void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002598 AddStmt(If->getElse());
2599 AddStmt(If->getThen());
2600 AddStmt(If->getCond());
2601 AddDecl(If->getConditionVariable());
2602}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002603void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002604 // We care about the syntactic form of the initializer list, only.
2605 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2606 IE = Syntactic;
2607 EnqueueChildren(IE);
2608}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002609void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002610 WL.push_back(MemberExprParts(M, Parent));
2611
2612 // If the base of the member access expression is an implicit 'this', don't
2613 // visit it.
2614 // FIXME: If we ever want to show these implicit accesses, this will be
2615 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002616 if (M->isImplicitAccess())
2617 return;
2618
2619 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002620 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002621 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2622 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2623 if (FD->isAnonymousStructOrUnion()) {
2624 AddStmt(SubME->getBase());
2625 return;
2626 }
2627 }
2628 }
2629
2630 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002631}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002632void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002633 AddTypeLoc(E->getEncodedTypeSourceInfo());
2634}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002635void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002636 EnqueueChildren(M);
2637 AddTypeLoc(M->getClassReceiverTypeInfo());
2638}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002639void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 // Visit the components of the offsetof expression.
2641 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002642 const OffsetOfNode &Node = E->getComponent(I-1);
2643 switch (Node.getKind()) {
2644 case OffsetOfNode::Array:
2645 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2646 break;
2647 case OffsetOfNode::Field:
2648 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2649 break;
2650 case OffsetOfNode::Identifier:
2651 case OffsetOfNode::Base:
2652 continue;
2653 }
2654 }
2655 // Visit the type into which we're computing the offset.
2656 AddTypeLoc(E->getTypeSourceInfo());
2657}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002658void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002659 if (E->hasExplicitTemplateArgs())
2660 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 WL.push_back(OverloadExprParts(E, Parent));
2662}
2663void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002664 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 EnqueueChildren(E);
2666 if (E->isArgumentType())
2667 AddTypeLoc(E->getArgumentTypeInfo());
2668}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002669void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002670 EnqueueChildren(S);
2671}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002672void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002673 AddStmt(S->getBody());
2674 AddStmt(S->getCond());
2675 AddDecl(S->getConditionVariable());
2676}
2677
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002678void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002679 AddStmt(W->getBody());
2680 AddStmt(W->getCond());
2681 AddDecl(W->getConditionVariable());
2682}
2683
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002684void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002685 for (unsigned I = E->getNumArgs(); I > 0; --I)
2686 AddTypeLoc(E->getArg(I-1));
2687}
2688
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002689void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002690 AddTypeLoc(E->getQueriedTypeSourceInfo());
2691}
2692
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002693void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002694 EnqueueChildren(E);
2695}
2696
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002697void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002698 VisitOverloadExpr(U);
2699 if (!U->isImplicitAccess())
2700 AddStmt(U->getBase());
2701}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002702void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002703 AddStmt(E->getSubExpr());
2704 AddTypeLoc(E->getWrittenTypeInfo());
2705}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002706void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002707 WL.push_back(SizeOfPackExprParts(E, Parent));
2708}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002709void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002710 // If the opaque value has a source expression, just transparently
2711 // visit that. This is useful for (e.g.) pseudo-object expressions.
2712 if (Expr *SourceExpr = E->getSourceExpr())
2713 return Visit(SourceExpr);
2714}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002715void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002716 AddStmt(E->getBody());
2717 WL.push_back(LambdaExprParts(E, Parent));
2718}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002719void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002720 // Treat the expression like its syntactic form.
2721 Visit(E->getSyntacticForm());
2722}
2723
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002724void EnqueueVisitor::VisitOMPExecutableDirective(
2725 const OMPExecutableDirective *D) {
2726 EnqueueChildren(D);
2727 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2728 E = D->clauses().end();
2729 I != E; ++I)
2730 EnqueueChildren(*I);
2731}
2732
Alexander Musman3aaab662014-08-19 11:27:13 +00002733void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2734 VisitOMPExecutableDirective(D);
2735}
2736
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002737void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2738 VisitOMPExecutableDirective(D);
2739}
2740
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002741void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002742 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002743}
2744
Alexey Bataevf29276e2014-06-18 04:14:57 +00002745void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002746 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002747}
2748
Alexander Musmanf82886e2014-09-18 05:12:34 +00002749void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2750 VisitOMPLoopDirective(D);
2751}
2752
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002753void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2754 VisitOMPExecutableDirective(D);
2755}
2756
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002757void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2758 VisitOMPExecutableDirective(D);
2759}
2760
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002761void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2762 VisitOMPExecutableDirective(D);
2763}
2764
Alexander Musman80c22892014-07-17 08:54:58 +00002765void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2766 VisitOMPExecutableDirective(D);
2767}
2768
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002769void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2770 VisitOMPExecutableDirective(D);
2771 AddDeclarationNameInfo(D);
2772}
2773
Alexey Bataev4acb8592014-07-07 13:01:15 +00002774void
2775EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002776 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002777}
2778
Alexander Musmane4e893b2014-09-23 09:33:00 +00002779void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2780 const OMPParallelForSimdDirective *D) {
2781 VisitOMPLoopDirective(D);
2782}
2783
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002784void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2785 const OMPParallelSectionsDirective *D) {
2786 VisitOMPExecutableDirective(D);
2787}
2788
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002789void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2790 VisitOMPExecutableDirective(D);
2791}
2792
Alexey Bataev68446b72014-07-18 07:47:19 +00002793void
2794EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2795 VisitOMPExecutableDirective(D);
2796}
2797
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002798void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2799 VisitOMPExecutableDirective(D);
2800}
2801
Alexey Bataev2df347a2014-07-18 10:17:07 +00002802void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2803 VisitOMPExecutableDirective(D);
2804}
2805
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002806void EnqueueVisitor::VisitOMPTaskgroupDirective(
2807 const OMPTaskgroupDirective *D) {
2808 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002809 if (const Expr *E = D->getReductionRef())
2810 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002811}
2812
Alexey Bataev6125da92014-07-21 11:26:11 +00002813void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2814 VisitOMPExecutableDirective(D);
2815}
2816
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002817void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2818 VisitOMPExecutableDirective(D);
2819}
2820
Alexey Bataev0162e452014-07-22 10:10:35 +00002821void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2822 VisitOMPExecutableDirective(D);
2823}
2824
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002825void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2826 VisitOMPExecutableDirective(D);
2827}
2828
Michael Wong65f367f2015-07-21 13:44:28 +00002829void EnqueueVisitor::VisitOMPTargetDataDirective(const
2830 OMPTargetDataDirective *D) {
2831 VisitOMPExecutableDirective(D);
2832}
2833
Samuel Antaodf67fc42016-01-19 19:15:56 +00002834void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2835 const OMPTargetEnterDataDirective *D) {
2836 VisitOMPExecutableDirective(D);
2837}
2838
Samuel Antao72590762016-01-19 20:04:50 +00002839void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2840 const OMPTargetExitDataDirective *D) {
2841 VisitOMPExecutableDirective(D);
2842}
2843
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002844void EnqueueVisitor::VisitOMPTargetParallelDirective(
2845 const OMPTargetParallelDirective *D) {
2846 VisitOMPExecutableDirective(D);
2847}
2848
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002849void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2850 const OMPTargetParallelForDirective *D) {
2851 VisitOMPLoopDirective(D);
2852}
2853
Alexey Bataev13314bf2014-10-09 04:18:56 +00002854void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2855 VisitOMPExecutableDirective(D);
2856}
2857
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002858void EnqueueVisitor::VisitOMPCancellationPointDirective(
2859 const OMPCancellationPointDirective *D) {
2860 VisitOMPExecutableDirective(D);
2861}
2862
Alexey Bataev80909872015-07-02 11:25:17 +00002863void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2864 VisitOMPExecutableDirective(D);
2865}
2866
Alexey Bataev49f6e782015-12-01 04:18:41 +00002867void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2868 VisitOMPLoopDirective(D);
2869}
2870
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002871void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2872 const OMPTaskLoopSimdDirective *D) {
2873 VisitOMPLoopDirective(D);
2874}
2875
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002876void EnqueueVisitor::VisitOMPDistributeDirective(
2877 const OMPDistributeDirective *D) {
2878 VisitOMPLoopDirective(D);
2879}
2880
Carlo Bertolli9925f152016-06-27 14:55:37 +00002881void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2882 const OMPDistributeParallelForDirective *D) {
2883 VisitOMPLoopDirective(D);
2884}
2885
Kelvin Li4a39add2016-07-05 05:00:15 +00002886void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2887 const OMPDistributeParallelForSimdDirective *D) {
2888 VisitOMPLoopDirective(D);
2889}
2890
Kelvin Li787f3fc2016-07-06 04:45:38 +00002891void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2892 const OMPDistributeSimdDirective *D) {
2893 VisitOMPLoopDirective(D);
2894}
2895
Kelvin Lia579b912016-07-14 02:54:56 +00002896void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2897 const OMPTargetParallelForSimdDirective *D) {
2898 VisitOMPLoopDirective(D);
2899}
2900
Kelvin Li986330c2016-07-20 22:57:10 +00002901void EnqueueVisitor::VisitOMPTargetSimdDirective(
2902 const OMPTargetSimdDirective *D) {
2903 VisitOMPLoopDirective(D);
2904}
2905
Kelvin Li02532872016-08-05 14:37:37 +00002906void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2907 const OMPTeamsDistributeDirective *D) {
2908 VisitOMPLoopDirective(D);
2909}
2910
Kelvin Li4e325f72016-10-25 12:50:55 +00002911void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2912 const OMPTeamsDistributeSimdDirective *D) {
2913 VisitOMPLoopDirective(D);
2914}
2915
Kelvin Li579e41c2016-11-30 23:51:03 +00002916void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2917 const OMPTeamsDistributeParallelForSimdDirective *D) {
2918 VisitOMPLoopDirective(D);
2919}
2920
Kelvin Li7ade93f2016-12-09 03:24:30 +00002921void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2922 const OMPTeamsDistributeParallelForDirective *D) {
2923 VisitOMPLoopDirective(D);
2924}
2925
Kelvin Libf594a52016-12-17 05:48:59 +00002926void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2927 const OMPTargetTeamsDirective *D) {
2928 VisitOMPExecutableDirective(D);
2929}
2930
Kelvin Li83c451e2016-12-25 04:52:54 +00002931void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2932 const OMPTargetTeamsDistributeDirective *D) {
2933 VisitOMPLoopDirective(D);
2934}
2935
Kelvin Li80e8f562016-12-29 22:16:30 +00002936void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2937 const OMPTargetTeamsDistributeParallelForDirective *D) {
2938 VisitOMPLoopDirective(D);
2939}
2940
Kelvin Li1851df52017-01-03 05:23:48 +00002941void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2942 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2943 VisitOMPLoopDirective(D);
2944}
2945
Kelvin Lida681182017-01-10 18:08:18 +00002946void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2947 const OMPTargetTeamsDistributeSimdDirective *D) {
2948 VisitOMPLoopDirective(D);
2949}
2950
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002951void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002952 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2953}
2954
2955bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2956 if (RegionOfInterest.isValid()) {
2957 SourceRange Range = getRawCursorExtent(C);
2958 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2959 return false;
2960 }
2961 return true;
2962}
2963
2964bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2965 while (!WL.empty()) {
2966 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002967 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002968
2969 // Set the Parent field, then back to its old value once we're done.
2970 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2971
2972 switch (LI.getKind()) {
2973 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002974 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002975 if (!D)
2976 continue;
2977
2978 // For now, perform default visitation for Decls.
2979 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2980 cast<DeclVisit>(&LI)->isFirst())))
2981 return true;
2982
2983 continue;
2984 }
2985 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002986 for (const TemplateArgumentLoc &Arg :
2987 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2988 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002989 return true;
2990 }
2991 continue;
2992 }
2993 case VisitorJob::TypeLocVisitKind: {
2994 // Perform default visitation for TypeLocs.
2995 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2996 return true;
2997 continue;
2998 }
2999 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003000 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003001 if (LabelStmt *stmt = LS->getStmt()) {
3002 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3003 TU))) {
3004 return true;
3005 }
3006 }
3007 continue;
3008 }
3009
3010 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3011 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3012 if (VisitNestedNameSpecifierLoc(V->get()))
3013 return true;
3014 continue;
3015 }
3016
3017 case VisitorJob::DeclarationNameInfoVisitKind: {
3018 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3019 ->get()))
3020 return true;
3021 continue;
3022 }
3023 case VisitorJob::MemberRefVisitKind: {
3024 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3025 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3026 return true;
3027 continue;
3028 }
3029 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003030 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003031 if (!S)
3032 continue;
3033
3034 // Update the current cursor.
3035 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3036 if (!IsInRegionOfInterest(Cursor))
3037 continue;
3038 switch (Visitor(Cursor, Parent, ClientData)) {
3039 case CXChildVisit_Break: return true;
3040 case CXChildVisit_Continue: break;
3041 case CXChildVisit_Recurse:
3042 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003043 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003044 EnqueueWorkList(WL, S);
3045 break;
3046 }
3047 continue;
3048 }
3049 case VisitorJob::MemberExprPartsKind: {
3050 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003051 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003052
3053 // Visit the nested-name-specifier
3054 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3055 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3056 return true;
3057
3058 // Visit the declaration name.
3059 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3060 return true;
3061
3062 // Visit the explicitly-specified template arguments, if any.
3063 if (M->hasExplicitTemplateArgs()) {
3064 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3065 *ArgEnd = Arg + M->getNumTemplateArgs();
3066 Arg != ArgEnd; ++Arg) {
3067 if (VisitTemplateArgumentLoc(*Arg))
3068 return true;
3069 }
3070 }
3071 continue;
3072 }
3073 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003074 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003075 // Visit nested-name-specifier, if present.
3076 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3077 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3078 return true;
3079 // Visit declaration name.
3080 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3081 return true;
3082 continue;
3083 }
3084 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003085 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003086 // Visit the nested-name-specifier.
3087 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3088 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3089 return true;
3090 // Visit the declaration name.
3091 if (VisitDeclarationNameInfo(O->getNameInfo()))
3092 return true;
3093 // Visit the overloaded declaration reference.
3094 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3095 return true;
3096 continue;
3097 }
3098 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003099 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003100 NamedDecl *Pack = E->getPack();
3101 if (isa<TemplateTypeParmDecl>(Pack)) {
3102 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3103 E->getPackLoc(), TU)))
3104 return true;
3105
3106 continue;
3107 }
3108
3109 if (isa<TemplateTemplateParmDecl>(Pack)) {
3110 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3111 E->getPackLoc(), TU)))
3112 return true;
3113
3114 continue;
3115 }
3116
3117 // Non-type template parameter packs and function parameter packs are
3118 // treated like DeclRefExpr cursors.
3119 continue;
3120 }
3121
3122 case VisitorJob::LambdaExprPartsKind: {
3123 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003124 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003125 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3126 CEnd = E->explicit_capture_end();
3127 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003128 // FIXME: Lambda init-captures.
3129 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003130 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003131
Guy Benyei11169dd2012-12-18 14:30:41 +00003132 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3133 C->getLocation(),
3134 TU)))
3135 return true;
3136 }
3137
Haojian Wuef87c262018-12-18 15:29:12 +00003138 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00003139 // Visit parameters and return type, if present.
Haojian Wuef87c262018-12-18 15:29:12 +00003140 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3141 if (E->hasExplicitParameters()) {
3142 // Visit parameters.
3143 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3144 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003145 return true;
Haojian Wuef87c262018-12-18 15:29:12 +00003146 }
3147 if (E->hasExplicitResultType()) {
3148 // Visit result type.
3149 if (Visit(Proto.getReturnLoc()))
3150 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003151 }
3152 }
3153 break;
3154 }
3155
3156 case VisitorJob::PostChildrenVisitKind:
3157 if (PostChildrenVisitor(Parent, ClientData))
3158 return true;
3159 break;
3160 }
3161 }
3162 return false;
3163}
3164
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003165bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003166 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003167 if (!WorkListFreeList.empty()) {
3168 WL = WorkListFreeList.back();
3169 WL->clear();
3170 WorkListFreeList.pop_back();
3171 }
3172 else {
3173 WL = new VisitorWorkList();
3174 WorkListCache.push_back(WL);
3175 }
3176 EnqueueWorkList(*WL, S);
3177 bool result = RunVisitorWorkList(*WL);
3178 WorkListFreeList.push_back(WL);
3179 return result;
3180}
3181
3182namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003183typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003184RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3185 const DeclarationNameInfo &NI, SourceRange QLoc,
3186 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003187 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3188 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3189 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3190
3191 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3192
3193 RefNamePieces Pieces;
3194
3195 if (WantQualifier && QLoc.isValid())
3196 Pieces.push_back(QLoc);
3197
3198 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3199 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003200
3201 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3202 Pieces.push_back(*TemplateArgsLoc);
3203
Guy Benyei11169dd2012-12-18 14:30:41 +00003204 if (Kind == DeclarationName::CXXOperatorName) {
3205 Pieces.push_back(SourceLocation::getFromRawEncoding(
3206 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3207 Pieces.push_back(SourceLocation::getFromRawEncoding(
3208 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3209 }
3210
3211 if (WantSinglePiece) {
3212 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3213 Pieces.clear();
3214 Pieces.push_back(R);
3215 }
3216
3217 return Pieces;
3218}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003219}
Guy Benyei11169dd2012-12-18 14:30:41 +00003220
3221//===----------------------------------------------------------------------===//
3222// Misc. API hooks.
3223//===----------------------------------------------------------------------===//
3224
Chad Rosier05c71aa2013-03-27 18:28:23 +00003225static void fatal_error_handler(void *user_data, const std::string& reason,
3226 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003227 // Write the result out to stderr avoiding errs() because raw_ostreams can
3228 // call report_fatal_error.
3229 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3230 ::abort();
3231}
3232
Chandler Carruth66660742014-06-27 16:37:27 +00003233namespace {
3234struct RegisterFatalErrorHandler {
3235 RegisterFatalErrorHandler() {
3236 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3237 }
3238};
3239}
3240
3241static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3242
Guy Benyei11169dd2012-12-18 14:30:41 +00003243CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3244 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003245 // We use crash recovery to make some of our APIs more reliable, implicitly
3246 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003247 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3248 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003249
Chandler Carruth66660742014-06-27 16:37:27 +00003250 // Look through the managed static to trigger construction of the managed
3251 // static which registers our fatal error handler. This ensures it is only
3252 // registered once.
3253 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003254
Adrian Prantlbc068582015-07-08 01:00:30 +00003255 // Initialize targets for clang module support.
3256 llvm::InitializeAllTargets();
3257 llvm::InitializeAllTargetMCs();
3258 llvm::InitializeAllAsmPrinters();
3259 llvm::InitializeAllAsmParsers();
3260
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003261 CIndexer *CIdxr = new CIndexer();
3262
Guy Benyei11169dd2012-12-18 14:30:41 +00003263 if (excludeDeclarationsFromPCH)
3264 CIdxr->setOnlyLocalDecls();
3265 if (displayDiagnostics)
3266 CIdxr->setDisplayDiagnostics();
3267
3268 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3269 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3270 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3271 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3272 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3273 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3274
3275 return CIdxr;
3276}
3277
3278void clang_disposeIndex(CXIndex CIdx) {
3279 if (CIdx)
3280 delete static_cast<CIndexer *>(CIdx);
3281}
3282
3283void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3284 if (CIdx)
3285 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3286}
3287
3288unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3289 if (CIdx)
3290 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3291 return 0;
3292}
3293
Alex Lorenz08615792017-12-04 21:56:36 +00003294void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3295 const char *Path) {
3296 if (CIdx)
3297 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3298}
3299
Guy Benyei11169dd2012-12-18 14:30:41 +00003300void clang_toggleCrashRecovery(unsigned isEnabled) {
3301 if (isEnabled)
3302 llvm::CrashRecoveryContext::Enable();
3303 else
3304 llvm::CrashRecoveryContext::Disable();
3305}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003306
Guy Benyei11169dd2012-12-18 14:30:41 +00003307CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3308 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003309 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003310 enum CXErrorCode Result =
3311 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003312 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003313 assert((TU && Result == CXError_Success) ||
3314 (!TU && Result != CXError_Success));
3315 return TU;
3316}
3317
3318enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3319 const char *ast_filename,
3320 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003321 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003322 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003323
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003324 if (!CIdx || !ast_filename || !out_TU)
3325 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003326
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003327 LOG_FUNC_SECTION {
3328 *Log << ast_filename;
3329 }
3330
Guy Benyei11169dd2012-12-18 14:30:41 +00003331 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3332 FileSystemOptions FileSystemOpts;
3333
Justin Bognerd512c1e2014-10-15 00:33:06 +00003334 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3335 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003336 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003337 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3338 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003339 FileSystemOpts, /*UseDebugInfo=*/false,
3340 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003341 /*CaptureDiagnostics=*/true,
3342 /*AllowPCHWithCompilerErrors=*/true,
3343 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003344 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003345 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003346}
3347
3348unsigned clang_defaultEditingTranslationUnitOptions() {
3349 return CXTranslationUnit_PrecompiledPreamble |
3350 CXTranslationUnit_CacheCompletionResults;
3351}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003352
Guy Benyei11169dd2012-12-18 14:30:41 +00003353CXTranslationUnit
3354clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3355 const char *source_filename,
3356 int num_command_line_args,
3357 const char * const *command_line_args,
3358 unsigned num_unsaved_files,
3359 struct CXUnsavedFile *unsaved_files) {
3360 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3361 return clang_parseTranslationUnit(CIdx, source_filename,
3362 command_line_args, num_command_line_args,
3363 unsaved_files, num_unsaved_files,
3364 Options);
3365}
3366
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003367static CXErrorCode
3368clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3369 const char *const *command_line_args,
3370 int num_command_line_args,
3371 ArrayRef<CXUnsavedFile> unsaved_files,
3372 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003373 // Set up the initial return values.
3374 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003375 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003376
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003377 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003378 if (!CIdx || !out_TU)
3379 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003380
Guy Benyei11169dd2012-12-18 14:30:41 +00003381 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3382
3383 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3384 setThreadBackgroundPriority();
3385
3386 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003387 bool CreatePreambleOnFirstParse =
3388 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003389 // FIXME: Add a flag for modules.
3390 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003391 = (options & (CXTranslationUnit_Incomplete |
3392 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003393 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003394 = options & CXTranslationUnit_CacheCompletionResults;
3395 bool IncludeBriefCommentsInCodeCompletion
3396 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003397 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3398 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003399 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3400 if (options & CXTranslationUnit_SkipFunctionBodies) {
3401 SkipFunctionBodies =
3402 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3403 ? SkipFunctionBodiesScope::Preamble
3404 : SkipFunctionBodiesScope::PreambleAndMainFile;
3405 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003406
3407 // Configure the diagnostics.
3408 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003409 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003410
Manuel Klimek016c0242016-03-01 10:56:19 +00003411 if (options & CXTranslationUnit_KeepGoing)
Richard Smithe37391c2017-05-03 00:28:49 +00003412 Diags->setSuppressAfterFatalError(false);
Manuel Klimek016c0242016-03-01 10:56:19 +00003413
Guy Benyei11169dd2012-12-18 14:30:41 +00003414 // Recover resources if we crash before exiting this function.
3415 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3416 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003417 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003418
Ahmed Charlesb8984322014-03-07 20:03:18 +00003419 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3420 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003421
3422 // Recover resources if we crash before exiting this function.
3423 llvm::CrashRecoveryContextCleanupRegistrar<
3424 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3425
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003426 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003427 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003428 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003429 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003430 }
3431
Ahmed Charlesb8984322014-03-07 20:03:18 +00003432 std::unique_ptr<std::vector<const char *>> Args(
3433 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003434
3435 // Recover resources if we crash before exiting this method.
3436 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3437 ArgsCleanup(Args.get());
3438
3439 // Since the Clang C library is primarily used by batch tools dealing with
3440 // (often very broken) source code, where spell-checking can have a
3441 // significant negative impact on performance (particularly when
3442 // precompiled headers are involved), we disable it by default.
3443 // Only do this if we haven't found a spell-checking-related argument.
3444 bool FoundSpellCheckingArgument = false;
3445 for (int I = 0; I != num_command_line_args; ++I) {
3446 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3447 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3448 FoundSpellCheckingArgument = true;
3449 break;
3450 }
3451 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003452 Args->insert(Args->end(), command_line_args,
3453 command_line_args + num_command_line_args);
3454
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003455 if (!FoundSpellCheckingArgument)
3456 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3457
Guy Benyei11169dd2012-12-18 14:30:41 +00003458 // The 'source_filename' argument is optional. If the caller does not
3459 // specify it then it is assumed that the source file is specified
3460 // in the actual argument list.
3461 // Put the source file after command_line_args otherwise if '-x' flag is
3462 // present it will be unused.
3463 if (source_filename)
3464 Args->push_back(source_filename);
3465
3466 // Do we need the detailed preprocessing record?
3467 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3468 Args->push_back("-Xclang");
3469 Args->push_back("-detailed-preprocessing-record");
3470 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003471
3472 // Suppress any editor placeholder diagnostics.
3473 Args->push_back("-fallow-editor-placeholders");
3474
Guy Benyei11169dd2012-12-18 14:30:41 +00003475 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003476 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003477 // Unless the user specified that they want the preamble on the first parse
3478 // set it up to be created on the first reparse. This makes the first parse
3479 // faster, trading for a slower (first) reparse.
3480 unsigned PrecompilePreambleAfterNParses =
3481 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003482
Alex Lorenz08615792017-12-04 21:56:36 +00003483 LibclangInvocationReporter InvocationReporter(
3484 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003485 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3486 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003487 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003488 Args->data(), Args->data() + Args->size(),
3489 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003490 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3491 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003492 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3493 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003494 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003495 /*UserFilesAreVolatile=*/true, ForSerialization,
3496 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3497 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003498
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003499 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003500 if (!Unit && !ErrUnit)
3501 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003502
Guy Benyei11169dd2012-12-18 14:30:41 +00003503 if (NumErrors != Diags->getClient()->getNumErrors()) {
3504 // Make sure to check that 'Unit' is non-NULL.
3505 if (CXXIdx->getDisplayDiagnostics())
3506 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3507 }
3508
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003509 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3510 return CXError_ASTReadError;
3511
David Blaikieea4395e2017-01-06 19:49:01 +00003512 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003513 if (CXTranslationUnitImpl *TU = *out_TU) {
3514 TU->ParsingOptions = options;
3515 TU->Arguments.reserve(Args->size());
3516 for (const char *Arg : *Args)
3517 TU->Arguments.push_back(Arg);
3518 return CXError_Success;
3519 }
3520 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003521}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003522
3523CXTranslationUnit
3524clang_parseTranslationUnit(CXIndex CIdx,
3525 const char *source_filename,
3526 const char *const *command_line_args,
3527 int num_command_line_args,
3528 struct CXUnsavedFile *unsaved_files,
3529 unsigned num_unsaved_files,
3530 unsigned options) {
3531 CXTranslationUnit TU;
3532 enum CXErrorCode Result = clang_parseTranslationUnit2(
3533 CIdx, source_filename, command_line_args, num_command_line_args,
3534 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003535 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003536 assert((TU && Result == CXError_Success) ||
3537 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003538 return TU;
3539}
3540
3541enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003542 CXIndex CIdx, const char *source_filename,
3543 const char *const *command_line_args, int num_command_line_args,
3544 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3545 unsigned options, CXTranslationUnit *out_TU) {
3546 SmallVector<const char *, 4> Args;
3547 Args.push_back("clang");
3548 Args.append(command_line_args, command_line_args + num_command_line_args);
3549 return clang_parseTranslationUnit2FullArgv(
3550 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3551 num_unsaved_files, options, out_TU);
3552}
3553
3554enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3555 CXIndex CIdx, const char *source_filename,
3556 const char *const *command_line_args, int num_command_line_args,
3557 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3558 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003559 LOG_FUNC_SECTION {
3560 *Log << source_filename << ": ";
3561 for (int i = 0; i != num_command_line_args; ++i)
3562 *Log << command_line_args[i] << " ";
3563 }
3564
Alp Toker9d85b182014-07-07 01:23:14 +00003565 if (num_unsaved_files && !unsaved_files)
3566 return CXError_InvalidArguments;
3567
Alp Toker5c532982014-07-07 22:42:03 +00003568 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003569 auto ParseTranslationUnitImpl = [=, &result] {
3570 result = clang_parseTranslationUnit_Impl(
3571 CIdx, source_filename, command_line_args, num_command_line_args,
3572 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3573 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003574
Guy Benyei11169dd2012-12-18 14:30:41 +00003575 llvm::CrashRecoveryContext CRC;
3576
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003577 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003578 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3579 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3580 fprintf(stderr, " 'command_line_args' : [");
3581 for (int i = 0; i != num_command_line_args; ++i) {
3582 if (i)
3583 fprintf(stderr, ", ");
3584 fprintf(stderr, "'%s'", command_line_args[i]);
3585 }
3586 fprintf(stderr, "],\n");
3587 fprintf(stderr, " 'unsaved_files' : [");
3588 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3589 if (i)
3590 fprintf(stderr, ", ");
3591 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3592 unsaved_files[i].Length);
3593 }
3594 fprintf(stderr, "],\n");
3595 fprintf(stderr, " 'options' : %d,\n", options);
3596 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003597
3598 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003599 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003600 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003601 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003602 }
Alp Toker5c532982014-07-07 22:42:03 +00003603
3604 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003605}
3606
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003607CXString clang_Type_getObjCEncoding(CXType CT) {
3608 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3609 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3610 std::string encoding;
3611 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3612 encoding);
3613
3614 return cxstring::createDup(encoding);
3615}
3616
3617static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3618 if (C.kind == CXCursor_MacroDefinition) {
3619 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3620 return MDR->getName();
3621 } else if (C.kind == CXCursor_MacroExpansion) {
3622 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3623 return ME.getName();
3624 }
3625 return nullptr;
3626}
3627
3628unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3629 const IdentifierInfo *II = getMacroIdentifier(C);
3630 if (!II) {
3631 return false;
3632 }
3633 ASTUnit *ASTU = getCursorASTUnit(C);
3634 Preprocessor &PP = ASTU->getPreprocessor();
3635 if (const MacroInfo *MI = PP.getMacroInfo(II))
3636 return MI->isFunctionLike();
3637 return false;
3638}
3639
3640unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3641 const IdentifierInfo *II = getMacroIdentifier(C);
3642 if (!II) {
3643 return false;
3644 }
3645 ASTUnit *ASTU = getCursorASTUnit(C);
3646 Preprocessor &PP = ASTU->getPreprocessor();
3647 if (const MacroInfo *MI = PP.getMacroInfo(II))
3648 return MI->isBuiltinMacro();
3649 return false;
3650}
3651
3652unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3653 const Decl *D = getCursorDecl(C);
3654 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3655 if (!FD) {
3656 return false;
3657 }
3658 return FD->isInlined();
3659}
3660
3661static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3662 if (callExpr->getNumArgs() != 1) {
3663 return nullptr;
3664 }
3665
3666 StringLiteral *S = nullptr;
3667 auto *arg = callExpr->getArg(0);
3668 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3669 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3670 auto *subExpr = I->getSubExprAsWritten();
3671
3672 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3673 return nullptr;
3674 }
3675
3676 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3677 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3678 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3679 } else {
3680 return nullptr;
3681 }
3682 return S;
3683}
3684
David Blaikie59272572016-04-13 18:23:33 +00003685struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003686 CXEvalResultKind EvalType;
3687 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003688 unsigned long long unsignedVal;
3689 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003690 double floatVal;
3691 char *stringVal;
3692 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003693 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003694 ~ExprEvalResult() {
3695 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3696 EvalType != CXEval_Int) {
Alex Lorenza19cb2e2019-01-08 23:28:37 +00003697 delete[] EvalData.stringVal;
David Blaikie59272572016-04-13 18:23:33 +00003698 }
3699 }
3700};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003701
3702void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003703 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003704}
3705
3706CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3707 if (!E) {
3708 return CXEval_UnExposed;
3709 }
3710 return ((ExprEvalResult *)E)->EvalType;
3711}
3712
3713int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003714 return clang_EvalResult_getAsLongLong(E);
3715}
3716
3717long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003718 if (!E) {
3719 return 0;
3720 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003721 ExprEvalResult *Result = (ExprEvalResult*)E;
3722 if (Result->IsUnsignedInt)
3723 return Result->EvalData.unsignedVal;
3724 return Result->EvalData.intVal;
3725}
3726
3727unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3728 return ((ExprEvalResult *)E)->IsUnsignedInt;
3729}
3730
3731unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3732 if (!E) {
3733 return 0;
3734 }
3735
3736 ExprEvalResult *Result = (ExprEvalResult*)E;
3737 if (Result->IsUnsignedInt)
3738 return Result->EvalData.unsignedVal;
3739 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003740}
3741
3742double clang_EvalResult_getAsDouble(CXEvalResult E) {
3743 if (!E) {
3744 return 0;
3745 }
3746 return ((ExprEvalResult *)E)->EvalData.floatVal;
3747}
3748
3749const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3750 if (!E) {
3751 return nullptr;
3752 }
3753 return ((ExprEvalResult *)E)->EvalData.stringVal;
3754}
3755
3756static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3757 Expr::EvalResult ER;
3758 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003759 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003760 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003761
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003762 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003763 if (!expr->EvaluateAsRValue(ER, ctx))
3764 return nullptr;
3765
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003766 QualType rettype;
3767 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003768 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003769 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003770 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003771
David Blaikiebbc00882016-04-13 18:36:19 +00003772 if (ER.Val.isInt()) {
3773 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003774
3775 auto& val = ER.Val.getInt();
3776 if (val.isUnsigned()) {
3777 result->IsUnsignedInt = true;
3778 result->EvalData.unsignedVal = val.getZExtValue();
3779 } else {
3780 result->EvalData.intVal = val.getExtValue();
3781 }
3782
David Blaikiebbc00882016-04-13 18:36:19 +00003783 return result.release();
3784 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003785
David Blaikiebbc00882016-04-13 18:36:19 +00003786 if (ER.Val.isFloat()) {
3787 llvm::SmallVector<char, 100> Buffer;
3788 ER.Val.getFloat().toString(Buffer);
3789 std::string floatStr(Buffer.data(), Buffer.size());
3790 result->EvalType = CXEval_Float;
3791 bool ignored;
3792 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003793 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003794 llvm::APFloat::rmNearestTiesToEven, &ignored);
3795 result->EvalData.floatVal = apFloat.convertToDouble();
3796 return result.release();
3797 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003798
David Blaikiebbc00882016-04-13 18:36:19 +00003799 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3800 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3801 auto *subExpr = I->getSubExprAsWritten();
3802 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3803 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003804 const StringLiteral *StrE = nullptr;
3805 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003806 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003807
3808 if (ObjCExpr) {
3809 StrE = ObjCExpr->getString();
3810 result->EvalType = CXEval_ObjCStrLiteral;
3811 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003812 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003813 result->EvalType = CXEval_StrLiteral;
3814 }
3815
3816 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003817 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003818 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3819 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003820 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003821 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003822 }
3823 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3824 expr->getStmtClass() == Stmt::StringLiteralClass) {
3825 const StringLiteral *StrE = nullptr;
3826 const ObjCStringLiteral *ObjCExpr;
3827 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003828
David Blaikiebbc00882016-04-13 18:36:19 +00003829 if (ObjCExpr) {
3830 StrE = ObjCExpr->getString();
3831 result->EvalType = CXEval_ObjCStrLiteral;
3832 } else {
3833 StrE = cast<StringLiteral>(expr);
3834 result->EvalType = CXEval_StrLiteral;
3835 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003836
David Blaikiebbc00882016-04-13 18:36:19 +00003837 std::string strRef(StrE->getString().str());
3838 result->EvalData.stringVal = new char[strRef.size() + 1];
3839 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3840 result->EvalData.stringVal[strRef.size()] = '\0';
3841 return result.release();
3842 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003843
David Blaikiebbc00882016-04-13 18:36:19 +00003844 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3845 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003846
David Blaikiebbc00882016-04-13 18:36:19 +00003847 rettype = CC->getType();
3848 if (rettype.getAsString() == "CFStringRef" &&
3849 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003850
David Blaikiebbc00882016-04-13 18:36:19 +00003851 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3852 StringLiteral *S = getCFSTR_value(callExpr);
3853 if (S) {
3854 std::string strLiteral(S->getString().str());
3855 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003856
David Blaikiebbc00882016-04-13 18:36:19 +00003857 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3858 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3859 strLiteral.size());
3860 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003861 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003862 }
3863 }
3864
David Blaikiebbc00882016-04-13 18:36:19 +00003865 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3866 callExpr = static_cast<CallExpr *>(expr);
3867 rettype = callExpr->getCallReturnType(ctx);
3868
3869 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3870 return nullptr;
3871
3872 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3873 if (callExpr->getNumArgs() == 1 &&
3874 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3875 return nullptr;
3876 } else if (rettype.getAsString() == "CFStringRef") {
3877
3878 StringLiteral *S = getCFSTR_value(callExpr);
3879 if (S) {
3880 std::string strLiteral(S->getString().str());
3881 result->EvalType = CXEval_CFStr;
3882 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3883 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3884 strLiteral.size());
3885 result->EvalData.stringVal[strLiteral.size()] = '\0';
3886 return result.release();
3887 }
3888 }
3889 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3890 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3891 ValueDecl *V = D->getDecl();
3892 if (V->getKind() == Decl::Function) {
3893 std::string strName = V->getNameAsString();
3894 result->EvalType = CXEval_Other;
3895 result->EvalData.stringVal = new char[strName.size() + 1];
3896 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3897 result->EvalData.stringVal[strName.size()] = '\0';
3898 return result.release();
3899 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003900 }
3901
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003902 return nullptr;
3903}
3904
Alex Lorenz65317e12019-01-08 22:32:51 +00003905static const Expr *evaluateDeclExpr(const Decl *D) {
3906 if (!D)
Evgeniy Stepanov9b871492018-07-10 19:48:53 +00003907 return nullptr;
Alex Lorenz65317e12019-01-08 22:32:51 +00003908 if (auto *Var = dyn_cast<VarDecl>(D))
3909 return Var->getInit();
3910 else if (auto *Field = dyn_cast<FieldDecl>(D))
3911 return Field->getInClassInitializer();
3912 return nullptr;
3913}
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003914
Alex Lorenz65317e12019-01-08 22:32:51 +00003915static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
3916 assert(CS && "invalid compound statement");
3917 for (auto *bodyIterator : CS->body()) {
3918 if (const auto *E = dyn_cast<Expr>(bodyIterator))
3919 return E;
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003920 }
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00003921 return nullptr;
3922}
3923
Alex Lorenz65317e12019-01-08 22:32:51 +00003924CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3925 if (const Expr *E =
3926 clang_getCursorKind(C) == CXCursor_CompoundStmt
3927 ? evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)))
3928 : evaluateDeclExpr(getCursorDecl(C)))
3929 return const_cast<CXEvalResult>(
3930 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
3931 return nullptr;
3932}
3933
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003934unsigned clang_Cursor_hasAttrs(CXCursor C) {
3935 const Decl *D = getCursorDecl(C);
3936 if (!D) {
3937 return 0;
3938 }
3939
3940 if (D->hasAttrs()) {
3941 return 1;
3942 }
3943
3944 return 0;
3945}
Guy Benyei11169dd2012-12-18 14:30:41 +00003946unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3947 return CXSaveTranslationUnit_None;
3948}
3949
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003950static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3951 const char *FileName,
3952 unsigned options) {
3953 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003954 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3955 setThreadBackgroundPriority();
3956
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003957 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3958 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003959}
3960
3961int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3962 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003963 LOG_FUNC_SECTION {
3964 *Log << TU << ' ' << FileName;
3965 }
3966
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003967 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003968 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003969 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003970 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003971
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003972 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003973 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3974 if (!CXXUnit->hasSema())
3975 return CXSaveError_InvalidTU;
3976
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003977 CXSaveError result;
3978 auto SaveTranslationUnitImpl = [=, &result]() {
3979 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3980 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003981
Erik Verbruggen3cc39112017-11-14 09:34:39 +00003982 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003983 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003984
3985 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3986 PrintLibclangResourceUsage(TU);
3987
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003988 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003989 }
3990
3991 // We have an AST that has invalid nodes due to compiler errors.
3992 // Use a crash recovery thread for protection.
3993
3994 llvm::CrashRecoveryContext CRC;
3995
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003996 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003997 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3998 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3999 fprintf(stderr, " 'options' : %d,\n", options);
4000 fprintf(stderr, "}\n");
4001
4002 return CXSaveError_Unknown;
4003
4004 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4005 PrintLibclangResourceUsage(TU);
4006 }
4007
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004008 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004009}
4010
4011void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4012 if (CTUnit) {
4013 // If the translation unit has been marked as unsafe to free, just discard
4014 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004015 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4016 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004017 return;
4018
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004019 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004020 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004021 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4022 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004023 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004024 delete CTUnit;
4025 }
4026}
4027
Erik Verbruggen346066b2017-05-30 14:25:54 +00004028unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4029 if (CTUnit) {
4030 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4031
4032 if (Unit && Unit->isUnsafeToFree())
4033 return false;
4034
4035 Unit->ResetForParse();
4036 return true;
4037 }
4038
4039 return false;
4040}
4041
Guy Benyei11169dd2012-12-18 14:30:41 +00004042unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4043 return CXReparse_None;
4044}
4045
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004046static CXErrorCode
4047clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4048 ArrayRef<CXUnsavedFile> unsaved_files,
4049 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004050 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004051 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004052 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004053 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004054 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004055
4056 // Reset the associated diagnostics.
4057 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004058 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004059
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004060 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004061 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4062 setThreadBackgroundPriority();
4063
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004064 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004065 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004066
4067 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4068 new std::vector<ASTUnit::RemappedFile>());
4069
Guy Benyei11169dd2012-12-18 14:30:41 +00004070 // Recover resources if we crash before exiting this function.
4071 llvm::CrashRecoveryContextCleanupRegistrar<
4072 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004073
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004074 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004075 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004076 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004077 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004078 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004079
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004080 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4081 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004082 return CXError_Success;
4083 if (isASTReadError(CXXUnit))
4084 return CXError_ASTReadError;
4085 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004086}
4087
4088int clang_reparseTranslationUnit(CXTranslationUnit TU,
4089 unsigned num_unsaved_files,
4090 struct CXUnsavedFile *unsaved_files,
4091 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004092 LOG_FUNC_SECTION {
4093 *Log << TU;
4094 }
4095
Alp Toker9d85b182014-07-07 01:23:14 +00004096 if (num_unsaved_files && !unsaved_files)
4097 return CXError_InvalidArguments;
4098
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004099 CXErrorCode result;
4100 auto ReparseTranslationUnitImpl = [=, &result]() {
4101 result = clang_reparseTranslationUnit_Impl(
4102 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4103 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004104
Guy Benyei11169dd2012-12-18 14:30:41 +00004105 llvm::CrashRecoveryContext CRC;
4106
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004107 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004108 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004109 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004110 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004111 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4112 PrintLibclangResourceUsage(TU);
4113
Alp Toker5c532982014-07-07 22:42:03 +00004114 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004115}
4116
4117
4118CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004119 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004120 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004121 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004122 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004123
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004124 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004125 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004126}
4127
4128CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004129 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004130 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004131 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004132 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004133
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004134 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004135 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4136}
4137
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004138CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4139 if (isNotUsableTU(CTUnit)) {
4140 LOG_BAD_TU(CTUnit);
4141 return nullptr;
4142 }
4143
4144 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4145 impl->TranslationUnit = CTUnit;
4146 return impl;
4147}
4148
4149CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4150 if (!TargetInfo)
4151 return cxstring::createEmpty();
4152
4153 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4154 assert(!isNotUsableTU(CTUnit) &&
4155 "Unexpected unusable translation unit in TargetInfo");
4156
4157 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4158 std::string Triple =
4159 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4160 return cxstring::createDup(Triple);
4161}
4162
4163int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4164 if (!TargetInfo)
4165 return -1;
4166
4167 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4168 assert(!isNotUsableTU(CTUnit) &&
4169 "Unexpected unusable translation unit in TargetInfo");
4170
4171 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4172 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4173}
4174
4175void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4176 if (!TargetInfo)
4177 return;
4178
4179 delete TargetInfo;
4180}
4181
Guy Benyei11169dd2012-12-18 14:30:41 +00004182//===----------------------------------------------------------------------===//
4183// CXFile Operations.
4184//===----------------------------------------------------------------------===//
4185
Guy Benyei11169dd2012-12-18 14:30:41 +00004186CXString clang_getFileName(CXFile SFile) {
4187 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004188 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004189
4190 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004191 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004192}
4193
4194time_t clang_getFileTime(CXFile SFile) {
4195 if (!SFile)
4196 return 0;
4197
4198 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4199 return FEnt->getModificationTime();
4200}
4201
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004202CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004203 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004204 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004205 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004206 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004207
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004208 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004209
4210 FileManager &FMgr = CXXUnit->getFileManager();
4211 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4212}
4213
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004214const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4215 size_t *size) {
4216 if (isNotUsableTU(TU)) {
4217 LOG_BAD_TU(TU);
4218 return nullptr;
4219 }
4220
4221 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4222 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4223 bool Invalid = true;
4224 llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
4225 if (Invalid) {
4226 if (size)
4227 *size = 0;
4228 return nullptr;
4229 }
4230 if (size)
4231 *size = buf->getBufferSize();
4232 return buf->getBufferStart();
4233}
4234
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004235unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4236 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004237 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004238 LOG_BAD_TU(TU);
4239 return 0;
4240 }
4241
4242 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004243 return 0;
4244
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004245 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004246 FileEntry *FEnt = static_cast<FileEntry *>(file);
4247 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4248 .isFileMultipleIncludeGuarded(FEnt);
4249}
4250
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004251int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4252 if (!file || !outID)
4253 return 1;
4254
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004255 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004256 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4257 outID->data[0] = ID.getDevice();
4258 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004259 outID->data[2] = FEnt->getModificationTime();
4260 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004261}
4262
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004263int clang_File_isEqual(CXFile file1, CXFile file2) {
4264 if (file1 == file2)
4265 return true;
4266
4267 if (!file1 || !file2)
4268 return false;
4269
4270 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4271 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4272 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4273}
4274
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004275CXString clang_File_tryGetRealPathName(CXFile SFile) {
4276 if (!SFile)
4277 return cxstring::createNull();
4278
4279 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4280 return cxstring::createRef(FEnt->tryGetRealPathName());
4281}
4282
Guy Benyei11169dd2012-12-18 14:30:41 +00004283//===----------------------------------------------------------------------===//
4284// CXCursor Operations.
4285//===----------------------------------------------------------------------===//
4286
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004287static const Decl *getDeclFromExpr(const Stmt *E) {
4288 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004289 return getDeclFromExpr(CE->getSubExpr());
4290
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004291 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004292 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004293 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004294 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004295 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004296 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004297 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004298 if (PRE->isExplicitProperty())
4299 return PRE->getExplicitProperty();
4300 // It could be messaging both getter and setter as in:
4301 // ++myobj.myprop;
4302 // in which case prefer to associate the setter since it is less obvious
4303 // from inspecting the source that the setter is going to get called.
4304 if (PRE->isMessagingSetter())
4305 return PRE->getImplicitPropertySetter();
4306 return PRE->getImplicitPropertyGetter();
4307 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004308 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004309 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004310 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004311 if (Expr *Src = OVE->getSourceExpr())
4312 return getDeclFromExpr(Src);
4313
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004314 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004315 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004316 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004317 if (!CE->isElidable())
4318 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004319 if (const CXXInheritedCtorInitExpr *CE =
4320 dyn_cast<CXXInheritedCtorInitExpr>(E))
4321 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004322 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004323 return OME->getMethodDecl();
4324
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004325 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004326 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004327 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004328 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4329 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004330 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004331 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4332 isa<ParmVarDecl>(SizeOfPack->getPack()))
4333 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004334
4335 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004336}
4337
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004338static SourceLocation getLocationFromExpr(const Expr *E) {
4339 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004340 return getLocationFromExpr(CE->getSubExpr());
4341
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004342 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004343 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004344 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004345 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004346 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004347 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004348 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004349 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004350 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004351 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004352 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004353 return PropRef->getLocation();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004354
4355 return E->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00004356}
4357
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004358extern "C" {
4359
Guy Benyei11169dd2012-12-18 14:30:41 +00004360unsigned clang_visitChildren(CXCursor parent,
4361 CXCursorVisitor visitor,
4362 CXClientData client_data) {
4363 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4364 /*VisitPreprocessorLast=*/false);
4365 return CursorVis.VisitChildren(parent);
4366}
4367
4368#ifndef __has_feature
4369#define __has_feature(x) 0
4370#endif
4371#if __has_feature(blocks)
4372typedef enum CXChildVisitResult
4373 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4374
4375static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4376 CXClientData client_data) {
4377 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4378 return block(cursor, parent);
4379}
4380#else
4381// If we are compiled with a compiler that doesn't have native blocks support,
4382// define and call the block manually, so the
4383typedef struct _CXChildVisitResult
4384{
4385 void *isa;
4386 int flags;
4387 int reserved;
4388 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4389 CXCursor);
4390} *CXCursorVisitorBlock;
4391
4392static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4393 CXClientData client_data) {
4394 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4395 return block->invoke(block, cursor, parent);
4396}
4397#endif
4398
4399
4400unsigned clang_visitChildrenWithBlock(CXCursor parent,
4401 CXCursorVisitorBlock block) {
4402 return clang_visitChildren(parent, visitWithBlock, block);
4403}
4404
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004405static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004406 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004407 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004408
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004409 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004410 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004411 if (const ObjCPropertyImplDecl *PropImpl =
4412 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004413 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004414 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004415
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004416 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004417 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004418 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004419
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004420 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004421 }
4422
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004423 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004424 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004425
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004426 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004427 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4428 // and returns different names. NamedDecl returns the class name and
4429 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004430 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004431
4432 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004433 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004434
4435 SmallString<1024> S;
4436 llvm::raw_svector_ostream os(S);
4437 ND->printName(os);
4438
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004439 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004440}
4441
4442CXString clang_getCursorSpelling(CXCursor C) {
4443 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004444 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004445
4446 if (clang_isReference(C.kind)) {
4447 switch (C.kind) {
4448 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004449 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004450 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004451 }
4452 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004453 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004454 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004455 }
4456 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004457 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004458 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004459 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004460 }
4461 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004462 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004463 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004464 }
4465 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004466 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004467 assert(Type && "Missing type decl");
4468
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004469 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004470 getAsString());
4471 }
4472 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004473 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004474 assert(Template && "Missing template decl");
4475
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004476 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004477 }
4478
4479 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004480 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004481 assert(NS && "Missing namespace decl");
4482
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004483 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004484 }
4485
4486 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004487 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004488 assert(Field && "Missing member decl");
4489
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004490 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004491 }
4492
4493 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004494 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004495 assert(Label && "Missing label");
4496
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004497 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004498 }
4499
4500 case CXCursor_OverloadedDeclRef: {
4501 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004502 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4503 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004504 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004505 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004506 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004507 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004508 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004509 OverloadedTemplateStorage *Ovl
4510 = Storage.get<OverloadedTemplateStorage*>();
4511 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004512 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004513 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004514 }
4515
4516 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004517 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004518 assert(Var && "Missing variable decl");
4519
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004520 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004521 }
4522
4523 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004524 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004525 }
4526 }
4527
4528 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004529 const Expr *E = getCursorExpr(C);
4530
4531 if (C.kind == CXCursor_ObjCStringLiteral ||
4532 C.kind == CXCursor_StringLiteral) {
4533 const StringLiteral *SLit;
4534 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4535 SLit = OSL->getString();
4536 } else {
4537 SLit = cast<StringLiteral>(E);
4538 }
4539 SmallString<256> Buf;
4540 llvm::raw_svector_ostream OS(Buf);
4541 SLit->outputString(OS);
4542 return cxstring::createDup(OS.str());
4543 }
4544
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004545 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004546 if (D)
4547 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004548 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004549 }
4550
4551 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004552 const Stmt *S = getCursorStmt(C);
4553 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004554 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004555
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004556 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004557 }
4558
4559 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004560 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004561 ->getNameStart());
4562
4563 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004564 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004565 ->getNameStart());
4566
4567 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004568 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004569
4570 if (clang_isDeclaration(C.kind))
4571 return getDeclSpelling(getCursorDecl(C));
4572
4573 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004574 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004575 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004576 }
4577
4578 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004579 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004580 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004581 }
4582
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004583 if (C.kind == CXCursor_PackedAttr) {
4584 return cxstring::createRef("packed");
4585 }
4586
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004587 if (C.kind == CXCursor_VisibilityAttr) {
4588 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4589 switch (AA->getVisibility()) {
4590 case VisibilityAttr::VisibilityType::Default:
4591 return cxstring::createRef("default");
4592 case VisibilityAttr::VisibilityType::Hidden:
4593 return cxstring::createRef("hidden");
4594 case VisibilityAttr::VisibilityType::Protected:
4595 return cxstring::createRef("protected");
4596 }
4597 llvm_unreachable("unknown visibility type");
4598 }
4599
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004600 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004601}
4602
4603CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4604 unsigned pieceIndex,
4605 unsigned options) {
4606 if (clang_Cursor_isNull(C))
4607 return clang_getNullRange();
4608
4609 ASTContext &Ctx = getCursorContext(C);
4610
4611 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004612 const Stmt *S = getCursorStmt(C);
4613 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004614 if (pieceIndex > 0)
4615 return clang_getNullRange();
4616 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4617 }
4618
4619 return clang_getNullRange();
4620 }
4621
4622 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004623 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004624 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4625 if (pieceIndex >= ME->getNumSelectorLocs())
4626 return clang_getNullRange();
4627 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4628 }
4629 }
4630
4631 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4632 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004633 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004634 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4635 if (pieceIndex >= MD->getNumSelectorLocs())
4636 return clang_getNullRange();
4637 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4638 }
4639 }
4640
4641 if (C.kind == CXCursor_ObjCCategoryDecl ||
4642 C.kind == CXCursor_ObjCCategoryImplDecl) {
4643 if (pieceIndex > 0)
4644 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004645 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004646 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4647 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004648 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004649 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4650 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4651 }
4652
4653 if (C.kind == CXCursor_ModuleImportDecl) {
4654 if (pieceIndex > 0)
4655 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004656 if (const ImportDecl *ImportD =
4657 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004658 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4659 if (!Locs.empty())
4660 return cxloc::translateSourceRange(Ctx,
4661 SourceRange(Locs.front(), Locs.back()));
4662 }
4663 return clang_getNullRange();
4664 }
4665
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004666 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004667 C.kind == CXCursor_ConversionFunction ||
4668 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004669 if (pieceIndex > 0)
4670 return clang_getNullRange();
4671 if (const FunctionDecl *FD =
4672 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4673 DeclarationNameInfo FunctionName = FD->getNameInfo();
4674 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4675 }
4676 return clang_getNullRange();
4677 }
4678
Guy Benyei11169dd2012-12-18 14:30:41 +00004679 // FIXME: A CXCursor_InclusionDirective should give the location of the
4680 // filename, but we don't keep track of this.
4681
4682 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4683 // but we don't keep track of this.
4684
4685 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4686 // but we don't keep track of this.
4687
4688 // Default handling, give the location of the cursor.
4689
4690 if (pieceIndex > 0)
4691 return clang_getNullRange();
4692
4693 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4694 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4695 return cxloc::translateSourceRange(Ctx, Loc);
4696}
4697
Eli Bendersky44a206f2014-07-31 18:04:56 +00004698CXString clang_Cursor_getMangling(CXCursor C) {
4699 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4700 return cxstring::createEmpty();
4701
Eli Bendersky44a206f2014-07-31 18:04:56 +00004702 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004703 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004704 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4705 return cxstring::createEmpty();
4706
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004707 ASTContext &Ctx = D->getASTContext();
4708 index::CodegenNameGenerator CGNameGen(Ctx);
4709 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004710}
4711
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004712CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4713 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4714 return nullptr;
4715
4716 const Decl *D = getCursorDecl(C);
4717 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4718 return nullptr;
4719
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004720 ASTContext &Ctx = D->getASTContext();
4721 index::CodegenNameGenerator CGNameGen(Ctx);
4722 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004723 return cxstring::createSet(Manglings);
4724}
4725
Dave Lee1a532c92017-09-22 16:58:57 +00004726CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4727 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4728 return nullptr;
4729
4730 const Decl *D = getCursorDecl(C);
4731 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4732 return nullptr;
4733
4734 ASTContext &Ctx = D->getASTContext();
4735 index::CodegenNameGenerator CGNameGen(Ctx);
4736 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4737 return cxstring::createSet(Manglings);
4738}
4739
Jonathan Coe45ef5032018-01-16 10:19:56 +00004740CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4741 if (clang_Cursor_isNull(C))
4742 return 0;
4743 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4744}
4745
4746void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4747 if (Policy)
4748 delete static_cast<PrintingPolicy *>(Policy);
4749}
4750
4751unsigned
4752clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4753 enum CXPrintingPolicyProperty Property) {
4754 if (!Policy)
4755 return 0;
4756
4757 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4758 switch (Property) {
4759 case CXPrintingPolicy_Indentation:
4760 return P->Indentation;
4761 case CXPrintingPolicy_SuppressSpecifiers:
4762 return P->SuppressSpecifiers;
4763 case CXPrintingPolicy_SuppressTagKeyword:
4764 return P->SuppressTagKeyword;
4765 case CXPrintingPolicy_IncludeTagDefinition:
4766 return P->IncludeTagDefinition;
4767 case CXPrintingPolicy_SuppressScope:
4768 return P->SuppressScope;
4769 case CXPrintingPolicy_SuppressUnwrittenScope:
4770 return P->SuppressUnwrittenScope;
4771 case CXPrintingPolicy_SuppressInitializers:
4772 return P->SuppressInitializers;
4773 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4774 return P->ConstantArraySizeAsWritten;
4775 case CXPrintingPolicy_AnonymousTagLocations:
4776 return P->AnonymousTagLocations;
4777 case CXPrintingPolicy_SuppressStrongLifetime:
4778 return P->SuppressStrongLifetime;
4779 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4780 return P->SuppressLifetimeQualifiers;
4781 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4782 return P->SuppressTemplateArgsInCXXConstructors;
4783 case CXPrintingPolicy_Bool:
4784 return P->Bool;
4785 case CXPrintingPolicy_Restrict:
4786 return P->Restrict;
4787 case CXPrintingPolicy_Alignof:
4788 return P->Alignof;
4789 case CXPrintingPolicy_UnderscoreAlignof:
4790 return P->UnderscoreAlignof;
4791 case CXPrintingPolicy_UseVoidForZeroParams:
4792 return P->UseVoidForZeroParams;
4793 case CXPrintingPolicy_TerseOutput:
4794 return P->TerseOutput;
4795 case CXPrintingPolicy_PolishForDeclaration:
4796 return P->PolishForDeclaration;
4797 case CXPrintingPolicy_Half:
4798 return P->Half;
4799 case CXPrintingPolicy_MSWChar:
4800 return P->MSWChar;
4801 case CXPrintingPolicy_IncludeNewlines:
4802 return P->IncludeNewlines;
4803 case CXPrintingPolicy_MSVCFormatting:
4804 return P->MSVCFormatting;
4805 case CXPrintingPolicy_ConstantsAsWritten:
4806 return P->ConstantsAsWritten;
4807 case CXPrintingPolicy_SuppressImplicitBase:
4808 return P->SuppressImplicitBase;
4809 case CXPrintingPolicy_FullyQualifiedName:
4810 return P->FullyQualifiedName;
4811 }
4812
4813 assert(false && "Invalid CXPrintingPolicyProperty");
4814 return 0;
4815}
4816
4817void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4818 enum CXPrintingPolicyProperty Property,
4819 unsigned Value) {
4820 if (!Policy)
4821 return;
4822
4823 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4824 switch (Property) {
4825 case CXPrintingPolicy_Indentation:
4826 P->Indentation = Value;
4827 return;
4828 case CXPrintingPolicy_SuppressSpecifiers:
4829 P->SuppressSpecifiers = Value;
4830 return;
4831 case CXPrintingPolicy_SuppressTagKeyword:
4832 P->SuppressTagKeyword = Value;
4833 return;
4834 case CXPrintingPolicy_IncludeTagDefinition:
4835 P->IncludeTagDefinition = Value;
4836 return;
4837 case CXPrintingPolicy_SuppressScope:
4838 P->SuppressScope = Value;
4839 return;
4840 case CXPrintingPolicy_SuppressUnwrittenScope:
4841 P->SuppressUnwrittenScope = Value;
4842 return;
4843 case CXPrintingPolicy_SuppressInitializers:
4844 P->SuppressInitializers = Value;
4845 return;
4846 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4847 P->ConstantArraySizeAsWritten = Value;
4848 return;
4849 case CXPrintingPolicy_AnonymousTagLocations:
4850 P->AnonymousTagLocations = Value;
4851 return;
4852 case CXPrintingPolicy_SuppressStrongLifetime:
4853 P->SuppressStrongLifetime = Value;
4854 return;
4855 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4856 P->SuppressLifetimeQualifiers = Value;
4857 return;
4858 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4859 P->SuppressTemplateArgsInCXXConstructors = Value;
4860 return;
4861 case CXPrintingPolicy_Bool:
4862 P->Bool = Value;
4863 return;
4864 case CXPrintingPolicy_Restrict:
4865 P->Restrict = Value;
4866 return;
4867 case CXPrintingPolicy_Alignof:
4868 P->Alignof = Value;
4869 return;
4870 case CXPrintingPolicy_UnderscoreAlignof:
4871 P->UnderscoreAlignof = Value;
4872 return;
4873 case CXPrintingPolicy_UseVoidForZeroParams:
4874 P->UseVoidForZeroParams = Value;
4875 return;
4876 case CXPrintingPolicy_TerseOutput:
4877 P->TerseOutput = Value;
4878 return;
4879 case CXPrintingPolicy_PolishForDeclaration:
4880 P->PolishForDeclaration = Value;
4881 return;
4882 case CXPrintingPolicy_Half:
4883 P->Half = Value;
4884 return;
4885 case CXPrintingPolicy_MSWChar:
4886 P->MSWChar = Value;
4887 return;
4888 case CXPrintingPolicy_IncludeNewlines:
4889 P->IncludeNewlines = Value;
4890 return;
4891 case CXPrintingPolicy_MSVCFormatting:
4892 P->MSVCFormatting = Value;
4893 return;
4894 case CXPrintingPolicy_ConstantsAsWritten:
4895 P->ConstantsAsWritten = Value;
4896 return;
4897 case CXPrintingPolicy_SuppressImplicitBase:
4898 P->SuppressImplicitBase = Value;
4899 return;
4900 case CXPrintingPolicy_FullyQualifiedName:
4901 P->FullyQualifiedName = Value;
4902 return;
4903 }
4904
4905 assert(false && "Invalid CXPrintingPolicyProperty");
4906}
4907
4908CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4909 if (clang_Cursor_isNull(C))
4910 return cxstring::createEmpty();
4911
4912 if (clang_isDeclaration(C.kind)) {
4913 const Decl *D = getCursorDecl(C);
4914 if (!D)
4915 return cxstring::createEmpty();
4916
4917 SmallString<128> Str;
4918 llvm::raw_svector_ostream OS(Str);
4919 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4920 D->print(OS, UserPolicy ? *UserPolicy
4921 : getCursorContext(C).getPrintingPolicy());
4922
4923 return cxstring::createDup(OS.str());
4924 }
4925
4926 return cxstring::createEmpty();
4927}
4928
Guy Benyei11169dd2012-12-18 14:30:41 +00004929CXString clang_getCursorDisplayName(CXCursor C) {
4930 if (!clang_isDeclaration(C.kind))
4931 return clang_getCursorSpelling(C);
4932
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004933 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004934 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004935 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004936
4937 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004938 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004939 D = FunTmpl->getTemplatedDecl();
4940
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004941 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004942 SmallString<64> Str;
4943 llvm::raw_svector_ostream OS(Str);
4944 OS << *Function;
4945 if (Function->getPrimaryTemplate())
4946 OS << "<>";
4947 OS << "(";
4948 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4949 if (I)
4950 OS << ", ";
4951 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4952 }
4953
4954 if (Function->isVariadic()) {
4955 if (Function->getNumParams())
4956 OS << ", ";
4957 OS << "...";
4958 }
4959 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004960 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004961 }
4962
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004963 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004964 SmallString<64> Str;
4965 llvm::raw_svector_ostream OS(Str);
4966 OS << *ClassTemplate;
4967 OS << "<";
4968 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4969 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4970 if (I)
4971 OS << ", ";
4972
4973 NamedDecl *Param = Params->getParam(I);
4974 if (Param->getIdentifier()) {
4975 OS << Param->getIdentifier()->getName();
4976 continue;
4977 }
4978
4979 // There is no parameter name, which makes this tricky. Try to come up
4980 // with something useful that isn't too long.
4981 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4982 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4983 else if (NonTypeTemplateParmDecl *NTTP
4984 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4985 OS << NTTP->getType().getAsString(Policy);
4986 else
4987 OS << "template<...> class";
4988 }
4989
4990 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004991 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004992 }
4993
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004994 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00004995 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4996 // If the type was explicitly written, use that.
4997 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004998 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00004999
Benjamin Kramer9170e912013-02-22 15:46:01 +00005000 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00005001 llvm::raw_svector_ostream OS(Str);
5002 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00005003 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5004 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005005 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005006 }
5007
5008 return clang_getCursorSpelling(C);
5009}
5010
5011CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5012 switch (Kind) {
5013 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005014 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005015 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005016 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005017 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005018 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005019 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005020 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005021 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005022 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005023 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005024 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005025 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005026 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005027 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005028 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005029 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005030 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005031 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005032 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005033 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005034 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005035 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005036 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005037 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005038 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005039 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005040 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005041 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005042 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005043 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005044 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005045 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005046 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005047 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005048 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005049 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005050 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005051 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005052 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005053 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005054 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005055 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005056 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005057 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005058 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005059 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005060 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005061 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005062 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005063 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005064 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005065 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005066 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005067 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005068 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005069 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005070 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005071 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005072 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005074 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005075 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005076 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005077 case CXCursor_FixedPointLiteral:
5078 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005079 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005080 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005081 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005082 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005083 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005084 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005085 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005086 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005087 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005088 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005089 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005090 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005091 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005092 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005093 case CXCursor_OMPArraySectionExpr:
5094 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005095 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005096 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005097 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005098 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005099 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005100 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005101 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005102 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005103 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005104 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005105 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005106 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005107 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005108 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005109 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005110 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005111 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005112 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005113 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005114 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005115 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005116 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005117 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005118 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005119 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005120 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005121 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005122 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005123 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005124 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005125 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005126 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005127 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005128 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005129 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005130 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005131 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005132 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005133 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005134 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005135 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005136 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005137 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005138 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005139 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005140 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005141 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005142 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005143 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005144 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005145 case CXCursor_ObjCAvailabilityCheckExpr:
5146 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005147 case CXCursor_ObjCSelfExpr:
5148 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005149 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005150 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005151 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005152 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005153 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005154 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005155 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005156 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005157 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005158 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005159 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005160 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005161 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005162 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005163 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005164 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005165 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005166 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005167 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005168 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005169 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005170 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005171 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005172 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005173 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005174 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005175 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005176 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005177 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005178 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005179 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005180 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005181 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005182 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005183 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005184 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005185 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005186 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005187 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005188 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005189 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005190 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005191 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005192 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005193 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005194 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005195 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005196 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005197 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005198 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005199 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005200 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005201 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005202 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005203 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005204 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005205 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005206 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005207 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005208 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005209 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005210 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005211 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005212 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005213 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005214 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005215 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005216 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005217 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005218 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005219 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005220 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005221 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005222 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005223 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005224 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005225 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005226 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005227 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005228 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005229 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005230 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005231 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005232 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005233 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005234 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005235 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005236 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005237 case CXCursor_SEHLeaveStmt:
5238 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005239 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005240 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005241 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005242 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005243 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005244 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005245 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005246 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005247 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005248 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005249 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005250 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005251 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005252 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005253 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005254 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005255 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005256 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005257 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005258 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005259 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005260 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005261 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005262 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005263 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005264 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005265 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005266 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005267 case CXCursor_PackedAttr:
5268 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005269 case CXCursor_PureAttr:
5270 return cxstring::createRef("attribute(pure)");
5271 case CXCursor_ConstAttr:
5272 return cxstring::createRef("attribute(const)");
5273 case CXCursor_NoDuplicateAttr:
5274 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005275 case CXCursor_CUDAConstantAttr:
5276 return cxstring::createRef("attribute(constant)");
5277 case CXCursor_CUDADeviceAttr:
5278 return cxstring::createRef("attribute(device)");
5279 case CXCursor_CUDAGlobalAttr:
5280 return cxstring::createRef("attribute(global)");
5281 case CXCursor_CUDAHostAttr:
5282 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005283 case CXCursor_CUDASharedAttr:
5284 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005285 case CXCursor_VisibilityAttr:
5286 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005287 case CXCursor_DLLExport:
5288 return cxstring::createRef("attribute(dllexport)");
5289 case CXCursor_DLLImport:
5290 return cxstring::createRef("attribute(dllimport)");
Michael Wud092d0b2018-08-03 05:03:22 +00005291 case CXCursor_NSReturnsRetained:
5292 return cxstring::createRef("attribute(ns_returns_retained)");
5293 case CXCursor_NSReturnsNotRetained:
5294 return cxstring::createRef("attribute(ns_returns_not_retained)");
5295 case CXCursor_NSReturnsAutoreleased:
5296 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5297 case CXCursor_NSConsumesSelf:
5298 return cxstring::createRef("attribute(ns_consumes_self)");
5299 case CXCursor_NSConsumed:
5300 return cxstring::createRef("attribute(ns_consumed)");
5301 case CXCursor_ObjCException:
5302 return cxstring::createRef("attribute(objc_exception)");
5303 case CXCursor_ObjCNSObject:
5304 return cxstring::createRef("attribute(NSObject)");
5305 case CXCursor_ObjCIndependentClass:
5306 return cxstring::createRef("attribute(objc_independent_class)");
5307 case CXCursor_ObjCPreciseLifetime:
5308 return cxstring::createRef("attribute(objc_precise_lifetime)");
5309 case CXCursor_ObjCReturnsInnerPointer:
5310 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5311 case CXCursor_ObjCRequiresSuper:
5312 return cxstring::createRef("attribute(objc_requires_super)");
5313 case CXCursor_ObjCRootClass:
5314 return cxstring::createRef("attribute(objc_root_class)");
5315 case CXCursor_ObjCSubclassingRestricted:
5316 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5317 case CXCursor_ObjCExplicitProtocolImpl:
5318 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5319 case CXCursor_ObjCDesignatedInitializer:
5320 return cxstring::createRef("attribute(objc_designated_initializer)");
5321 case CXCursor_ObjCRuntimeVisible:
5322 return cxstring::createRef("attribute(objc_runtime_visible)");
5323 case CXCursor_ObjCBoxable:
5324 return cxstring::createRef("attribute(objc_boxable)");
Michael Wu58d837d2018-08-03 05:55:40 +00005325 case CXCursor_FlagEnum:
5326 return cxstring::createRef("attribute(flag_enum)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005327 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005328 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005329 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005330 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005331 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005332 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005333 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005334 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005335 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005336 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005337 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005338 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005339 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005340 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005341 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005342 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005343 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005344 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005345 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005346 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005347 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005348 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005349 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005350 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005351 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005352 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005353 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005354 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005355 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005356 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005357 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005358 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005359 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005360 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005361 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005362 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005363 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005364 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005365 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005366 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005367 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005368 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005369 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005370 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005371 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005372 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005373 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005374 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005375 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005376 return cxstring::createRef("OMPParallelDirective");
5377 case CXCursor_OMPSimdDirective:
5378 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005379 case CXCursor_OMPForDirective:
5380 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005381 case CXCursor_OMPForSimdDirective:
5382 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005383 case CXCursor_OMPSectionsDirective:
5384 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005385 case CXCursor_OMPSectionDirective:
5386 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005387 case CXCursor_OMPSingleDirective:
5388 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005389 case CXCursor_OMPMasterDirective:
5390 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005391 case CXCursor_OMPCriticalDirective:
5392 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005393 case CXCursor_OMPParallelForDirective:
5394 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005395 case CXCursor_OMPParallelForSimdDirective:
5396 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005397 case CXCursor_OMPParallelSectionsDirective:
5398 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005399 case CXCursor_OMPTaskDirective:
5400 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005401 case CXCursor_OMPTaskyieldDirective:
5402 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005403 case CXCursor_OMPBarrierDirective:
5404 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005405 case CXCursor_OMPTaskwaitDirective:
5406 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005407 case CXCursor_OMPTaskgroupDirective:
5408 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005409 case CXCursor_OMPFlushDirective:
5410 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005411 case CXCursor_OMPOrderedDirective:
5412 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005413 case CXCursor_OMPAtomicDirective:
5414 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005415 case CXCursor_OMPTargetDirective:
5416 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005417 case CXCursor_OMPTargetDataDirective:
5418 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005419 case CXCursor_OMPTargetEnterDataDirective:
5420 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005421 case CXCursor_OMPTargetExitDataDirective:
5422 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005423 case CXCursor_OMPTargetParallelDirective:
5424 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005425 case CXCursor_OMPTargetParallelForDirective:
5426 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005427 case CXCursor_OMPTargetUpdateDirective:
5428 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005429 case CXCursor_OMPTeamsDirective:
5430 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005431 case CXCursor_OMPCancellationPointDirective:
5432 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005433 case CXCursor_OMPCancelDirective:
5434 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005435 case CXCursor_OMPTaskLoopDirective:
5436 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005437 case CXCursor_OMPTaskLoopSimdDirective:
5438 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005439 case CXCursor_OMPDistributeDirective:
5440 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005441 case CXCursor_OMPDistributeParallelForDirective:
5442 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005443 case CXCursor_OMPDistributeParallelForSimdDirective:
5444 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005445 case CXCursor_OMPDistributeSimdDirective:
5446 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005447 case CXCursor_OMPTargetParallelForSimdDirective:
5448 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005449 case CXCursor_OMPTargetSimdDirective:
5450 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005451 case CXCursor_OMPTeamsDistributeDirective:
5452 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005453 case CXCursor_OMPTeamsDistributeSimdDirective:
5454 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005455 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5456 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005457 case CXCursor_OMPTeamsDistributeParallelForDirective:
5458 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005459 case CXCursor_OMPTargetTeamsDirective:
5460 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005461 case CXCursor_OMPTargetTeamsDistributeDirective:
5462 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005463 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5464 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005465 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5466 return cxstring::createRef(
5467 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005468 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5469 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005470 case CXCursor_OverloadCandidate:
5471 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005472 case CXCursor_TypeAliasTemplateDecl:
5473 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005474 case CXCursor_StaticAssert:
5475 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005476 case CXCursor_FriendDecl:
Sven van Haastregtdc2c9302019-02-11 11:00:56 +00005477 return cxstring::createRef("FriendDecl");
5478 case CXCursor_ConvergentAttr:
5479 return cxstring::createRef("attribute(convergent)");
Emilio Cobos Alvarez0a3fe502019-02-25 21:24:52 +00005480 case CXCursor_WarnUnusedAttr:
5481 return cxstring::createRef("attribute(warn_unused)");
5482 case CXCursor_WarnUnusedResultAttr:
5483 return cxstring::createRef("attribute(warn_unused_result)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005484 }
5485
5486 llvm_unreachable("Unhandled CXCursorKind");
5487}
5488
5489struct GetCursorData {
5490 SourceLocation TokenBeginLoc;
5491 bool PointsAtMacroArgExpansion;
5492 bool VisitedObjCPropertyImplDecl;
5493 SourceLocation VisitedDeclaratorDeclStartLoc;
5494 CXCursor &BestCursor;
5495
5496 GetCursorData(SourceManager &SM,
5497 SourceLocation tokenBegin, CXCursor &outputCursor)
5498 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5499 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5500 VisitedObjCPropertyImplDecl = false;
5501 }
5502};
5503
5504static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5505 CXCursor parent,
5506 CXClientData client_data) {
5507 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5508 CXCursor *BestCursor = &Data->BestCursor;
5509
5510 // If we point inside a macro argument we should provide info of what the
5511 // token is so use the actual cursor, don't replace it with a macro expansion
5512 // cursor.
5513 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5514 return CXChildVisit_Recurse;
5515
5516 if (clang_isDeclaration(cursor.kind)) {
5517 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005518 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005519 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5520 if (MD->isImplicit())
5521 return CXChildVisit_Break;
5522
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005523 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005524 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5525 // Check that when we have multiple @class references in the same line,
5526 // that later ones do not override the previous ones.
5527 // If we have:
5528 // @class Foo, Bar;
5529 // source ranges for both start at '@', so 'Bar' will end up overriding
5530 // 'Foo' even though the cursor location was at 'Foo'.
5531 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5532 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005533 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005534 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5535 if (PrevID != ID &&
5536 !PrevID->isThisDeclarationADefinition() &&
5537 !ID->isThisDeclarationADefinition())
5538 return CXChildVisit_Break;
5539 }
5540
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005541 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005542 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5543 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5544 // Check that when we have multiple declarators in the same line,
5545 // that later ones do not override the previous ones.
5546 // If we have:
5547 // int Foo, Bar;
5548 // source ranges for both start at 'int', so 'Bar' will end up overriding
5549 // 'Foo' even though the cursor location was at 'Foo'.
5550 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5551 return CXChildVisit_Break;
5552 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5553
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005554 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005555 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5556 (void)PropImp;
5557 // Check that when we have multiple @synthesize in the same line,
5558 // that later ones do not override the previous ones.
5559 // If we have:
5560 // @synthesize Foo, Bar;
5561 // source ranges for both start at '@', so 'Bar' will end up overriding
5562 // 'Foo' even though the cursor location was at 'Foo'.
5563 if (Data->VisitedObjCPropertyImplDecl)
5564 return CXChildVisit_Break;
5565 Data->VisitedObjCPropertyImplDecl = true;
5566 }
5567 }
5568
5569 if (clang_isExpression(cursor.kind) &&
5570 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005571 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005572 // Avoid having the cursor of an expression replace the declaration cursor
5573 // when the expression source range overlaps the declaration range.
5574 // This can happen for C++ constructor expressions whose range generally
5575 // include the variable declaration, e.g.:
5576 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5577 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5578 D->getLocation() == Data->TokenBeginLoc)
5579 return CXChildVisit_Break;
5580 }
5581 }
5582
5583 // If our current best cursor is the construction of a temporary object,
5584 // don't replace that cursor with a type reference, because we want
5585 // clang_getCursor() to point at the constructor.
5586 if (clang_isExpression(BestCursor->kind) &&
5587 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5588 cursor.kind == CXCursor_TypeRef) {
5589 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5590 // as having the actual point on the type reference.
5591 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5592 return CXChildVisit_Recurse;
5593 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005594
5595 // If we already have an Objective-C superclass reference, don't
5596 // update it further.
5597 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5598 return CXChildVisit_Break;
5599
Guy Benyei11169dd2012-12-18 14:30:41 +00005600 *BestCursor = cursor;
5601 return CXChildVisit_Recurse;
5602}
5603
5604CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005605 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005606 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005607 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005608 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005609
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005610 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005611 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5612
5613 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5614 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5615
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005616 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005617 CXFile SearchFile;
5618 unsigned SearchLine, SearchColumn;
5619 CXFile ResultFile;
5620 unsigned ResultLine, ResultColumn;
5621 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5622 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5623 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005624
5625 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5626 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005627 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005628 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005629 SearchFileName = clang_getFileName(SearchFile);
5630 ResultFileName = clang_getFileName(ResultFile);
5631 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5632 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005633 *Log << llvm::format("(%s:%d:%d) = %s",
5634 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5635 clang_getCString(KindSpelling))
5636 << llvm::format("(%s:%d:%d):%s%s",
5637 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5638 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005639 clang_disposeString(SearchFileName);
5640 clang_disposeString(ResultFileName);
5641 clang_disposeString(KindSpelling);
5642 clang_disposeString(USR);
5643
5644 CXCursor Definition = clang_getCursorDefinition(Result);
5645 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5646 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5647 CXString DefinitionKindSpelling
5648 = clang_getCursorKindSpelling(Definition.kind);
5649 CXFile DefinitionFile;
5650 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005651 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005652 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005653 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005654 *Log << llvm::format(" -> %s(%s:%d:%d)",
5655 clang_getCString(DefinitionKindSpelling),
5656 clang_getCString(DefinitionFileName),
5657 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005658 clang_disposeString(DefinitionFileName);
5659 clang_disposeString(DefinitionKindSpelling);
5660 }
5661 }
5662
5663 return Result;
5664}
5665
5666CXCursor clang_getNullCursor(void) {
5667 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5668}
5669
5670unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005671 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5672 // can't set consistently. For example, when visiting a DeclStmt we will set
5673 // it but we don't set it on the result of clang_getCursorDefinition for
5674 // a reference of the same declaration.
5675 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5676 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5677 // to provide that kind of info.
5678 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005679 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005680 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005681 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005682
Guy Benyei11169dd2012-12-18 14:30:41 +00005683 return X == Y;
5684}
5685
5686unsigned clang_hashCursor(CXCursor C) {
5687 unsigned Index = 0;
5688 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5689 Index = 1;
5690
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005691 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005692 std::make_pair(C.kind, C.data[Index]));
5693}
5694
5695unsigned clang_isInvalid(enum CXCursorKind K) {
5696 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5697}
5698
5699unsigned clang_isDeclaration(enum CXCursorKind K) {
5700 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005701 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5702}
5703
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005704unsigned clang_isInvalidDeclaration(CXCursor C) {
5705 if (clang_isDeclaration(C.kind)) {
5706 if (const Decl *D = getCursorDecl(C))
5707 return D->isInvalidDecl();
5708 }
5709
5710 return 0;
5711}
5712
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005713unsigned clang_isReference(enum CXCursorKind K) {
5714 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5715}
Guy Benyei11169dd2012-12-18 14:30:41 +00005716
5717unsigned clang_isExpression(enum CXCursorKind K) {
5718 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5719}
5720
5721unsigned clang_isStatement(enum CXCursorKind K) {
5722 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5723}
5724
5725unsigned clang_isAttribute(enum CXCursorKind K) {
5726 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5727}
5728
5729unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5730 return K == CXCursor_TranslationUnit;
5731}
5732
5733unsigned clang_isPreprocessing(enum CXCursorKind K) {
5734 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5735}
5736
5737unsigned clang_isUnexposed(enum CXCursorKind K) {
5738 switch (K) {
5739 case CXCursor_UnexposedDecl:
5740 case CXCursor_UnexposedExpr:
5741 case CXCursor_UnexposedStmt:
5742 case CXCursor_UnexposedAttr:
5743 return true;
5744 default:
5745 return false;
5746 }
5747}
5748
5749CXCursorKind clang_getCursorKind(CXCursor C) {
5750 return C.kind;
5751}
5752
5753CXSourceLocation clang_getCursorLocation(CXCursor C) {
5754 if (clang_isReference(C.kind)) {
5755 switch (C.kind) {
5756 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005757 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005758 = getCursorObjCSuperClassRef(C);
5759 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5760 }
5761
5762 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005763 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005764 = getCursorObjCProtocolRef(C);
5765 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5766 }
5767
5768 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005769 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005770 = getCursorObjCClassRef(C);
5771 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5772 }
5773
5774 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005775 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005776 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5777 }
5778
5779 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005780 std::pair<const TemplateDecl *, SourceLocation> P =
5781 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005782 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5783 }
5784
5785 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005786 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005787 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5788 }
5789
5790 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005791 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005792 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5793 }
5794
5795 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005796 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005797 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5798 }
5799
5800 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005801 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005802 if (!BaseSpec)
5803 return clang_getNullLocation();
5804
5805 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5806 return cxloc::translateSourceLocation(getCursorContext(C),
5807 TSInfo->getTypeLoc().getBeginLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005808
Guy Benyei11169dd2012-12-18 14:30:41 +00005809 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005810 BaseSpec->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005811 }
5812
5813 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005814 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005815 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5816 }
5817
5818 case CXCursor_OverloadedDeclRef:
5819 return cxloc::translateSourceLocation(getCursorContext(C),
5820 getCursorOverloadedDeclRef(C).second);
5821
5822 default:
5823 // FIXME: Need a way to enumerate all non-reference cases.
5824 llvm_unreachable("Missed a reference kind");
5825 }
5826 }
5827
5828 if (clang_isExpression(C.kind))
5829 return cxloc::translateSourceLocation(getCursorContext(C),
5830 getLocationFromExpr(getCursorExpr(C)));
5831
5832 if (clang_isStatement(C.kind))
5833 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005834 getCursorStmt(C)->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005835
5836 if (C.kind == CXCursor_PreprocessingDirective) {
5837 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5838 return cxloc::translateSourceLocation(getCursorContext(C), L);
5839 }
5840
5841 if (C.kind == CXCursor_MacroExpansion) {
5842 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005843 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005844 return cxloc::translateSourceLocation(getCursorContext(C), L);
5845 }
5846
5847 if (C.kind == CXCursor_MacroDefinition) {
5848 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5849 return cxloc::translateSourceLocation(getCursorContext(C), L);
5850 }
5851
5852 if (C.kind == CXCursor_InclusionDirective) {
5853 SourceLocation L
5854 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5855 return cxloc::translateSourceLocation(getCursorContext(C), L);
5856 }
5857
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005858 if (clang_isAttribute(C.kind)) {
5859 SourceLocation L
5860 = cxcursor::getCursorAttr(C)->getLocation();
5861 return cxloc::translateSourceLocation(getCursorContext(C), L);
5862 }
5863
Guy Benyei11169dd2012-12-18 14:30:41 +00005864 if (!clang_isDeclaration(C.kind))
5865 return clang_getNullLocation();
5866
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005867 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005868 if (!D)
5869 return clang_getNullLocation();
5870
5871 SourceLocation Loc = D->getLocation();
5872 // FIXME: Multiple variables declared in a single declaration
5873 // currently lack the information needed to correctly determine their
5874 // ranges when accounting for the type-specifier. We use context
5875 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5876 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005877 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005878 if (!cxcursor::isFirstInDeclGroup(C))
5879 Loc = VD->getLocation();
5880 }
5881
5882 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005883 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005884 Loc = MD->getSelectorStartLoc();
5885
5886 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5887}
5888
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005889} // end extern "C"
5890
Guy Benyei11169dd2012-12-18 14:30:41 +00005891CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5892 assert(TU);
5893
5894 // Guard against an invalid SourceLocation, or we may assert in one
5895 // of the following calls.
5896 if (SLoc.isInvalid())
5897 return clang_getNullCursor();
5898
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005899 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005900
5901 // Translate the given source location to make it point at the beginning of
5902 // the token under the cursor.
5903 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5904 CXXUnit->getASTContext().getLangOpts());
5905
5906 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5907 if (SLoc.isValid()) {
5908 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5909 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5910 /*VisitPreprocessorLast=*/true,
5911 /*VisitIncludedEntities=*/false,
5912 SourceLocation(SLoc));
5913 CursorVis.visitFileRegion();
5914 }
5915
5916 return Result;
5917}
5918
5919static SourceRange getRawCursorExtent(CXCursor C) {
5920 if (clang_isReference(C.kind)) {
5921 switch (C.kind) {
5922 case CXCursor_ObjCSuperClassRef:
5923 return getCursorObjCSuperClassRef(C).second;
5924
5925 case CXCursor_ObjCProtocolRef:
5926 return getCursorObjCProtocolRef(C).second;
5927
5928 case CXCursor_ObjCClassRef:
5929 return getCursorObjCClassRef(C).second;
5930
5931 case CXCursor_TypeRef:
5932 return getCursorTypeRef(C).second;
5933
5934 case CXCursor_TemplateRef:
5935 return getCursorTemplateRef(C).second;
5936
5937 case CXCursor_NamespaceRef:
5938 return getCursorNamespaceRef(C).second;
5939
5940 case CXCursor_MemberRef:
5941 return getCursorMemberRef(C).second;
5942
5943 case CXCursor_CXXBaseSpecifier:
5944 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5945
5946 case CXCursor_LabelRef:
5947 return getCursorLabelRef(C).second;
5948
5949 case CXCursor_OverloadedDeclRef:
5950 return getCursorOverloadedDeclRef(C).second;
5951
5952 case CXCursor_VariableRef:
5953 return getCursorVariableRef(C).second;
5954
5955 default:
5956 // FIXME: Need a way to enumerate all non-reference cases.
5957 llvm_unreachable("Missed a reference kind");
5958 }
5959 }
5960
5961 if (clang_isExpression(C.kind))
5962 return getCursorExpr(C)->getSourceRange();
5963
5964 if (clang_isStatement(C.kind))
5965 return getCursorStmt(C)->getSourceRange();
5966
5967 if (clang_isAttribute(C.kind))
5968 return getCursorAttr(C)->getRange();
5969
5970 if (C.kind == CXCursor_PreprocessingDirective)
5971 return cxcursor::getCursorPreprocessingDirective(C);
5972
5973 if (C.kind == CXCursor_MacroExpansion) {
5974 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005975 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005976 return TU->mapRangeFromPreamble(Range);
5977 }
5978
5979 if (C.kind == CXCursor_MacroDefinition) {
5980 ASTUnit *TU = getCursorASTUnit(C);
5981 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5982 return TU->mapRangeFromPreamble(Range);
5983 }
5984
5985 if (C.kind == CXCursor_InclusionDirective) {
5986 ASTUnit *TU = getCursorASTUnit(C);
5987 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5988 return TU->mapRangeFromPreamble(Range);
5989 }
5990
5991 if (C.kind == CXCursor_TranslationUnit) {
5992 ASTUnit *TU = getCursorASTUnit(C);
5993 FileID MainID = TU->getSourceManager().getMainFileID();
5994 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5995 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5996 return SourceRange(Start, End);
5997 }
5998
5999 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006000 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006001 if (!D)
6002 return SourceRange();
6003
6004 SourceRange R = D->getSourceRange();
6005 // FIXME: Multiple variables declared in a single declaration
6006 // currently lack the information needed to correctly determine their
6007 // ranges when accounting for the type-specifier. We use context
6008 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6009 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006010 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006011 if (!cxcursor::isFirstInDeclGroup(C))
6012 R.setBegin(VD->getLocation());
6013 }
6014 return R;
6015 }
6016 return SourceRange();
6017}
6018
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006019/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00006020/// the decl-specifier-seq for declarations.
6021static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6022 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006023 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006024 if (!D)
6025 return SourceRange();
6026
6027 SourceRange R = D->getSourceRange();
6028
6029 // Adjust the start of the location for declarations preceded by
6030 // declaration specifiers.
6031 SourceLocation StartLoc;
6032 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6033 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006034 StartLoc = TI->getTypeLoc().getBeginLoc();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006035 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006036 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006037 StartLoc = TI->getTypeLoc().getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006038 }
6039
6040 if (StartLoc.isValid() && R.getBegin().isValid() &&
6041 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6042 R.setBegin(StartLoc);
6043
6044 // FIXME: Multiple variables declared in a single declaration
6045 // currently lack the information needed to correctly determine their
6046 // ranges when accounting for the type-specifier. We use context
6047 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6048 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006049 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006050 if (!cxcursor::isFirstInDeclGroup(C))
6051 R.setBegin(VD->getLocation());
6052 }
6053
6054 return R;
6055 }
6056
6057 return getRawCursorExtent(C);
6058}
6059
Guy Benyei11169dd2012-12-18 14:30:41 +00006060CXSourceRange clang_getCursorExtent(CXCursor C) {
6061 SourceRange R = getRawCursorExtent(C);
6062 if (R.isInvalid())
6063 return clang_getNullRange();
6064
6065 return cxloc::translateSourceRange(getCursorContext(C), R);
6066}
6067
6068CXCursor clang_getCursorReferenced(CXCursor C) {
6069 if (clang_isInvalid(C.kind))
6070 return clang_getNullCursor();
6071
6072 CXTranslationUnit tu = getCursorTU(C);
6073 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006074 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006075 if (!D)
6076 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006077 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006078 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006079 if (const ObjCPropertyImplDecl *PropImpl =
6080 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006081 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6082 return MakeCXCursor(Property, tu);
6083
6084 return C;
6085 }
6086
6087 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006088 const Expr *E = getCursorExpr(C);
6089 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006090 if (D) {
6091 CXCursor declCursor = MakeCXCursor(D, tu);
6092 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6093 declCursor);
6094 return declCursor;
6095 }
6096
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006097 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006098 return MakeCursorOverloadedDeclRef(Ovl, tu);
6099
6100 return clang_getNullCursor();
6101 }
6102
6103 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006104 const Stmt *S = getCursorStmt(C);
6105 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006106 if (LabelDecl *label = Goto->getLabel())
6107 if (LabelStmt *labelS = label->getStmt())
6108 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6109
6110 return clang_getNullCursor();
6111 }
Richard Smith66a81862015-05-04 02:25:31 +00006112
Guy Benyei11169dd2012-12-18 14:30:41 +00006113 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006114 if (const MacroDefinitionRecord *Def =
6115 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006116 return MakeMacroDefinitionCursor(Def, tu);
6117 }
6118
6119 if (!clang_isReference(C.kind))
6120 return clang_getNullCursor();
6121
6122 switch (C.kind) {
6123 case CXCursor_ObjCSuperClassRef:
6124 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6125
6126 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006127 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6128 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006129 return MakeCXCursor(Def, tu);
6130
6131 return MakeCXCursor(Prot, tu);
6132 }
6133
6134 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006135 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6136 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006137 return MakeCXCursor(Def, tu);
6138
6139 return MakeCXCursor(Class, tu);
6140 }
6141
6142 case CXCursor_TypeRef:
6143 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6144
6145 case CXCursor_TemplateRef:
6146 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6147
6148 case CXCursor_NamespaceRef:
6149 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6150
6151 case CXCursor_MemberRef:
6152 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6153
6154 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006155 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006156 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6157 tu ));
6158 }
6159
6160 case CXCursor_LabelRef:
6161 // FIXME: We end up faking the "parent" declaration here because we
6162 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006163 return MakeCXCursor(getCursorLabelRef(C).first,
6164 cxtu::getASTUnit(tu)->getASTContext()
6165 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006166 tu);
6167
6168 case CXCursor_OverloadedDeclRef:
6169 return C;
6170
6171 case CXCursor_VariableRef:
6172 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6173
6174 default:
6175 // We would prefer to enumerate all non-reference cursor kinds here.
6176 llvm_unreachable("Unhandled reference cursor kind");
6177 }
6178}
6179
6180CXCursor clang_getCursorDefinition(CXCursor C) {
6181 if (clang_isInvalid(C.kind))
6182 return clang_getNullCursor();
6183
6184 CXTranslationUnit TU = getCursorTU(C);
6185
6186 bool WasReference = false;
6187 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6188 C = clang_getCursorReferenced(C);
6189 WasReference = true;
6190 }
6191
6192 if (C.kind == CXCursor_MacroExpansion)
6193 return clang_getCursorReferenced(C);
6194
6195 if (!clang_isDeclaration(C.kind))
6196 return clang_getNullCursor();
6197
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006198 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006199 if (!D)
6200 return clang_getNullCursor();
6201
6202 switch (D->getKind()) {
6203 // Declaration kinds that don't really separate the notions of
6204 // declaration and definition.
6205 case Decl::Namespace:
6206 case Decl::Typedef:
6207 case Decl::TypeAlias:
6208 case Decl::TypeAliasTemplate:
6209 case Decl::TemplateTypeParm:
6210 case Decl::EnumConstant:
6211 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006212 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006213 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006214 case Decl::IndirectField:
6215 case Decl::ObjCIvar:
6216 case Decl::ObjCAtDefsField:
6217 case Decl::ImplicitParam:
6218 case Decl::ParmVar:
6219 case Decl::NonTypeTemplateParm:
6220 case Decl::TemplateTemplateParm:
6221 case Decl::ObjCCategoryImpl:
6222 case Decl::ObjCImplementation:
6223 case Decl::AccessSpec:
6224 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006225 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006226 case Decl::ObjCPropertyImpl:
6227 case Decl::FileScopeAsm:
6228 case Decl::StaticAssert:
6229 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006230 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006231 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006232 case Decl::Label: // FIXME: Is this right??
6233 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006234 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006235 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006236 case Decl::OMPThreadPrivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006237 case Decl::OMPDeclareReduction:
Michael Kruse251e1482019-02-01 20:25:04 +00006238 case Decl::OMPDeclareMapper:
Kelvin Li1408f912018-09-26 04:28:39 +00006239 case Decl::OMPRequires:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006240 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006241 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006242 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006243 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006244 case Decl::UsingPack:
Guy Benyei11169dd2012-12-18 14:30:41 +00006245 return C;
6246
6247 // Declaration kinds that don't make any sense here, but are
6248 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006249 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006250 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006251 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006252 break;
6253
6254 // Declaration kinds for which the definition is not resolvable.
6255 case Decl::UnresolvedUsingTypename:
6256 case Decl::UnresolvedUsingValue:
6257 break;
6258
6259 case Decl::UsingDirective:
6260 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6261 TU);
6262
6263 case Decl::NamespaceAlias:
6264 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6265
6266 case Decl::Enum:
6267 case Decl::Record:
6268 case Decl::CXXRecord:
6269 case Decl::ClassTemplateSpecialization:
6270 case Decl::ClassTemplatePartialSpecialization:
6271 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6272 return MakeCXCursor(Def, TU);
6273 return clang_getNullCursor();
6274
6275 case Decl::Function:
6276 case Decl::CXXMethod:
6277 case Decl::CXXConstructor:
6278 case Decl::CXXDestructor:
6279 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006280 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006281 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006282 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006283 return clang_getNullCursor();
6284 }
6285
Larisse Voufo39a1e502013-08-06 01:03:05 +00006286 case Decl::Var:
6287 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006288 case Decl::VarTemplatePartialSpecialization:
6289 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006290 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006291 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006292 return MakeCXCursor(Def, TU);
6293 return clang_getNullCursor();
6294 }
6295
6296 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006297 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006298 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6299 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6300 return clang_getNullCursor();
6301 }
6302
6303 case Decl::ClassTemplate: {
6304 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6305 ->getDefinition())
6306 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6307 TU);
6308 return clang_getNullCursor();
6309 }
6310
Larisse Voufo39a1e502013-08-06 01:03:05 +00006311 case Decl::VarTemplate: {
6312 if (VarDecl *Def =
6313 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6314 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6315 return clang_getNullCursor();
6316 }
6317
Guy Benyei11169dd2012-12-18 14:30:41 +00006318 case Decl::Using:
6319 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6320 D->getLocation(), TU);
6321
6322 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006323 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006324 return clang_getCursorDefinition(
6325 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6326 TU));
6327
6328 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006329 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006330 if (Method->isThisDeclarationADefinition())
6331 return C;
6332
6333 // Dig out the method definition in the associated
6334 // @implementation, if we have it.
6335 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006336 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006337 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6338 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6339 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6340 Method->isInstanceMethod()))
6341 if (Def->isThisDeclarationADefinition())
6342 return MakeCXCursor(Def, TU);
6343
6344 return clang_getNullCursor();
6345 }
6346
6347 case Decl::ObjCCategory:
6348 if (ObjCCategoryImplDecl *Impl
6349 = cast<ObjCCategoryDecl>(D)->getImplementation())
6350 return MakeCXCursor(Impl, TU);
6351 return clang_getNullCursor();
6352
6353 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006354 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006355 return MakeCXCursor(Def, TU);
6356 return clang_getNullCursor();
6357
6358 case Decl::ObjCInterface: {
6359 // There are two notions of a "definition" for an Objective-C
6360 // class: the interface and its implementation. When we resolved a
6361 // reference to an Objective-C class, produce the @interface as
6362 // the definition; when we were provided with the interface,
6363 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006364 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006365 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006366 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006367 return MakeCXCursor(Def, TU);
6368 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6369 return MakeCXCursor(Impl, TU);
6370 return clang_getNullCursor();
6371 }
6372
6373 case Decl::ObjCProperty:
6374 // FIXME: We don't really know where to find the
6375 // ObjCPropertyImplDecls that implement this property.
6376 return clang_getNullCursor();
6377
6378 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006379 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006380 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006381 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006382 return MakeCXCursor(Def, TU);
6383
6384 return clang_getNullCursor();
6385
6386 case Decl::Friend:
6387 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6388 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6389 return clang_getNullCursor();
6390
6391 case Decl::FriendTemplate:
6392 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6393 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6394 return clang_getNullCursor();
6395 }
6396
6397 return clang_getNullCursor();
6398}
6399
6400unsigned clang_isCursorDefinition(CXCursor C) {
6401 if (!clang_isDeclaration(C.kind))
6402 return 0;
6403
6404 return clang_getCursorDefinition(C) == C;
6405}
6406
6407CXCursor clang_getCanonicalCursor(CXCursor C) {
6408 if (!clang_isDeclaration(C.kind))
6409 return C;
6410
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006411 if (const Decl *D = getCursorDecl(C)) {
6412 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006413 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6414 return MakeCXCursor(CatD, getCursorTU(C));
6415
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006416 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6417 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006418 return MakeCXCursor(IFD, getCursorTU(C));
6419
6420 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6421 }
6422
6423 return C;
6424}
6425
6426int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6427 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6428}
6429
6430unsigned clang_getNumOverloadedDecls(CXCursor C) {
6431 if (C.kind != CXCursor_OverloadedDeclRef)
6432 return 0;
6433
6434 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006435 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006436 return E->getNumDecls();
6437
6438 if (OverloadedTemplateStorage *S
6439 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6440 return S->size();
6441
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006442 const Decl *D = Storage.get<const Decl *>();
6443 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006444 return Using->shadow_size();
6445
6446 return 0;
6447}
6448
6449CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6450 if (cursor.kind != CXCursor_OverloadedDeclRef)
6451 return clang_getNullCursor();
6452
6453 if (index >= clang_getNumOverloadedDecls(cursor))
6454 return clang_getNullCursor();
6455
6456 CXTranslationUnit TU = getCursorTU(cursor);
6457 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006458 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006459 return MakeCXCursor(E->decls_begin()[index], TU);
6460
6461 if (OverloadedTemplateStorage *S
6462 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6463 return MakeCXCursor(S->begin()[index], TU);
6464
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006465 const Decl *D = Storage.get<const Decl *>();
6466 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006467 // FIXME: This is, unfortunately, linear time.
6468 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6469 std::advance(Pos, index);
6470 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6471 }
6472
6473 return clang_getNullCursor();
6474}
6475
6476void clang_getDefinitionSpellingAndExtent(CXCursor C,
6477 const char **startBuf,
6478 const char **endBuf,
6479 unsigned *startLine,
6480 unsigned *startColumn,
6481 unsigned *endLine,
6482 unsigned *endColumn) {
6483 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006484 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006485 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6486
6487 SourceManager &SM = FD->getASTContext().getSourceManager();
6488 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6489 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6490 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6491 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6492 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6493 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6494}
6495
6496
6497CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6498 unsigned PieceIndex) {
6499 RefNamePieces Pieces;
6500
6501 switch (C.kind) {
6502 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006503 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006504 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6505 E->getQualifierLoc().getSourceRange());
6506 break;
6507
6508 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006509 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6510 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6511 Pieces =
6512 buildPieces(NameFlags, false, E->getNameInfo(),
6513 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6514 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006515 break;
6516
6517 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006518 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006519 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006520 const Expr *Callee = OCE->getCallee();
6521 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006522 Callee = ICE->getSubExpr();
6523
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006524 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006525 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6526 DRE->getQualifierLoc().getSourceRange());
6527 }
6528 break;
6529
6530 default:
6531 break;
6532 }
6533
6534 if (Pieces.empty()) {
6535 if (PieceIndex == 0)
6536 return clang_getCursorExtent(C);
6537 } else if (PieceIndex < Pieces.size()) {
6538 SourceRange R = Pieces[PieceIndex];
6539 if (R.isValid())
6540 return cxloc::translateSourceRange(getCursorContext(C), R);
6541 }
6542
6543 return clang_getNullRange();
6544}
6545
6546void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006547 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6548 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006549}
6550
6551void clang_executeOnThread(void (*fn)(void*), void *user_data,
6552 unsigned stack_size) {
6553 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6554}
6555
Guy Benyei11169dd2012-12-18 14:30:41 +00006556//===----------------------------------------------------------------------===//
6557// Token-based Operations.
6558//===----------------------------------------------------------------------===//
6559
6560/* CXToken layout:
6561 * int_data[0]: a CXTokenKind
6562 * int_data[1]: starting token location
6563 * int_data[2]: token length
6564 * int_data[3]: reserved
6565 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6566 * otherwise unused.
6567 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006568CXTokenKind clang_getTokenKind(CXToken CXTok) {
6569 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6570}
6571
6572CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6573 switch (clang_getTokenKind(CXTok)) {
6574 case CXToken_Identifier:
6575 case CXToken_Keyword:
6576 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006577 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006578 ->getNameStart());
6579
6580 case CXToken_Literal: {
6581 // We have stashed the starting pointer in the ptr_data field. Use it.
6582 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006583 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006584 }
6585
6586 case CXToken_Punctuation:
6587 case CXToken_Comment:
6588 break;
6589 }
6590
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006591 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006592 LOG_BAD_TU(TU);
6593 return cxstring::createEmpty();
6594 }
6595
Guy Benyei11169dd2012-12-18 14:30:41 +00006596 // We have to find the starting buffer pointer the hard way, by
6597 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006598 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006599 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006600 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006601
6602 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6603 std::pair<FileID, unsigned> LocInfo
6604 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6605 bool Invalid = false;
6606 StringRef Buffer
6607 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6608 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006609 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006610
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006611 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006612}
6613
6614CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006615 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006616 LOG_BAD_TU(TU);
6617 return clang_getNullLocation();
6618 }
6619
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006620 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006621 if (!CXXUnit)
6622 return clang_getNullLocation();
6623
6624 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6625 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6626}
6627
6628CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006629 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006630 LOG_BAD_TU(TU);
6631 return clang_getNullRange();
6632 }
6633
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006634 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006635 if (!CXXUnit)
6636 return clang_getNullRange();
6637
6638 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6639 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6640}
6641
6642static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6643 SmallVectorImpl<CXToken> &CXTokens) {
6644 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6645 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006646 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006647 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006648 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006649
6650 // Cannot tokenize across files.
6651 if (BeginLocInfo.first != EndLocInfo.first)
6652 return;
6653
6654 // Create a lexer
6655 bool Invalid = false;
6656 StringRef Buffer
6657 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6658 if (Invalid)
6659 return;
6660
6661 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6662 CXXUnit->getASTContext().getLangOpts(),
6663 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6664 Lex.SetCommentRetentionState(true);
6665
6666 // Lex tokens until we hit the end of the range.
6667 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6668 Token Tok;
6669 bool previousWasAt = false;
6670 do {
6671 // Lex the next token
6672 Lex.LexFromRawLexer(Tok);
6673 if (Tok.is(tok::eof))
6674 break;
6675
6676 // Initialize the CXToken.
6677 CXToken CXTok;
6678
6679 // - Common fields
6680 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6681 CXTok.int_data[2] = Tok.getLength();
6682 CXTok.int_data[3] = 0;
6683
6684 // - Kind-specific fields
6685 if (Tok.isLiteral()) {
6686 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006687 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006688 } else if (Tok.is(tok::raw_identifier)) {
6689 // Lookup the identifier to determine whether we have a keyword.
6690 IdentifierInfo *II
6691 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6692
6693 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6694 CXTok.int_data[0] = CXToken_Keyword;
6695 }
6696 else {
6697 CXTok.int_data[0] = Tok.is(tok::identifier)
6698 ? CXToken_Identifier
6699 : CXToken_Keyword;
6700 }
6701 CXTok.ptr_data = II;
6702 } else if (Tok.is(tok::comment)) {
6703 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006704 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006705 } else {
6706 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006707 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006708 }
6709 CXTokens.push_back(CXTok);
6710 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006711 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006712}
6713
Ivan Donchevskii3957e482018-06-13 12:37:08 +00006714CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6715 LOG_FUNC_SECTION {
6716 *Log << TU << ' ' << Location;
6717 }
6718
6719 if (isNotUsableTU(TU)) {
6720 LOG_BAD_TU(TU);
6721 return NULL;
6722 }
6723
6724 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6725 if (!CXXUnit)
6726 return NULL;
6727
6728 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6729 if (Begin.isInvalid())
6730 return NULL;
6731 SourceManager &SM = CXXUnit->getSourceManager();
6732 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6733 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6734
6735 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6736
6737 SmallVector<CXToken, 32> CXTokens;
6738 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6739
6740 if (CXTokens.empty())
6741 return NULL;
6742
6743 CXTokens.resize(1);
6744 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6745
6746 memmove(Token, CXTokens.data(), sizeof(CXToken));
6747 return Token;
6748}
6749
Guy Benyei11169dd2012-12-18 14:30:41 +00006750void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6751 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006752 LOG_FUNC_SECTION {
6753 *Log << TU << ' ' << Range;
6754 }
6755
Guy Benyei11169dd2012-12-18 14:30:41 +00006756 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006757 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006758 if (NumTokens)
6759 *NumTokens = 0;
6760
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006761 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006762 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006763 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006764 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006765
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006766 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006767 if (!CXXUnit || !Tokens || !NumTokens)
6768 return;
6769
6770 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6771
6772 SourceRange R = cxloc::translateCXSourceRange(Range);
6773 if (R.isInvalid())
6774 return;
6775
6776 SmallVector<CXToken, 32> CXTokens;
6777 getTokens(CXXUnit, R, CXTokens);
6778
6779 if (CXTokens.empty())
6780 return;
6781
Serge Pavlov52525732018-02-21 02:02:39 +00006782 *Tokens = static_cast<CXToken *>(
6783 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006784 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6785 *NumTokens = CXTokens.size();
6786}
6787
6788void clang_disposeTokens(CXTranslationUnit TU,
6789 CXToken *Tokens, unsigned NumTokens) {
6790 free(Tokens);
6791}
6792
Guy Benyei11169dd2012-12-18 14:30:41 +00006793//===----------------------------------------------------------------------===//
6794// Token annotation APIs.
6795//===----------------------------------------------------------------------===//
6796
Guy Benyei11169dd2012-12-18 14:30:41 +00006797static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6798 CXCursor parent,
6799 CXClientData client_data);
6800static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6801 CXClientData client_data);
6802
6803namespace {
6804class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006805 CXToken *Tokens;
6806 CXCursor *Cursors;
6807 unsigned NumTokens;
6808 unsigned TokIdx;
6809 unsigned PreprocessingTokIdx;
6810 CursorVisitor AnnotateVis;
6811 SourceManager &SrcMgr;
6812 bool HasContextSensitiveKeywords;
6813
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006814 struct PostChildrenAction {
6815 CXCursor cursor;
6816 enum Action { Invalid, Ignore, Postpone } action;
6817 };
6818 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
6819
Guy Benyei11169dd2012-12-18 14:30:41 +00006820 struct PostChildrenInfo {
6821 CXCursor Cursor;
6822 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006823 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006824 unsigned BeforeChildrenTokenIdx;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006825 PostChildrenActions ChildActions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006826 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006827 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006828
6829 CXToken &getTok(unsigned Idx) {
6830 assert(Idx < NumTokens);
6831 return Tokens[Idx];
6832 }
6833 const CXToken &getTok(unsigned Idx) const {
6834 assert(Idx < NumTokens);
6835 return Tokens[Idx];
6836 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006837 bool MoreTokens() const { return TokIdx < NumTokens; }
6838 unsigned NextToken() const { return TokIdx; }
6839 void AdvanceToken() { ++TokIdx; }
6840 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006841 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006842 }
6843 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006844 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006845 }
6846 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006847 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006848 }
6849
6850 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006851 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006852 SourceRange);
6853
6854public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006855 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006856 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006857 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006858 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006859 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006860 AnnotateTokensVisitor, this,
6861 /*VisitPreprocessorLast=*/true,
6862 /*VisitIncludedEntities=*/false,
6863 RegionOfInterest,
6864 /*VisitDeclsOnly=*/false,
6865 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006866 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006867 HasContextSensitiveKeywords(false) { }
6868
6869 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6870 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006871 bool IsIgnoredChildCursor(CXCursor cursor) const;
6872 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
6873
Guy Benyei11169dd2012-12-18 14:30:41 +00006874 bool postVisitChildren(CXCursor cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006875 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
6876 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
6877
Guy Benyei11169dd2012-12-18 14:30:41 +00006878 void AnnotateTokens();
6879
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006880 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00006881 /// context-sensitive keywords.
6882 bool hasContextSensitiveKeywords() const {
6883 return HasContextSensitiveKeywords;
6884 }
6885
6886 ~AnnotateTokensWorker() {
6887 assert(PostChildrenInfos.empty());
6888 }
6889};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006890}
Guy Benyei11169dd2012-12-18 14:30:41 +00006891
6892void AnnotateTokensWorker::AnnotateTokens() {
6893 // Walk the AST within the region of interest, annotating tokens
6894 // along the way.
6895 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006896}
Guy Benyei11169dd2012-12-18 14:30:41 +00006897
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006898bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
6899 if (PostChildrenInfos.empty())
6900 return false;
6901
6902 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
6903 if (ChildAction.cursor == cursor &&
6904 ChildAction.action == PostChildrenAction::Ignore) {
6905 return true;
6906 }
6907 }
6908
6909 return false;
6910}
6911
6912const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
6913 if (!clang_isExpression(Cursor.kind))
6914 return nullptr;
6915
6916 const Expr *E = getCursorExpr(Cursor);
6917 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
6918 const OverloadedOperatorKind Kind = OCE->getOperator();
6919 if (Kind == OO_Call || Kind == OO_Subscript)
6920 return OCE;
6921 }
6922
6923 return nullptr;
6924}
6925
6926AnnotateTokensWorker::PostChildrenActions
6927AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
6928 PostChildrenActions actions;
6929
6930 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
6931 // visited before the arguments to the operator call. For the Call and
6932 // Subscript operator the range of this DeclRefExpr includes the whole call
6933 // expression, so that all tokens in that range would be mapped to the
6934 // operator function, including the tokens of the arguments. To avoid that,
6935 // ensure to visit this DeclRefExpr as last node.
6936 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
6937 const Expr *Callee = OCE->getCallee();
6938 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
6939 const Expr *SubExpr = ICE->getSubExpr();
6940 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
Fangrui Songcabb36d2018-11-20 08:00:00 +00006941 const Decl *parentDecl = getCursorDecl(Cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006942 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
6943
6944 // Visit the DeclRefExpr as last.
6945 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
6946 actions.push_back({cxChild, PostChildrenAction::Postpone});
6947
6948 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
6949 // wide range as the DeclRefExpr. We can skip visiting this entirely.
6950 cxChild = MakeCXCursor(ICE, parentDecl, TU);
6951 actions.push_back({cxChild, PostChildrenAction::Ignore});
6952 }
6953 }
6954 }
6955
6956 return actions;
6957}
6958
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006959static inline void updateCursorAnnotation(CXCursor &Cursor,
6960 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006961 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006962 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006963 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006964}
6965
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006966/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00006967//// between the cursor location and the source range is the same as
6968/// \arg compResult.
6969///
6970/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6971/// Pass RangeOverlap to annotate tokens inside a range.
6972void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6973 RangeComparisonResult compResult,
6974 SourceRange range) {
6975 while (MoreTokens()) {
6976 const unsigned I = NextToken();
6977 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006978 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6979 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006980
6981 SourceLocation TokLoc = GetTokenLoc(I);
6982 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006983 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006984 AdvanceToken();
6985 continue;
6986 }
6987 break;
6988 }
6989}
6990
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006991/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006992/// \returns true if it advanced beyond all macro tokens, false otherwise.
6993bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00006994 CXCursor updateC,
6995 RangeComparisonResult compResult,
6996 SourceRange range) {
6997 assert(MoreTokens());
6998 assert(isFunctionMacroToken(NextToken()) &&
6999 "Should be called only for macro arg tokens");
7000
7001 // This works differently than annotateAndAdvanceTokens; because expanded
7002 // macro arguments can have arbitrary translation-unit source order, we do not
7003 // advance the token index one by one until a token fails the range test.
7004 // We only advance once past all of the macro arg tokens if all of them
7005 // pass the range test. If one of them fails we keep the token index pointing
7006 // at the start of the macro arg tokens so that the failing token will be
7007 // annotated by a subsequent annotation try.
7008
7009 bool atLeastOneCompFail = false;
7010
7011 unsigned I = NextToken();
7012 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7013 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7014 if (TokLoc.isFileID())
7015 continue; // not macro arg token, it's parens or comma.
7016 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7017 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7018 Cursors[I] = updateC;
7019 } else
7020 atLeastOneCompFail = true;
7021 }
7022
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007023 if (atLeastOneCompFail)
7024 return false;
7025
7026 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7027 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00007028}
7029
7030enum CXChildVisitResult
7031AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007032 SourceRange cursorRange = getRawCursorExtent(cursor);
7033 if (cursorRange.isInvalid())
7034 return CXChildVisit_Recurse;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007035
7036 if (IsIgnoredChildCursor(cursor))
7037 return CXChildVisit_Continue;
7038
Guy Benyei11169dd2012-12-18 14:30:41 +00007039 if (!HasContextSensitiveKeywords) {
7040 // Objective-C properties can have context-sensitive keywords.
7041 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007042 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007043 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7044 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7045 }
7046 // Objective-C methods can have context-sensitive keywords.
7047 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7048 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007049 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007050 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7051 if (Method->getObjCDeclQualifier())
7052 HasContextSensitiveKeywords = true;
7053 else {
David Majnemer59f77922016-06-24 04:05:48 +00007054 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00007055 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007056 HasContextSensitiveKeywords = true;
7057 break;
7058 }
7059 }
7060 }
7061 }
7062 }
7063 // C++ methods can have context-sensitive keywords.
7064 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007065 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007066 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7067 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7068 HasContextSensitiveKeywords = true;
7069 }
7070 }
7071 // C++ classes can have context-sensitive keywords.
7072 else if (cursor.kind == CXCursor_StructDecl ||
7073 cursor.kind == CXCursor_ClassDecl ||
7074 cursor.kind == CXCursor_ClassTemplate ||
7075 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007076 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007077 if (D->hasAttr<FinalAttr>())
7078 HasContextSensitiveKeywords = true;
7079 }
7080 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00007081
7082 // Don't override a property annotation with its getter/setter method.
7083 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7084 parent.kind == CXCursor_ObjCPropertyDecl)
7085 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007086
7087 if (clang_isPreprocessing(cursor.kind)) {
7088 // Items in the preprocessing record are kept separate from items in
7089 // declarations, so we keep a separate token index.
7090 unsigned SavedTokIdx = TokIdx;
7091 TokIdx = PreprocessingTokIdx;
7092
7093 // Skip tokens up until we catch up to the beginning of the preprocessing
7094 // entry.
7095 while (MoreTokens()) {
7096 const unsigned I = NextToken();
7097 SourceLocation TokLoc = GetTokenLoc(I);
7098 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7099 case RangeBefore:
7100 AdvanceToken();
7101 continue;
7102 case RangeAfter:
7103 case RangeOverlap:
7104 break;
7105 }
7106 break;
7107 }
7108
7109 // Look at all of the tokens within this range.
7110 while (MoreTokens()) {
7111 const unsigned I = NextToken();
7112 SourceLocation TokLoc = GetTokenLoc(I);
7113 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7114 case RangeBefore:
7115 llvm_unreachable("Infeasible");
7116 case RangeAfter:
7117 break;
7118 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007119 // For macro expansions, just note where the beginning of the macro
7120 // expansion occurs.
7121 if (cursor.kind == CXCursor_MacroExpansion) {
7122 if (TokLoc == cursorRange.getBegin())
7123 Cursors[I] = cursor;
7124 AdvanceToken();
7125 break;
7126 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007127 // We may have already annotated macro names inside macro definitions.
7128 if (Cursors[I].kind != CXCursor_MacroExpansion)
7129 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007130 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007131 continue;
7132 }
7133 break;
7134 }
7135
7136 // Save the preprocessing token index; restore the non-preprocessing
7137 // token index.
7138 PreprocessingTokIdx = TokIdx;
7139 TokIdx = SavedTokIdx;
7140 return CXChildVisit_Recurse;
7141 }
7142
7143 if (cursorRange.isInvalid())
7144 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007145
7146 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007147 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007148 const enum CXCursorKind K = clang_getCursorKind(parent);
7149 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007150 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7151 // Attributes are annotated out-of-order, skip tokens until we reach it.
7152 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007153 ? clang_getNullCursor() : parent;
7154
7155 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7156
7157 // Avoid having the cursor of an expression "overwrite" the annotation of the
7158 // variable declaration that it belongs to.
7159 // This can happen for C++ constructor expressions whose range generally
7160 // include the variable declaration, e.g.:
7161 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007162 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00007163 const Expr *E = getCursorExpr(cursor);
Fangrui Songcabb36d2018-11-20 08:00:00 +00007164 if (const Decl *D = getCursorDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007165 const unsigned I = NextToken();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007166 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7167 E->getBeginLoc() == D->getLocation() &&
7168 E->getBeginLoc() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007169 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007170 AdvanceToken();
7171 }
7172 }
7173 }
7174
7175 // Before recursing into the children keep some state that we are going
7176 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7177 // extra work after the child nodes are visited.
7178 // Note that we don't call VisitChildren here to avoid traversing statements
7179 // code-recursively which can blow the stack.
7180
7181 PostChildrenInfo Info;
7182 Info.Cursor = cursor;
7183 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007184 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007185 Info.BeforeChildrenTokenIdx = NextToken();
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007186 Info.ChildActions = DetermineChildActions(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007187 PostChildrenInfos.push_back(Info);
7188
7189 return CXChildVisit_Recurse;
7190}
7191
7192bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7193 if (PostChildrenInfos.empty())
7194 return false;
7195 const PostChildrenInfo &Info = PostChildrenInfos.back();
7196 if (!clang_equalCursors(Info.Cursor, cursor))
7197 return false;
7198
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007199 HandlePostPonedChildCursors(Info);
7200
Guy Benyei11169dd2012-12-18 14:30:41 +00007201 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7202 const unsigned AfterChildren = NextToken();
7203 SourceRange cursorRange = Info.CursorRange;
7204
7205 // Scan the tokens that are at the end of the cursor, but are not captured
7206 // but the child cursors.
7207 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7208
7209 // Scan the tokens that are at the beginning of the cursor, but are not
7210 // capture by the child cursors.
7211 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7212 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7213 break;
7214
7215 Cursors[I] = cursor;
7216 }
7217
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007218 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7219 // encountered the attribute cursor.
7220 if (clang_isAttribute(cursor.kind))
7221 TokIdx = Info.BeforeReachingCursorIdx;
7222
Guy Benyei11169dd2012-12-18 14:30:41 +00007223 PostChildrenInfos.pop_back();
7224 return false;
7225}
7226
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007227void AnnotateTokensWorker::HandlePostPonedChildCursors(
7228 const PostChildrenInfo &Info) {
7229 for (const auto &ChildAction : Info.ChildActions) {
7230 if (ChildAction.action == PostChildrenAction::Postpone) {
7231 HandlePostPonedChildCursor(ChildAction.cursor,
7232 Info.BeforeChildrenTokenIdx);
7233 }
7234 }
7235}
7236
7237void AnnotateTokensWorker::HandlePostPonedChildCursor(
7238 CXCursor Cursor, unsigned StartTokenIndex) {
7239 const auto flags = CXNameRange_WantQualifier | CXNameRange_WantQualifier;
7240 unsigned I = StartTokenIndex;
7241
7242 // The bracket tokens of a Call or Subscript operator are mapped to
7243 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7244 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7245 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
7246 const CXSourceRange CXRefNameRange =
7247 clang_getCursorReferenceNameRange(Cursor, flags, RefNameRangeNr);
7248 if (clang_Range_isNull(CXRefNameRange))
7249 break; // All ranges handled.
7250
7251 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7252 while (I < NumTokens) {
7253 const SourceLocation TokenLocation = GetTokenLoc(I);
7254 if (!TokenLocation.isValid())
7255 break;
7256
7257 // Adapt the end range, because LocationCompare() reports
7258 // RangeOverlap even for the not-inclusive end location.
7259 const SourceLocation fixedEnd =
7260 RefNameRange.getEnd().getLocWithOffset(-1);
7261 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7262
7263 const RangeComparisonResult ComparisonResult =
7264 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7265
7266 if (ComparisonResult == RangeOverlap) {
7267 Cursors[I++] = Cursor;
7268 } else if (ComparisonResult == RangeBefore) {
7269 ++I; // Not relevant token, check next one.
7270 } else if (ComparisonResult == RangeAfter) {
7271 break; // All tokens updated for current range, check next.
7272 }
7273 }
7274 }
7275}
7276
Guy Benyei11169dd2012-12-18 14:30:41 +00007277static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7278 CXCursor parent,
7279 CXClientData client_data) {
7280 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7281}
7282
7283static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7284 CXClientData client_data) {
7285 return static_cast<AnnotateTokensWorker*>(client_data)->
7286 postVisitChildren(cursor);
7287}
7288
7289namespace {
7290
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007291/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007292/// and mark tokens that are macro arguments. This info is used by the
7293/// AnnotateTokensWorker.
7294class MarkMacroArgTokensVisitor {
7295 SourceManager &SM;
7296 CXToken *Tokens;
7297 unsigned NumTokens;
7298 unsigned CurIdx;
7299
7300public:
7301 MarkMacroArgTokensVisitor(SourceManager &SM,
7302 CXToken *tokens, unsigned numTokens)
7303 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7304
7305 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7306 if (cursor.kind != CXCursor_MacroExpansion)
7307 return CXChildVisit_Continue;
7308
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007309 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007310 if (macroRange.getBegin() == macroRange.getEnd())
7311 return CXChildVisit_Continue; // it's not a function macro.
7312
7313 for (; CurIdx < NumTokens; ++CurIdx) {
7314 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7315 macroRange.getBegin()))
7316 break;
7317 }
7318
7319 if (CurIdx == NumTokens)
7320 return CXChildVisit_Break;
7321
7322 for (; CurIdx < NumTokens; ++CurIdx) {
7323 SourceLocation tokLoc = getTokenLoc(CurIdx);
7324 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7325 break;
7326
7327 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7328 }
7329
7330 if (CurIdx == NumTokens)
7331 return CXChildVisit_Break;
7332
7333 return CXChildVisit_Continue;
7334 }
7335
7336private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007337 CXToken &getTok(unsigned Idx) {
7338 assert(Idx < NumTokens);
7339 return Tokens[Idx];
7340 }
7341 const CXToken &getTok(unsigned Idx) const {
7342 assert(Idx < NumTokens);
7343 return Tokens[Idx];
7344 }
7345
Guy Benyei11169dd2012-12-18 14:30:41 +00007346 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007347 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007348 }
7349
7350 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7351 // The third field is reserved and currently not used. Use it here
7352 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007353 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007354 }
7355};
7356
7357} // end anonymous namespace
7358
7359static CXChildVisitResult
7360MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7361 CXClientData client_data) {
7362 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7363 parent);
7364}
7365
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007366/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007367/// \returns true if lexing was finished, false otherwise.
7368static bool lexNext(Lexer &Lex, Token &Tok,
7369 unsigned &NextIdx, unsigned NumTokens) {
7370 if (NextIdx >= NumTokens)
7371 return true;
7372
7373 ++NextIdx;
7374 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007375 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007376}
7377
Guy Benyei11169dd2012-12-18 14:30:41 +00007378static void annotatePreprocessorTokens(CXTranslationUnit TU,
7379 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007380 CXCursor *Cursors,
7381 CXToken *Tokens,
7382 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007383 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007384
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007385 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007386 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7387 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007388 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007389 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007390 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007391
7392 if (BeginLocInfo.first != EndLocInfo.first)
7393 return;
7394
7395 StringRef Buffer;
7396 bool Invalid = false;
7397 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7398 if (Buffer.empty() || Invalid)
7399 return;
7400
7401 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7402 CXXUnit->getASTContext().getLangOpts(),
7403 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7404 Buffer.end());
7405 Lex.SetCommentRetentionState(true);
7406
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007407 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007408 // Lex tokens in raw mode until we hit the end of the range, to avoid
7409 // entering #includes or expanding macros.
7410 while (true) {
7411 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007412 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7413 break;
7414 unsigned TokIdx = NextIdx-1;
7415 assert(Tok.getLocation() ==
7416 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007417
7418 reprocess:
7419 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007420 // We have found a preprocessing directive. Annotate the tokens
7421 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007422 //
7423 // FIXME: Some simple tests here could identify macro definitions and
7424 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007425
7426 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007427 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7428 break;
7429
Craig Topper69186e72014-06-08 08:38:04 +00007430 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007431 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007432 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7433 break;
7434
7435 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007436 IdentifierInfo &II =
7437 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007438 SourceLocation MappedTokLoc =
7439 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7440 MI = getMacroInfo(II, MappedTokLoc, TU);
7441 }
7442 }
7443
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007444 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007445 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007446 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7447 finished = true;
7448 break;
7449 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007450 // If we are in a macro definition, check if the token was ever a
7451 // macro name and annotate it if that's the case.
7452 if (MI) {
7453 SourceLocation SaveLoc = Tok.getLocation();
7454 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007455 MacroDefinitionRecord *MacroDef =
7456 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007457 Tok.setLocation(SaveLoc);
7458 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007459 Cursors[NextIdx - 1] =
7460 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007461 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007462 } while (!Tok.isAtStartOfLine());
7463
7464 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7465 assert(TokIdx <= LastIdx);
7466 SourceLocation EndLoc =
7467 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7468 CXCursor Cursor =
7469 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7470
7471 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007472 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007473
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007474 if (finished)
7475 break;
7476 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007477 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007478 }
7479}
7480
7481// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007482static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7483 CXToken *Tokens, unsigned NumTokens,
7484 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007485 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007486 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7487 setThreadBackgroundPriority();
7488
7489 // Determine the region of interest, which contains all of the tokens.
7490 SourceRange RegionOfInterest;
7491 RegionOfInterest.setBegin(
7492 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7493 RegionOfInterest.setEnd(
7494 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7495 Tokens[NumTokens-1])));
7496
Guy Benyei11169dd2012-12-18 14:30:41 +00007497 // Relex the tokens within the source range to look for preprocessing
7498 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007499 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007500
7501 // If begin location points inside a macro argument, set it to the expansion
7502 // location so we can have the full context when annotating semantically.
7503 {
7504 SourceManager &SM = CXXUnit->getSourceManager();
7505 SourceLocation Loc =
7506 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7507 if (Loc.isMacroID())
7508 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7509 }
7510
Guy Benyei11169dd2012-12-18 14:30:41 +00007511 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7512 // Search and mark tokens that are macro argument expansions.
7513 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7514 Tokens, NumTokens);
7515 CursorVisitor MacroArgMarker(TU,
7516 MarkMacroArgTokensVisitorDelegate, &Visitor,
7517 /*VisitPreprocessorLast=*/true,
7518 /*VisitIncludedEntities=*/false,
7519 RegionOfInterest);
7520 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7521 }
7522
7523 // Annotate all of the source locations in the region of interest that map to
7524 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007525 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007526
7527 // FIXME: We use a ridiculous stack size here because the data-recursion
7528 // algorithm uses a large stack frame than the non-data recursive version,
7529 // and AnnotationTokensWorker currently transforms the data-recursion
7530 // algorithm back into a traditional recursion by explicitly calling
7531 // VisitChildren(). We will need to remove this explicit recursive call.
7532 W.AnnotateTokens();
7533
7534 // If we ran into any entities that involve context-sensitive keywords,
7535 // take another pass through the tokens to mark them as such.
7536 if (W.hasContextSensitiveKeywords()) {
7537 for (unsigned I = 0; I != NumTokens; ++I) {
7538 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7539 continue;
7540
7541 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7542 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007543 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007544 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7545 if (Property->getPropertyAttributesAsWritten() != 0 &&
7546 llvm::StringSwitch<bool>(II->getName())
7547 .Case("readonly", true)
7548 .Case("assign", true)
7549 .Case("unsafe_unretained", true)
7550 .Case("readwrite", true)
7551 .Case("retain", true)
7552 .Case("copy", true)
7553 .Case("nonatomic", true)
7554 .Case("atomic", true)
7555 .Case("getter", true)
7556 .Case("setter", true)
7557 .Case("strong", true)
7558 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007559 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007560 .Default(false))
7561 Tokens[I].int_data[0] = CXToken_Keyword;
7562 }
7563 continue;
7564 }
7565
7566 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7567 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7568 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7569 if (llvm::StringSwitch<bool>(II->getName())
7570 .Case("in", true)
7571 .Case("out", true)
7572 .Case("inout", true)
7573 .Case("oneway", true)
7574 .Case("bycopy", true)
7575 .Case("byref", true)
7576 .Default(false))
7577 Tokens[I].int_data[0] = CXToken_Keyword;
7578 continue;
7579 }
7580
7581 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7582 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7583 Tokens[I].int_data[0] = CXToken_Keyword;
7584 continue;
7585 }
7586 }
7587 }
7588}
7589
Guy Benyei11169dd2012-12-18 14:30:41 +00007590void clang_annotateTokens(CXTranslationUnit TU,
7591 CXToken *Tokens, unsigned NumTokens,
7592 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007593 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007594 LOG_BAD_TU(TU);
7595 return;
7596 }
7597 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007598 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007599 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007600 }
7601
7602 LOG_FUNC_SECTION {
7603 *Log << TU << ' ';
7604 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7605 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7606 *Log << clang_getRange(bloc, eloc);
7607 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007608
7609 // Any token we don't specifically annotate will have a NULL cursor.
7610 CXCursor C = clang_getNullCursor();
7611 for (unsigned I = 0; I != NumTokens; ++I)
7612 Cursors[I] = C;
7613
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007614 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007615 if (!CXXUnit)
7616 return;
7617
7618 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007619
7620 auto AnnotateTokensImpl = [=]() {
7621 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7622 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007623 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007624 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007625 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7626 }
7627}
7628
Guy Benyei11169dd2012-12-18 14:30:41 +00007629//===----------------------------------------------------------------------===//
7630// Operations for querying linkage of a cursor.
7631//===----------------------------------------------------------------------===//
7632
Guy Benyei11169dd2012-12-18 14:30:41 +00007633CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7634 if (!clang_isDeclaration(cursor.kind))
7635 return CXLinkage_Invalid;
7636
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007637 const Decl *D = cxcursor::getCursorDecl(cursor);
7638 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007639 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007640 case NoLinkage:
7641 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007642 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007643 case InternalLinkage: return CXLinkage_Internal;
7644 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007645 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007646 case ExternalLinkage: return CXLinkage_External;
7647 };
7648
7649 return CXLinkage_Invalid;
7650}
Guy Benyei11169dd2012-12-18 14:30:41 +00007651
7652//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007653// Operations for querying visibility of a cursor.
7654//===----------------------------------------------------------------------===//
7655
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007656CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7657 if (!clang_isDeclaration(cursor.kind))
7658 return CXVisibility_Invalid;
7659
7660 const Decl *D = cxcursor::getCursorDecl(cursor);
7661 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7662 switch (ND->getVisibility()) {
7663 case HiddenVisibility: return CXVisibility_Hidden;
7664 case ProtectedVisibility: return CXVisibility_Protected;
7665 case DefaultVisibility: return CXVisibility_Default;
7666 };
7667
7668 return CXVisibility_Invalid;
7669}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007670
7671//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007672// Operations for querying language of a cursor.
7673//===----------------------------------------------------------------------===//
7674
7675static CXLanguageKind getDeclLanguage(const Decl *D) {
7676 if (!D)
7677 return CXLanguage_C;
7678
7679 switch (D->getKind()) {
7680 default:
7681 break;
7682 case Decl::ImplicitParam:
7683 case Decl::ObjCAtDefsField:
7684 case Decl::ObjCCategory:
7685 case Decl::ObjCCategoryImpl:
7686 case Decl::ObjCCompatibleAlias:
7687 case Decl::ObjCImplementation:
7688 case Decl::ObjCInterface:
7689 case Decl::ObjCIvar:
7690 case Decl::ObjCMethod:
7691 case Decl::ObjCProperty:
7692 case Decl::ObjCPropertyImpl:
7693 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007694 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007695 return CXLanguage_ObjC;
7696 case Decl::CXXConstructor:
7697 case Decl::CXXConversion:
7698 case Decl::CXXDestructor:
7699 case Decl::CXXMethod:
7700 case Decl::CXXRecord:
7701 case Decl::ClassTemplate:
7702 case Decl::ClassTemplatePartialSpecialization:
7703 case Decl::ClassTemplateSpecialization:
7704 case Decl::Friend:
7705 case Decl::FriendTemplate:
7706 case Decl::FunctionTemplate:
7707 case Decl::LinkageSpec:
7708 case Decl::Namespace:
7709 case Decl::NamespaceAlias:
7710 case Decl::NonTypeTemplateParm:
7711 case Decl::StaticAssert:
7712 case Decl::TemplateTemplateParm:
7713 case Decl::TemplateTypeParm:
7714 case Decl::UnresolvedUsingTypename:
7715 case Decl::UnresolvedUsingValue:
7716 case Decl::Using:
7717 case Decl::UsingDirective:
7718 case Decl::UsingShadow:
7719 return CXLanguage_CPlusPlus;
7720 }
7721
7722 return CXLanguage_C;
7723}
7724
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007725static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7726 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007727 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007728
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007729 switch (D->getAvailability()) {
7730 case AR_Available:
7731 case AR_NotYetIntroduced:
7732 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007733 return getCursorAvailabilityForDecl(
7734 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007735 return CXAvailability_Available;
7736
7737 case AR_Deprecated:
7738 return CXAvailability_Deprecated;
7739
7740 case AR_Unavailable:
7741 return CXAvailability_NotAvailable;
7742 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007743
7744 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007745}
7746
Guy Benyei11169dd2012-12-18 14:30:41 +00007747enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7748 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007749 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7750 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007751
7752 return CXAvailability_Available;
7753}
7754
7755static CXVersion convertVersion(VersionTuple In) {
7756 CXVersion Out = { -1, -1, -1 };
7757 if (In.empty())
7758 return Out;
7759
7760 Out.Major = In.getMajor();
7761
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007762 Optional<unsigned> Minor = In.getMinor();
7763 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007764 Out.Minor = *Minor;
7765 else
7766 return Out;
7767
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007768 Optional<unsigned> Subminor = In.getSubminor();
7769 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007770 Out.Subminor = *Subminor;
7771
7772 return Out;
7773}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007774
Alex Lorenz1345ea22017-06-12 19:06:30 +00007775static void getCursorPlatformAvailabilityForDecl(
7776 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7777 int *always_unavailable, CXString *unavailable_message,
7778 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007779 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007780 for (auto A : D->attrs()) {
7781 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007782 HadAvailAttr = true;
7783 if (always_deprecated)
7784 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007785 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007786 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007787 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007788 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007789 continue;
7790 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007791
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007792 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007793 HadAvailAttr = true;
7794 if (always_unavailable)
7795 *always_unavailable = 1;
7796 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007797 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007798 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7799 }
7800 continue;
7801 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007802
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007803 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007804 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007805 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007806 }
7807 }
7808
7809 if (!HadAvailAttr)
7810 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7811 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007812 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7813 deprecated_message, always_unavailable, unavailable_message,
7814 AvailabilityAttrs);
7815
7816 if (AvailabilityAttrs.empty())
7817 return;
7818
Fangrui Song55fab262018-09-26 22:16:28 +00007819 llvm::sort(AvailabilityAttrs,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007820 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7821 return LHS->getPlatform()->getName() <
7822 RHS->getPlatform()->getName();
Fangrui Song55fab262018-09-26 22:16:28 +00007823 });
Alex Lorenz1345ea22017-06-12 19:06:30 +00007824 ASTContext &Ctx = D->getASTContext();
7825 auto It = std::unique(
7826 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7827 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7828 if (LHS->getPlatform() != RHS->getPlatform())
7829 return false;
7830
7831 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7832 LHS->getDeprecated() == RHS->getDeprecated() &&
7833 LHS->getObsoleted() == RHS->getObsoleted() &&
7834 LHS->getMessage() == RHS->getMessage() &&
7835 LHS->getReplacement() == RHS->getReplacement())
7836 return true;
7837
7838 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7839 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7840 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7841 return false;
7842
7843 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7844 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7845
7846 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7847 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7848 if (LHS->getMessage().empty())
7849 LHS->setMessage(Ctx, RHS->getMessage());
7850 if (LHS->getReplacement().empty())
7851 LHS->setReplacement(Ctx, RHS->getReplacement());
7852 }
7853
7854 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7855 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7856 if (LHS->getMessage().empty())
7857 LHS->setMessage(Ctx, RHS->getMessage());
7858 if (LHS->getReplacement().empty())
7859 LHS->setReplacement(Ctx, RHS->getReplacement());
7860 }
7861
7862 return true;
7863 });
7864 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007865}
7866
Alex Lorenz1345ea22017-06-12 19:06:30 +00007867int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007868 CXString *deprecated_message,
7869 int *always_unavailable,
7870 CXString *unavailable_message,
7871 CXPlatformAvailability *availability,
7872 int availability_size) {
7873 if (always_deprecated)
7874 *always_deprecated = 0;
7875 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007876 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007877 if (always_unavailable)
7878 *always_unavailable = 0;
7879 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007880 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007881
Guy Benyei11169dd2012-12-18 14:30:41 +00007882 if (!clang_isDeclaration(cursor.kind))
7883 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007884
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007885 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007886 if (!D)
7887 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007888
Alex Lorenz1345ea22017-06-12 19:06:30 +00007889 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7890 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7891 always_unavailable, unavailable_message,
7892 AvailabilityAttrs);
7893 for (const auto &Avail :
7894 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7895 .take_front(availability_size))) {
7896 availability[Avail.index()].Platform =
7897 cxstring::createDup(Avail.value()->getPlatform()->getName());
7898 availability[Avail.index()].Introduced =
7899 convertVersion(Avail.value()->getIntroduced());
7900 availability[Avail.index()].Deprecated =
7901 convertVersion(Avail.value()->getDeprecated());
7902 availability[Avail.index()].Obsoleted =
7903 convertVersion(Avail.value()->getObsoleted());
7904 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7905 availability[Avail.index()].Message =
7906 cxstring::createDup(Avail.value()->getMessage());
7907 }
7908
7909 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007910}
Alex Lorenz1345ea22017-06-12 19:06:30 +00007911
Guy Benyei11169dd2012-12-18 14:30:41 +00007912void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7913 clang_disposeString(availability->Platform);
7914 clang_disposeString(availability->Message);
7915}
7916
7917CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7918 if (clang_isDeclaration(cursor.kind))
7919 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7920
7921 return CXLanguage_Invalid;
7922}
7923
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00007924CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7925 const Decl *D = cxcursor::getCursorDecl(cursor);
7926 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7927 switch (VD->getTLSKind()) {
7928 case VarDecl::TLS_None:
7929 return CXTLS_None;
7930 case VarDecl::TLS_Dynamic:
7931 return CXTLS_Dynamic;
7932 case VarDecl::TLS_Static:
7933 return CXTLS_Static;
7934 }
7935 }
7936
7937 return CXTLS_None;
7938}
7939
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007940 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007941 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00007942 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007943static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007944 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007945 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007946
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007947 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007948 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7949 return FunTmpl;
7950
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007951 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007952 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7953 return ClassTmpl;
7954
7955 return D;
7956}
7957
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007958
7959enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7960 StorageClass sc = SC_None;
7961 const Decl *D = getCursorDecl(C);
7962 if (D) {
7963 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7964 sc = FD->getStorageClass();
7965 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7966 sc = VD->getStorageClass();
7967 } else {
7968 return CX_SC_Invalid;
7969 }
7970 } else {
7971 return CX_SC_Invalid;
7972 }
7973 switch (sc) {
7974 case SC_None:
7975 return CX_SC_None;
7976 case SC_Extern:
7977 return CX_SC_Extern;
7978 case SC_Static:
7979 return CX_SC_Static;
7980 case SC_PrivateExtern:
7981 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007982 case SC_Auto:
7983 return CX_SC_Auto;
7984 case SC_Register:
7985 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007986 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007987 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007988}
7989
Guy Benyei11169dd2012-12-18 14:30:41 +00007990CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7991 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007992 if (const Decl *D = getCursorDecl(cursor)) {
7993 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00007994 if (!DC)
7995 return clang_getNullCursor();
7996
7997 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7998 getCursorTU(cursor));
7999 }
8000 }
8001
8002 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008003 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00008004 return MakeCXCursor(D, getCursorTU(cursor));
8005 }
8006
8007 return clang_getNullCursor();
8008}
8009
8010CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8011 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008012 if (const Decl *D = getCursorDecl(cursor)) {
8013 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008014 if (!DC)
8015 return clang_getNullCursor();
8016
8017 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8018 getCursorTU(cursor));
8019 }
8020 }
8021
8022 // FIXME: Note that we can't easily compute the lexical context of a
8023 // statement or expression, so we return nothing.
8024 return clang_getNullCursor();
8025}
8026
8027CXFile clang_getIncludedFile(CXCursor cursor) {
8028 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00008029 return nullptr;
8030
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008031 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00008032 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00008033}
8034
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008035unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8036 if (C.kind != CXCursor_ObjCPropertyDecl)
8037 return CXObjCPropertyAttr_noattr;
8038
8039 unsigned Result = CXObjCPropertyAttr_noattr;
8040 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8041 ObjCPropertyDecl::PropertyAttributeKind Attr =
8042 PD->getPropertyAttributesAsWritten();
8043
8044#define SET_CXOBJCPROP_ATTR(A) \
8045 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8046 Result |= CXObjCPropertyAttr_##A
8047 SET_CXOBJCPROP_ATTR(readonly);
8048 SET_CXOBJCPROP_ATTR(getter);
8049 SET_CXOBJCPROP_ATTR(assign);
8050 SET_CXOBJCPROP_ATTR(readwrite);
8051 SET_CXOBJCPROP_ATTR(retain);
8052 SET_CXOBJCPROP_ATTR(copy);
8053 SET_CXOBJCPROP_ATTR(nonatomic);
8054 SET_CXOBJCPROP_ATTR(setter);
8055 SET_CXOBJCPROP_ATTR(atomic);
8056 SET_CXOBJCPROP_ATTR(weak);
8057 SET_CXOBJCPROP_ATTR(strong);
8058 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00008059 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008060#undef SET_CXOBJCPROP_ATTR
8061
8062 return Result;
8063}
8064
Michael Wu6e88f532018-08-03 05:38:29 +00008065CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8066 if (C.kind != CXCursor_ObjCPropertyDecl)
8067 return cxstring::createNull();
8068
8069 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8070 Selector sel = PD->getGetterName();
8071 if (sel.isNull())
8072 return cxstring::createNull();
8073
8074 return cxstring::createDup(sel.getAsString());
8075}
8076
8077CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8078 if (C.kind != CXCursor_ObjCPropertyDecl)
8079 return cxstring::createNull();
8080
8081 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8082 Selector sel = PD->getSetterName();
8083 if (sel.isNull())
8084 return cxstring::createNull();
8085
8086 return cxstring::createDup(sel.getAsString());
8087}
8088
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00008089unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8090 if (!clang_isDeclaration(C.kind))
8091 return CXObjCDeclQualifier_None;
8092
8093 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8094 const Decl *D = getCursorDecl(C);
8095 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8096 QT = MD->getObjCDeclQualifier();
8097 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8098 QT = PD->getObjCDeclQualifier();
8099 if (QT == Decl::OBJC_TQ_None)
8100 return CXObjCDeclQualifier_None;
8101
8102 unsigned Result = CXObjCDeclQualifier_None;
8103 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
8104 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
8105 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
8106 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
8107 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
8108 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
8109
8110 return Result;
8111}
8112
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00008113unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8114 if (!clang_isDeclaration(C.kind))
8115 return 0;
8116
8117 const Decl *D = getCursorDecl(C);
8118 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8119 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8120 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8121 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8122
8123 return 0;
8124}
8125
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00008126unsigned clang_Cursor_isVariadic(CXCursor C) {
8127 if (!clang_isDeclaration(C.kind))
8128 return 0;
8129
8130 const Decl *D = getCursorDecl(C);
8131 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8132 return FD->isVariadic();
8133 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8134 return MD->isVariadic();
8135
8136 return 0;
8137}
8138
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008139unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8140 CXString *language, CXString *definedIn,
8141 unsigned *isGenerated) {
8142 if (!clang_isDeclaration(C.kind))
8143 return 0;
8144
8145 const Decl *D = getCursorDecl(C);
8146
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00008147 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008148 if (language)
8149 *language = cxstring::createDup(attr->getLanguage());
8150 if (definedIn)
8151 *definedIn = cxstring::createDup(attr->getDefinedIn());
8152 if (isGenerated)
8153 *isGenerated = attr->getGeneratedDeclaration();
8154 return 1;
8155 }
8156 return 0;
8157}
8158
Guy Benyei11169dd2012-12-18 14:30:41 +00008159CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8160 if (!clang_isDeclaration(C.kind))
8161 return clang_getNullRange();
8162
8163 const Decl *D = getCursorDecl(C);
8164 ASTContext &Context = getCursorContext(C);
8165 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8166 if (!RC)
8167 return clang_getNullRange();
8168
8169 return cxloc::translateSourceRange(Context, RC->getSourceRange());
8170}
8171
8172CXString clang_Cursor_getRawCommentText(CXCursor C) {
8173 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008174 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008175
8176 const Decl *D = getCursorDecl(C);
8177 ASTContext &Context = getCursorContext(C);
8178 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8179 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8180 StringRef();
8181
8182 // Don't duplicate the string because RawText points directly into source
8183 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008184 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008185}
8186
8187CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8188 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008189 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008190
8191 const Decl *D = getCursorDecl(C);
8192 const ASTContext &Context = getCursorContext(C);
8193 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8194
8195 if (RC) {
8196 StringRef BriefText = RC->getBriefText(Context);
8197
8198 // Don't duplicate the string because RawComment ensures that this memory
8199 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008200 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008201 }
8202
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008203 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008204}
8205
Guy Benyei11169dd2012-12-18 14:30:41 +00008206CXModule clang_Cursor_getModule(CXCursor C) {
8207 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008208 if (const ImportDecl *ImportD =
8209 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00008210 return ImportD->getImportedModule();
8211 }
8212
Craig Topper69186e72014-06-08 08:38:04 +00008213 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008214}
8215
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008216CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8217 if (isNotUsableTU(TU)) {
8218 LOG_BAD_TU(TU);
8219 return nullptr;
8220 }
8221 if (!File)
8222 return nullptr;
8223 FileEntry *FE = static_cast<FileEntry *>(File);
8224
8225 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8226 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8227 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8228
Richard Smithfeb54b62014-10-23 02:01:19 +00008229 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008230}
8231
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008232CXFile clang_Module_getASTFile(CXModule CXMod) {
8233 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008234 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008235 Module *Mod = static_cast<Module*>(CXMod);
8236 return const_cast<FileEntry *>(Mod->getASTFile());
8237}
8238
Guy Benyei11169dd2012-12-18 14:30:41 +00008239CXModule clang_Module_getParent(CXModule CXMod) {
8240 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008241 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008242 Module *Mod = static_cast<Module*>(CXMod);
8243 return Mod->Parent;
8244}
8245
8246CXString clang_Module_getName(CXModule CXMod) {
8247 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008248 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008249 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008250 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00008251}
8252
8253CXString clang_Module_getFullName(CXModule CXMod) {
8254 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008255 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008256 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008257 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008258}
8259
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008260int clang_Module_isSystem(CXModule CXMod) {
8261 if (!CXMod)
8262 return 0;
8263 Module *Mod = static_cast<Module*>(CXMod);
8264 return Mod->IsSystem;
8265}
8266
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008267unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8268 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008269 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008270 LOG_BAD_TU(TU);
8271 return 0;
8272 }
8273 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008274 return 0;
8275 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008276 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8277 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8278 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008279}
8280
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008281CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8282 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008283 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008284 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008285 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008286 }
8287 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008288 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008289 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008290 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008291
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008292 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8293 if (Index < TopHeaders.size())
8294 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008295
Craig Topper69186e72014-06-08 08:38:04 +00008296 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008297}
8298
Guy Benyei11169dd2012-12-18 14:30:41 +00008299//===----------------------------------------------------------------------===//
8300// C++ AST instrospection.
8301//===----------------------------------------------------------------------===//
8302
Jonathan Coe29565352016-04-27 12:48:25 +00008303unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8304 if (!clang_isDeclaration(C.kind))
8305 return 0;
8306
8307 const Decl *D = cxcursor::getCursorDecl(C);
8308 const CXXConstructorDecl *Constructor =
8309 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8310 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8311}
8312
8313unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8314 if (!clang_isDeclaration(C.kind))
8315 return 0;
8316
8317 const Decl *D = cxcursor::getCursorDecl(C);
8318 const CXXConstructorDecl *Constructor =
8319 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8320 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8321}
8322
8323unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8324 if (!clang_isDeclaration(C.kind))
8325 return 0;
8326
8327 const Decl *D = cxcursor::getCursorDecl(C);
8328 const CXXConstructorDecl *Constructor =
8329 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8330 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8331}
8332
8333unsigned clang_CXXConstructor_isConvertingConstructor(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 // Passing 'false' excludes constructors marked 'explicit'.
8341 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8342}
8343
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008344unsigned clang_CXXField_isMutable(CXCursor C) {
8345 if (!clang_isDeclaration(C.kind))
8346 return 0;
8347
8348 if (const auto D = cxcursor::getCursorDecl(C))
8349 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8350 return FD->isMutable() ? 1 : 0;
8351 return 0;
8352}
8353
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008354unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8355 if (!clang_isDeclaration(C.kind))
8356 return 0;
8357
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008358 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008359 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008360 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008361 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8362}
8363
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008364unsigned clang_CXXMethod_isConst(CXCursor C) {
8365 if (!clang_isDeclaration(C.kind))
8366 return 0;
8367
8368 const Decl *D = cxcursor::getCursorDecl(C);
8369 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008370 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008371 return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008372}
8373
Jonathan Coe29565352016-04-27 12:48:25 +00008374unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8375 if (!clang_isDeclaration(C.kind))
8376 return 0;
8377
8378 const Decl *D = cxcursor::getCursorDecl(C);
8379 const CXXMethodDecl *Method =
8380 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8381 return (Method && Method->isDefaulted()) ? 1 : 0;
8382}
8383
Guy Benyei11169dd2012-12-18 14:30:41 +00008384unsigned clang_CXXMethod_isStatic(CXCursor C) {
8385 if (!clang_isDeclaration(C.kind))
8386 return 0;
8387
Dmitri Gribenkod15bb302013-01-23 17:25:27 +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;
Guy Benyei11169dd2012-12-18 14:30:41 +00008391 return (Method && Method->isStatic()) ? 1 : 0;
8392}
8393
8394unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8395 if (!clang_isDeclaration(C.kind))
8396 return 0;
8397
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008398 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008399 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008400 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008401 return (Method && Method->isVirtual()) ? 1 : 0;
8402}
Guy Benyei11169dd2012-12-18 14:30:41 +00008403
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008404unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8405 if (!clang_isDeclaration(C.kind))
8406 return 0;
8407
8408 const auto *D = cxcursor::getCursorDecl(C);
8409 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8410 if (RD)
8411 RD = RD->getDefinition();
8412 return (RD && RD->isAbstract()) ? 1 : 0;
8413}
8414
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008415unsigned clang_EnumDecl_isScoped(CXCursor C) {
8416 if (!clang_isDeclaration(C.kind))
8417 return 0;
8418
8419 const Decl *D = cxcursor::getCursorDecl(C);
8420 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8421 return (Enum && Enum->isScoped()) ? 1 : 0;
8422}
8423
Guy Benyei11169dd2012-12-18 14:30:41 +00008424//===----------------------------------------------------------------------===//
8425// Attribute introspection.
8426//===----------------------------------------------------------------------===//
8427
Guy Benyei11169dd2012-12-18 14:30:41 +00008428CXType clang_getIBOutletCollectionType(CXCursor C) {
8429 if (C.kind != CXCursor_IBOutletCollectionAttr)
8430 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8431
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008432 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008433 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8434
8435 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8436}
Guy Benyei11169dd2012-12-18 14:30:41 +00008437
8438//===----------------------------------------------------------------------===//
8439// Inspecting memory usage.
8440//===----------------------------------------------------------------------===//
8441
8442typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8443
8444static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8445 enum CXTUResourceUsageKind k,
8446 unsigned long amount) {
8447 CXTUResourceUsageEntry entry = { k, amount };
8448 entries.push_back(entry);
8449}
8450
Guy Benyei11169dd2012-12-18 14:30:41 +00008451const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8452 const char *str = "";
8453 switch (kind) {
8454 case CXTUResourceUsage_AST:
8455 str = "ASTContext: expressions, declarations, and types";
8456 break;
8457 case CXTUResourceUsage_Identifiers:
8458 str = "ASTContext: identifiers";
8459 break;
8460 case CXTUResourceUsage_Selectors:
8461 str = "ASTContext: selectors";
8462 break;
8463 case CXTUResourceUsage_GlobalCompletionResults:
8464 str = "Code completion: cached global results";
8465 break;
8466 case CXTUResourceUsage_SourceManagerContentCache:
8467 str = "SourceManager: content cache allocator";
8468 break;
8469 case CXTUResourceUsage_AST_SideTables:
8470 str = "ASTContext: side tables";
8471 break;
8472 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8473 str = "SourceManager: malloc'ed memory buffers";
8474 break;
8475 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8476 str = "SourceManager: mmap'ed memory buffers";
8477 break;
8478 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8479 str = "ExternalASTSource: malloc'ed memory buffers";
8480 break;
8481 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8482 str = "ExternalASTSource: mmap'ed memory buffers";
8483 break;
8484 case CXTUResourceUsage_Preprocessor:
8485 str = "Preprocessor: malloc'ed memory";
8486 break;
8487 case CXTUResourceUsage_PreprocessingRecord:
8488 str = "Preprocessor: PreprocessingRecord";
8489 break;
8490 case CXTUResourceUsage_SourceManager_DataStructures:
8491 str = "SourceManager: data structures and tables";
8492 break;
8493 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8494 str = "Preprocessor: header search tables";
8495 break;
8496 }
8497 return str;
8498}
8499
8500CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008501 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008502 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008503 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008504 return usage;
8505 }
8506
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008507 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008508 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008509 ASTContext &astContext = astUnit->getASTContext();
8510
8511 // How much memory is used by AST nodes and types?
8512 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8513 (unsigned long) astContext.getASTAllocatedMemory());
8514
8515 // How much memory is used by identifiers?
8516 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8517 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8518
8519 // How much memory is used for selectors?
8520 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8521 (unsigned long) astContext.Selectors.getTotalMemory());
8522
8523 // How much memory is used by ASTContext's side tables?
8524 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8525 (unsigned long) astContext.getSideTableAllocatedMemory());
8526
8527 // How much memory is used for caching global code completion results?
8528 unsigned long completionBytes = 0;
8529 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008530 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008531 completionBytes = completionAllocator->getTotalMemory();
8532 }
8533 createCXTUResourceUsageEntry(*entries,
8534 CXTUResourceUsage_GlobalCompletionResults,
8535 completionBytes);
8536
8537 // How much memory is being used by SourceManager's content cache?
8538 createCXTUResourceUsageEntry(*entries,
8539 CXTUResourceUsage_SourceManagerContentCache,
8540 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8541
8542 // How much memory is being used by the MemoryBuffer's in SourceManager?
8543 const SourceManager::MemoryBufferSizes &srcBufs =
8544 astUnit->getSourceManager().getMemoryBufferSizes();
8545
8546 createCXTUResourceUsageEntry(*entries,
8547 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8548 (unsigned long) srcBufs.malloc_bytes);
8549 createCXTUResourceUsageEntry(*entries,
8550 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8551 (unsigned long) srcBufs.mmap_bytes);
8552 createCXTUResourceUsageEntry(*entries,
8553 CXTUResourceUsage_SourceManager_DataStructures,
8554 (unsigned long) astContext.getSourceManager()
8555 .getDataStructureSizes());
8556
8557 // How much memory is being used by the ExternalASTSource?
8558 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8559 const ExternalASTSource::MemoryBufferSizes &sizes =
8560 esrc->getMemoryBufferSizes();
8561
8562 createCXTUResourceUsageEntry(*entries,
8563 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8564 (unsigned long) sizes.malloc_bytes);
8565 createCXTUResourceUsageEntry(*entries,
8566 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8567 (unsigned long) sizes.mmap_bytes);
8568 }
8569
8570 // How much memory is being used by the Preprocessor?
8571 Preprocessor &pp = astUnit->getPreprocessor();
8572 createCXTUResourceUsageEntry(*entries,
8573 CXTUResourceUsage_Preprocessor,
8574 pp.getTotalMemory());
8575
8576 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8577 createCXTUResourceUsageEntry(*entries,
8578 CXTUResourceUsage_PreprocessingRecord,
8579 pRec->getTotalMemory());
8580 }
8581
8582 createCXTUResourceUsageEntry(*entries,
8583 CXTUResourceUsage_Preprocessor_HeaderSearch,
8584 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008585
Guy Benyei11169dd2012-12-18 14:30:41 +00008586 CXTUResourceUsage usage = { (void*) entries.get(),
8587 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008588 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008589 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008590 return usage;
8591}
8592
8593void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8594 if (usage.data)
8595 delete (MemUsageEntries*) usage.data;
8596}
8597
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008598CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8599 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008600 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008601 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008602
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008603 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008604 LOG_BAD_TU(TU);
8605 return skipped;
8606 }
8607
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008608 if (!file)
8609 return skipped;
8610
8611 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8612 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8613 if (!ppRec)
8614 return skipped;
8615
8616 ASTContext &Ctx = astUnit->getASTContext();
8617 SourceManager &sm = Ctx.getSourceManager();
8618 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8619 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008620 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008621
8622 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8623 std::vector<SourceRange> wantedRanges;
8624 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8625 i != ei; ++i) {
8626 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8627 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008628 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8629 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008630 }
8631
8632 skipped->count = wantedRanges.size();
8633 skipped->ranges = new CXSourceRange[skipped->count];
8634 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8635 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8636
8637 return skipped;
8638}
8639
Cameron Desrochersd8091282016-08-18 15:43:55 +00008640CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8641 CXSourceRangeList *skipped = new CXSourceRangeList;
8642 skipped->count = 0;
8643 skipped->ranges = nullptr;
8644
8645 if (isNotUsableTU(TU)) {
8646 LOG_BAD_TU(TU);
8647 return skipped;
8648 }
8649
8650 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8651 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8652 if (!ppRec)
8653 return skipped;
8654
8655 ASTContext &Ctx = astUnit->getASTContext();
8656
8657 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8658
8659 skipped->count = SkippedRanges.size();
8660 skipped->ranges = new CXSourceRange[skipped->count];
8661 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8662 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8663
8664 return skipped;
8665}
8666
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008667void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8668 if (ranges) {
8669 delete[] ranges->ranges;
8670 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008671 }
8672}
8673
Guy Benyei11169dd2012-12-18 14:30:41 +00008674void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8675 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8676 for (unsigned I = 0; I != Usage.numEntries; ++I)
8677 fprintf(stderr, " %s: %lu\n",
8678 clang_getTUResourceUsageName(Usage.entries[I].kind),
8679 Usage.entries[I].amount);
8680
8681 clang_disposeCXTUResourceUsage(Usage);
8682}
8683
8684//===----------------------------------------------------------------------===//
8685// Misc. utility functions.
8686//===----------------------------------------------------------------------===//
8687
Richard Smith0a7b2972018-07-03 21:34:13 +00008688/// Default to using our desired 8 MB stack size on "safety" threads.
8689static unsigned SafetyStackThreadSize = DesiredStackSize;
Guy Benyei11169dd2012-12-18 14:30:41 +00008690
8691namespace clang {
8692
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008693bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008694 unsigned Size) {
8695 if (!Size)
8696 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008697 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008698 return CRC.RunSafelyOnThread(Fn, Size);
8699 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008700}
8701
8702unsigned GetSafetyThreadStackSize() {
8703 return SafetyStackThreadSize;
8704}
8705
8706void SetSafetyThreadStackSize(unsigned Value) {
8707 SafetyStackThreadSize = Value;
8708}
8709
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008710}
Guy Benyei11169dd2012-12-18 14:30:41 +00008711
8712void clang::setThreadBackgroundPriority() {
8713 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8714 return;
8715
Alp Toker1a86ad22014-07-06 06:24:00 +00008716#ifdef USE_DARWIN_THREADS
Guy Benyei11169dd2012-12-18 14:30:41 +00008717 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
8718#endif
8719}
8720
8721void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8722 if (!Unit)
8723 return;
8724
8725 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8726 DEnd = Unit->stored_diag_end();
8727 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008728 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008729 CXString Msg = clang_formatDiagnostic(&Diag,
8730 clang_defaultDiagnosticDisplayOptions());
8731 fprintf(stderr, "%s\n", clang_getCString(Msg));
8732 clang_disposeString(Msg);
8733 }
Nico Weber1865df42018-04-27 19:11:14 +00008734#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008735 // On Windows, force a flush, since there may be multiple copies of
8736 // stderr and stdout in the file system, all with different buffers
8737 // but writing to the same device.
8738 fflush(stderr);
8739#endif
8740}
8741
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008742MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8743 SourceLocation MacroDefLoc,
8744 CXTranslationUnit TU){
8745 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008746 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008747 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008748 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008749
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008750 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008751 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008752 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008753 if (MD) {
8754 for (MacroDirective::DefInfo
8755 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8756 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8757 return Def.getMacroInfo();
8758 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008759 }
8760
Craig Topper69186e72014-06-08 08:38:04 +00008761 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008762}
8763
Richard Smith66a81862015-05-04 02:25:31 +00008764const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008765 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008766 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008767 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008768 const IdentifierInfo *II = MacroDef->getName();
8769 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008770 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008771
8772 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8773}
8774
Richard Smith66a81862015-05-04 02:25:31 +00008775MacroDefinitionRecord *
8776cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8777 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008778 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008779 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008780 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008781 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008782
8783 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008784 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008785 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8786 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008787 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008788
8789 // Check that the token is inside the definition and not its argument list.
8790 SourceManager &SM = Unit->getSourceManager();
8791 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008792 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008793 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008794 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008795
8796 Preprocessor &PP = Unit->getPreprocessor();
8797 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8798 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008799 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008800
Alp Toker2d57cea2014-05-17 04:53:25 +00008801 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008802 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008803 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008804
8805 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008806 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008807 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008808
Richard Smith20e883e2015-04-29 23:20:19 +00008809 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008810 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008811 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008812
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008813 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008814}
8815
Richard Smith66a81862015-05-04 02:25:31 +00008816MacroDefinitionRecord *
8817cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8818 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008819 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008820 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008821
8822 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008823 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008824 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008825 Preprocessor &PP = Unit->getPreprocessor();
8826 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008827 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008828 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8829 Token Tok;
8830 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008831 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008832
8833 return checkForMacroInMacroDefinition(MI, Tok, TU);
8834}
8835
Guy Benyei11169dd2012-12-18 14:30:41 +00008836CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008837 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008838}
8839
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008840Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8841 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008842 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008843 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008844 if (Unit->isMainFileAST())
8845 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008846 return *this;
8847 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008848 } else {
8849 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008850 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008851 return *this;
8852}
8853
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008854Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8855 *this << FE->getName();
8856 return *this;
8857}
8858
8859Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8860 CXString cursorName = clang_getCursorDisplayName(cursor);
8861 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8862 clang_disposeString(cursorName);
8863 return *this;
8864}
8865
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008866Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8867 CXFile File;
8868 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008869 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008870 CXString FileName = clang_getFileName(File);
8871 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8872 clang_disposeString(FileName);
8873 return *this;
8874}
8875
8876Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8877 CXSourceLocation BLoc = clang_getRangeStart(range);
8878 CXSourceLocation ELoc = clang_getRangeEnd(range);
8879
8880 CXFile BFile;
8881 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008882 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008883
8884 CXFile EFile;
8885 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008886 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008887
8888 CXString BFileName = clang_getFileName(BFile);
8889 if (BFile == EFile) {
8890 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8891 BLine, BColumn, ELine, EColumn);
8892 } else {
8893 CXString EFileName = clang_getFileName(EFile);
8894 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8895 BLine, BColumn)
8896 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8897 ELine, EColumn);
8898 clang_disposeString(EFileName);
8899 }
8900 clang_disposeString(BFileName);
8901 return *this;
8902}
8903
8904Logger &cxindex::Logger::operator<<(CXString Str) {
8905 *this << clang_getCString(Str);
8906 return *this;
8907}
8908
8909Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8910 LogOS << Fmt;
8911 return *this;
8912}
8913
Chandler Carruth37ad2582014-06-27 15:14:39 +00008914static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8915
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008916cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008917 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008918
8919 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8920
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008921 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008922 OS << "[libclang:" << Name << ':';
8923
Alp Toker1a86ad22014-07-06 06:24:00 +00008924#ifdef USE_DARWIN_THREADS
8925 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008926 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8927 OS << tid << ':';
8928#endif
8929
8930 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8931 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008932 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008933
8934 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008935 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008936 OS << "--------------------------------------------------\n";
8937 }
8938}
Ivan Donchevskiic5929132018-12-10 15:58:50 +00008939
8940#ifdef CLANG_TOOL_EXTRA_BUILD
8941// This anchor is used to force the linker to link the clang-tidy plugin.
8942extern volatile int ClangTidyPluginAnchorSource;
8943static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8944 ClangTidyPluginAnchorSource;
8945
8946// This anchor is used to force the linker to link the clang-include-fixer
8947// plugin.
8948extern volatile int ClangIncludeFixerPluginAnchorSource;
8949static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8950 ClangIncludeFixerPluginAnchorSource;
8951#endif