blob: fa4ac48fb7153ad5e861c30a7f6bba4f15ff66f5 [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);
2133#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002134 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002135 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002136};
2137
Alexey Bataev3392d762016-02-16 11:18:12 +00002138void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2139 const OMPClauseWithPreInit *C) {
2140 Visitor->AddStmt(C->getPreInitStmt());
2141}
2142
Alexey Bataev005248a2016-02-25 05:25:57 +00002143void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2144 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002145 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002146 Visitor->AddStmt(C->getPostUpdateExpr());
2147}
2148
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002149void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002150 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002151 Visitor->AddStmt(C->getCondition());
2152}
2153
Alexey Bataev3778b602014-07-17 07:32:53 +00002154void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2155 Visitor->AddStmt(C->getCondition());
2156}
2157
Alexey Bataev568a8332014-03-06 06:15:19 +00002158void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002159 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002160 Visitor->AddStmt(C->getNumThreads());
2161}
2162
Alexey Bataev62c87d22014-03-21 04:51:18 +00002163void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2164 Visitor->AddStmt(C->getSafelen());
2165}
2166
Alexey Bataev66b15b52015-08-21 11:14:16 +00002167void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2168 Visitor->AddStmt(C->getSimdlen());
2169}
2170
Alexander Musman8bd31e62014-05-27 15:12:19 +00002171void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2172 Visitor->AddStmt(C->getNumForLoops());
2173}
2174
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002175void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002176
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002177void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2178
Alexey Bataev56dafe82014-06-20 07:16:17 +00002179void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002180 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002181 Visitor->AddStmt(C->getChunkSize());
2182}
2183
Alexey Bataev10e775f2015-07-30 11:36:16 +00002184void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2185 Visitor->AddStmt(C->getNumForLoops());
2186}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002187
Alexey Bataev236070f2014-06-20 11:19:47 +00002188void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2189
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002190void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2191
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002192void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2193
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002194void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2195
Alexey Bataevdea47612014-07-23 07:46:59 +00002196void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2197
Alexey Bataev67a4f222014-07-23 10:25:33 +00002198void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2199
Alexey Bataev459dec02014-07-24 06:46:57 +00002200void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2201
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002202void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2203
Alexey Bataev346265e2015-09-25 10:37:12 +00002204void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2205
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002206void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2207
Alexey Bataevb825de12015-12-07 10:51:44 +00002208void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2209
Kelvin Li1408f912018-09-26 04:28:39 +00002210void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2211 const OMPUnifiedAddressClause *) {}
2212
Patrick Lyster4a370b92018-10-01 13:47:43 +00002213void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2214 const OMPUnifiedSharedMemoryClause *) {}
2215
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00002216void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2217 const OMPReverseOffloadClause *) {}
2218
Patrick Lyster3fe9e392018-10-11 14:41:10 +00002219void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2220 const OMPDynamicAllocatorsClause *) {}
2221
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00002222void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2223 const OMPAtomicDefaultMemOrderClause *) {}
2224
Michael Wonge710d542015-08-07 16:16:36 +00002225void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2226 Visitor->AddStmt(C->getDevice());
2227}
2228
Kelvin Li099bb8c2015-11-24 20:50:12 +00002229void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002230 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002231 Visitor->AddStmt(C->getNumTeams());
2232}
2233
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002234void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002235 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002236 Visitor->AddStmt(C->getThreadLimit());
2237}
2238
Alexey Bataeva0569352015-12-01 10:17:31 +00002239void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2240 Visitor->AddStmt(C->getPriority());
2241}
2242
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002243void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2244 Visitor->AddStmt(C->getGrainsize());
2245}
2246
Alexey Bataev382967a2015-12-08 12:06:20 +00002247void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2248 Visitor->AddStmt(C->getNumTasks());
2249}
2250
Alexey Bataev28c75412015-12-15 08:19:24 +00002251void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2252 Visitor->AddStmt(C->getHint());
2253}
2254
Alexey Bataev756c1962013-09-24 03:17:45 +00002255template<typename T>
2256void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002257 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002258 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002259 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002260}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002261
2262void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002263 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002264 for (const auto *E : C->private_copies()) {
2265 Visitor->AddStmt(E);
2266 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002267}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002268void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2269 const OMPFirstprivateClause *C) {
2270 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002271 VisitOMPClauseWithPreInit(C);
2272 for (const auto *E : C->private_copies()) {
2273 Visitor->AddStmt(E);
2274 }
2275 for (const auto *E : C->inits()) {
2276 Visitor->AddStmt(E);
2277 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002278}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002279void OMPClauseEnqueue::VisitOMPLastprivateClause(
2280 const OMPLastprivateClause *C) {
2281 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002282 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002283 for (auto *E : C->private_copies()) {
2284 Visitor->AddStmt(E);
2285 }
2286 for (auto *E : C->source_exprs()) {
2287 Visitor->AddStmt(E);
2288 }
2289 for (auto *E : C->destination_exprs()) {
2290 Visitor->AddStmt(E);
2291 }
2292 for (auto *E : C->assignment_ops()) {
2293 Visitor->AddStmt(E);
2294 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002295}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002296void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002297 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002298}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002299void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2300 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002301 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002302 for (auto *E : C->privates()) {
2303 Visitor->AddStmt(E);
2304 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002305 for (auto *E : C->lhs_exprs()) {
2306 Visitor->AddStmt(E);
2307 }
2308 for (auto *E : C->rhs_exprs()) {
2309 Visitor->AddStmt(E);
2310 }
2311 for (auto *E : C->reduction_ops()) {
2312 Visitor->AddStmt(E);
2313 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002314}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002315void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2316 const OMPTaskReductionClause *C) {
2317 VisitOMPClauseList(C);
2318 VisitOMPClauseWithPostUpdate(C);
2319 for (auto *E : C->privates()) {
2320 Visitor->AddStmt(E);
2321 }
2322 for (auto *E : C->lhs_exprs()) {
2323 Visitor->AddStmt(E);
2324 }
2325 for (auto *E : C->rhs_exprs()) {
2326 Visitor->AddStmt(E);
2327 }
2328 for (auto *E : C->reduction_ops()) {
2329 Visitor->AddStmt(E);
2330 }
2331}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002332void OMPClauseEnqueue::VisitOMPInReductionClause(
2333 const OMPInReductionClause *C) {
2334 VisitOMPClauseList(C);
2335 VisitOMPClauseWithPostUpdate(C);
2336 for (auto *E : C->privates()) {
2337 Visitor->AddStmt(E);
2338 }
2339 for (auto *E : C->lhs_exprs()) {
2340 Visitor->AddStmt(E);
2341 }
2342 for (auto *E : C->rhs_exprs()) {
2343 Visitor->AddStmt(E);
2344 }
2345 for (auto *E : C->reduction_ops()) {
2346 Visitor->AddStmt(E);
2347 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002348 for (auto *E : C->taskgroup_descriptors())
2349 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002350}
Alexander Musman8dba6642014-04-22 13:09:42 +00002351void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2352 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002353 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002354 for (const auto *E : C->privates()) {
2355 Visitor->AddStmt(E);
2356 }
Alexander Musman3276a272015-03-21 10:12:56 +00002357 for (const auto *E : C->inits()) {
2358 Visitor->AddStmt(E);
2359 }
2360 for (const auto *E : C->updates()) {
2361 Visitor->AddStmt(E);
2362 }
2363 for (const auto *E : C->finals()) {
2364 Visitor->AddStmt(E);
2365 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002366 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002367 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002368}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002369void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2370 VisitOMPClauseList(C);
2371 Visitor->AddStmt(C->getAlignment());
2372}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002373void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2374 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002375 for (auto *E : C->source_exprs()) {
2376 Visitor->AddStmt(E);
2377 }
2378 for (auto *E : C->destination_exprs()) {
2379 Visitor->AddStmt(E);
2380 }
2381 for (auto *E : C->assignment_ops()) {
2382 Visitor->AddStmt(E);
2383 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002384}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002385void
2386OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2387 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002388 for (auto *E : C->source_exprs()) {
2389 Visitor->AddStmt(E);
2390 }
2391 for (auto *E : C->destination_exprs()) {
2392 Visitor->AddStmt(E);
2393 }
2394 for (auto *E : C->assignment_ops()) {
2395 Visitor->AddStmt(E);
2396 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002397}
Alexey Bataev6125da92014-07-21 11:26:11 +00002398void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2399 VisitOMPClauseList(C);
2400}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002401void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2402 VisitOMPClauseList(C);
2403}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002404void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2405 VisitOMPClauseList(C);
2406}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002407void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2408 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002409 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002410 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002411}
Alexey Bataev3392d762016-02-16 11:18:12 +00002412void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2413 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002414void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2415 VisitOMPClauseList(C);
2416}
Samuel Antaoec172c62016-05-26 17:49:04 +00002417void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2418 VisitOMPClauseList(C);
2419}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002420void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2421 VisitOMPClauseList(C);
2422}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002423void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2424 VisitOMPClauseList(C);
2425}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002426}
Alexey Bataev756c1962013-09-24 03:17:45 +00002427
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002428void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2429 unsigned size = WL.size();
2430 OMPClauseEnqueue Visitor(this);
2431 Visitor.Visit(S);
2432 if (size == WL.size())
2433 return;
2434 // Now reverse the entries we just added. This will match the DFS
2435 // ordering performed by the worklist.
2436 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2437 std::reverse(I, E);
2438}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002439void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002440 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2441}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002442void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002443 AddDecl(B->getBlockDecl());
2444}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002445void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002446 EnqueueChildren(E);
2447 AddTypeLoc(E->getTypeSourceInfo());
2448}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002449void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002450 for (auto &I : llvm::reverse(S->body()))
2451 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002452}
2453void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002454VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002455 AddStmt(S->getSubStmt());
2456 AddDeclarationNameInfo(S);
2457 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2458 AddNestedNameSpecifierLoc(QualifierLoc);
2459}
2460
2461void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002462VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002463 if (E->hasExplicitTemplateArgs())
2464 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002465 AddDeclarationNameInfo(E);
2466 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2467 AddNestedNameSpecifierLoc(QualifierLoc);
2468 if (!E->isImplicitAccess())
2469 AddStmt(E->getBase());
2470}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002471void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 // Enqueue the initializer , if any.
2473 AddStmt(E->getInitializer());
2474 // Enqueue the array size, if any.
2475 AddStmt(E->getArraySize());
2476 // Enqueue the allocated type.
2477 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2478 // Enqueue the placement arguments.
2479 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2480 AddStmt(E->getPlacementArg(I-1));
2481}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002482void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002483 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2484 AddStmt(CE->getArg(I-1));
2485 AddStmt(CE->getCallee());
2486 AddStmt(CE->getArg(0));
2487}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002488void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2489 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002490 // Visit the name of the type being destroyed.
2491 AddTypeLoc(E->getDestroyedTypeInfo());
2492 // Visit the scope type that looks disturbingly like the nested-name-specifier
2493 // but isn't.
2494 AddTypeLoc(E->getScopeTypeInfo());
2495 // Visit the nested-name-specifier.
2496 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2497 AddNestedNameSpecifierLoc(QualifierLoc);
2498 // Visit base expression.
2499 AddStmt(E->getBase());
2500}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002501void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2502 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002503 AddTypeLoc(E->getTypeSourceInfo());
2504}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002505void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2506 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002507 EnqueueChildren(E);
2508 AddTypeLoc(E->getTypeSourceInfo());
2509}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002510void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002511 EnqueueChildren(E);
2512 if (E->isTypeOperand())
2513 AddTypeLoc(E->getTypeOperandSourceInfo());
2514}
2515
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002516void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2517 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002518 EnqueueChildren(E);
2519 AddTypeLoc(E->getTypeSourceInfo());
2520}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002521void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002522 EnqueueChildren(E);
2523 if (E->isTypeOperand())
2524 AddTypeLoc(E->getTypeOperandSourceInfo());
2525}
2526
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002527void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002528 EnqueueChildren(S);
2529 AddDecl(S->getExceptionDecl());
2530}
2531
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002532void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002533 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002534 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002535 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002536}
2537
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002538void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002539 if (DR->hasExplicitTemplateArgs())
2540 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002541 WL.push_back(DeclRefExprParts(DR, Parent));
2542}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002543void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2544 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002545 if (E->hasExplicitTemplateArgs())
2546 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002547 AddDeclarationNameInfo(E);
2548 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2549}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002550void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002551 unsigned size = WL.size();
2552 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002553 for (const auto *D : S->decls()) {
2554 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002555 isFirst = false;
2556 }
2557 if (size == WL.size())
2558 return;
2559 // Now reverse the entries we just added. This will match the DFS
2560 // ordering performed by the worklist.
2561 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2562 std::reverse(I, E);
2563}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002564void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002565 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002566 for (const DesignatedInitExpr::Designator &D :
2567 llvm::reverse(E->designators())) {
2568 if (D.isFieldDesignator()) {
2569 if (FieldDecl *Field = D.getField())
2570 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002571 continue;
2572 }
David Majnemerf7e36092016-06-23 00:15:04 +00002573 if (D.isArrayDesignator()) {
2574 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002575 continue;
2576 }
David Majnemerf7e36092016-06-23 00:15:04 +00002577 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2578 AddStmt(E->getArrayRangeEnd(D));
2579 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002580 }
2581}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002582void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002583 EnqueueChildren(E);
2584 AddTypeLoc(E->getTypeInfoAsWritten());
2585}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002586void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002587 AddStmt(FS->getBody());
2588 AddStmt(FS->getInc());
2589 AddStmt(FS->getCond());
2590 AddDecl(FS->getConditionVariable());
2591 AddStmt(FS->getInit());
2592}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002593void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2595}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002596void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002597 AddStmt(If->getElse());
2598 AddStmt(If->getThen());
2599 AddStmt(If->getCond());
2600 AddDecl(If->getConditionVariable());
2601}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002602void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002603 // We care about the syntactic form of the initializer list, only.
2604 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2605 IE = Syntactic;
2606 EnqueueChildren(IE);
2607}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002608void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002609 WL.push_back(MemberExprParts(M, Parent));
2610
2611 // If the base of the member access expression is an implicit 'this', don't
2612 // visit it.
2613 // FIXME: If we ever want to show these implicit accesses, this will be
2614 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002615 if (M->isImplicitAccess())
2616 return;
2617
2618 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002619 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002620 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2621 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2622 if (FD->isAnonymousStructOrUnion()) {
2623 AddStmt(SubME->getBase());
2624 return;
2625 }
2626 }
2627 }
2628
2629 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002630}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002631void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002632 AddTypeLoc(E->getEncodedTypeSourceInfo());
2633}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002634void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 EnqueueChildren(M);
2636 AddTypeLoc(M->getClassReceiverTypeInfo());
2637}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002638void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002639 // Visit the components of the offsetof expression.
2640 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002641 const OffsetOfNode &Node = E->getComponent(I-1);
2642 switch (Node.getKind()) {
2643 case OffsetOfNode::Array:
2644 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2645 break;
2646 case OffsetOfNode::Field:
2647 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2648 break;
2649 case OffsetOfNode::Identifier:
2650 case OffsetOfNode::Base:
2651 continue;
2652 }
2653 }
2654 // Visit the type into which we're computing the offset.
2655 AddTypeLoc(E->getTypeSourceInfo());
2656}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002657void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002658 if (E->hasExplicitTemplateArgs())
2659 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002660 WL.push_back(OverloadExprParts(E, Parent));
2661}
2662void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002663 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002664 EnqueueChildren(E);
2665 if (E->isArgumentType())
2666 AddTypeLoc(E->getArgumentTypeInfo());
2667}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002668void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002669 EnqueueChildren(S);
2670}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002671void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002672 AddStmt(S->getBody());
2673 AddStmt(S->getCond());
2674 AddDecl(S->getConditionVariable());
2675}
2676
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002677void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002678 AddStmt(W->getBody());
2679 AddStmt(W->getCond());
2680 AddDecl(W->getConditionVariable());
2681}
2682
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002683void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002684 for (unsigned I = E->getNumArgs(); I > 0; --I)
2685 AddTypeLoc(E->getArg(I-1));
2686}
2687
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002688void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002689 AddTypeLoc(E->getQueriedTypeSourceInfo());
2690}
2691
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002692void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002693 EnqueueChildren(E);
2694}
2695
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002696void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002697 VisitOverloadExpr(U);
2698 if (!U->isImplicitAccess())
2699 AddStmt(U->getBase());
2700}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002701void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002702 AddStmt(E->getSubExpr());
2703 AddTypeLoc(E->getWrittenTypeInfo());
2704}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002705void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002706 WL.push_back(SizeOfPackExprParts(E, Parent));
2707}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002708void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002709 // If the opaque value has a source expression, just transparently
2710 // visit that. This is useful for (e.g.) pseudo-object expressions.
2711 if (Expr *SourceExpr = E->getSourceExpr())
2712 return Visit(SourceExpr);
2713}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002714void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002715 AddStmt(E->getBody());
2716 WL.push_back(LambdaExprParts(E, Parent));
2717}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002718void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002719 // Treat the expression like its syntactic form.
2720 Visit(E->getSyntacticForm());
2721}
2722
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002723void EnqueueVisitor::VisitOMPExecutableDirective(
2724 const OMPExecutableDirective *D) {
2725 EnqueueChildren(D);
2726 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2727 E = D->clauses().end();
2728 I != E; ++I)
2729 EnqueueChildren(*I);
2730}
2731
Alexander Musman3aaab662014-08-19 11:27:13 +00002732void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2733 VisitOMPExecutableDirective(D);
2734}
2735
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002736void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2737 VisitOMPExecutableDirective(D);
2738}
2739
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002740void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002741 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002742}
2743
Alexey Bataevf29276e2014-06-18 04:14:57 +00002744void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002745 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002746}
2747
Alexander Musmanf82886e2014-09-18 05:12:34 +00002748void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2749 VisitOMPLoopDirective(D);
2750}
2751
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002752void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2753 VisitOMPExecutableDirective(D);
2754}
2755
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002756void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2757 VisitOMPExecutableDirective(D);
2758}
2759
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002760void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2761 VisitOMPExecutableDirective(D);
2762}
2763
Alexander Musman80c22892014-07-17 08:54:58 +00002764void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2765 VisitOMPExecutableDirective(D);
2766}
2767
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002768void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2769 VisitOMPExecutableDirective(D);
2770 AddDeclarationNameInfo(D);
2771}
2772
Alexey Bataev4acb8592014-07-07 13:01:15 +00002773void
2774EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002775 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002776}
2777
Alexander Musmane4e893b2014-09-23 09:33:00 +00002778void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2779 const OMPParallelForSimdDirective *D) {
2780 VisitOMPLoopDirective(D);
2781}
2782
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002783void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2784 const OMPParallelSectionsDirective *D) {
2785 VisitOMPExecutableDirective(D);
2786}
2787
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002788void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2789 VisitOMPExecutableDirective(D);
2790}
2791
Alexey Bataev68446b72014-07-18 07:47:19 +00002792void
2793EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2794 VisitOMPExecutableDirective(D);
2795}
2796
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002797void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2798 VisitOMPExecutableDirective(D);
2799}
2800
Alexey Bataev2df347a2014-07-18 10:17:07 +00002801void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2802 VisitOMPExecutableDirective(D);
2803}
2804
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002805void EnqueueVisitor::VisitOMPTaskgroupDirective(
2806 const OMPTaskgroupDirective *D) {
2807 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002808 if (const Expr *E = D->getReductionRef())
2809 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002810}
2811
Alexey Bataev6125da92014-07-21 11:26:11 +00002812void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2813 VisitOMPExecutableDirective(D);
2814}
2815
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002816void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2817 VisitOMPExecutableDirective(D);
2818}
2819
Alexey Bataev0162e452014-07-22 10:10:35 +00002820void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2821 VisitOMPExecutableDirective(D);
2822}
2823
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002824void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2825 VisitOMPExecutableDirective(D);
2826}
2827
Michael Wong65f367f2015-07-21 13:44:28 +00002828void EnqueueVisitor::VisitOMPTargetDataDirective(const
2829 OMPTargetDataDirective *D) {
2830 VisitOMPExecutableDirective(D);
2831}
2832
Samuel Antaodf67fc42016-01-19 19:15:56 +00002833void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2834 const OMPTargetEnterDataDirective *D) {
2835 VisitOMPExecutableDirective(D);
2836}
2837
Samuel Antao72590762016-01-19 20:04:50 +00002838void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2839 const OMPTargetExitDataDirective *D) {
2840 VisitOMPExecutableDirective(D);
2841}
2842
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002843void EnqueueVisitor::VisitOMPTargetParallelDirective(
2844 const OMPTargetParallelDirective *D) {
2845 VisitOMPExecutableDirective(D);
2846}
2847
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002848void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2849 const OMPTargetParallelForDirective *D) {
2850 VisitOMPLoopDirective(D);
2851}
2852
Alexey Bataev13314bf2014-10-09 04:18:56 +00002853void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2854 VisitOMPExecutableDirective(D);
2855}
2856
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002857void EnqueueVisitor::VisitOMPCancellationPointDirective(
2858 const OMPCancellationPointDirective *D) {
2859 VisitOMPExecutableDirective(D);
2860}
2861
Alexey Bataev80909872015-07-02 11:25:17 +00002862void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2863 VisitOMPExecutableDirective(D);
2864}
2865
Alexey Bataev49f6e782015-12-01 04:18:41 +00002866void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2867 VisitOMPLoopDirective(D);
2868}
2869
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002870void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2871 const OMPTaskLoopSimdDirective *D) {
2872 VisitOMPLoopDirective(D);
2873}
2874
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002875void EnqueueVisitor::VisitOMPDistributeDirective(
2876 const OMPDistributeDirective *D) {
2877 VisitOMPLoopDirective(D);
2878}
2879
Carlo Bertolli9925f152016-06-27 14:55:37 +00002880void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2881 const OMPDistributeParallelForDirective *D) {
2882 VisitOMPLoopDirective(D);
2883}
2884
Kelvin Li4a39add2016-07-05 05:00:15 +00002885void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2886 const OMPDistributeParallelForSimdDirective *D) {
2887 VisitOMPLoopDirective(D);
2888}
2889
Kelvin Li787f3fc2016-07-06 04:45:38 +00002890void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2891 const OMPDistributeSimdDirective *D) {
2892 VisitOMPLoopDirective(D);
2893}
2894
Kelvin Lia579b912016-07-14 02:54:56 +00002895void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2896 const OMPTargetParallelForSimdDirective *D) {
2897 VisitOMPLoopDirective(D);
2898}
2899
Kelvin Li986330c2016-07-20 22:57:10 +00002900void EnqueueVisitor::VisitOMPTargetSimdDirective(
2901 const OMPTargetSimdDirective *D) {
2902 VisitOMPLoopDirective(D);
2903}
2904
Kelvin Li02532872016-08-05 14:37:37 +00002905void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2906 const OMPTeamsDistributeDirective *D) {
2907 VisitOMPLoopDirective(D);
2908}
2909
Kelvin Li4e325f72016-10-25 12:50:55 +00002910void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2911 const OMPTeamsDistributeSimdDirective *D) {
2912 VisitOMPLoopDirective(D);
2913}
2914
Kelvin Li579e41c2016-11-30 23:51:03 +00002915void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2916 const OMPTeamsDistributeParallelForSimdDirective *D) {
2917 VisitOMPLoopDirective(D);
2918}
2919
Kelvin Li7ade93f2016-12-09 03:24:30 +00002920void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2921 const OMPTeamsDistributeParallelForDirective *D) {
2922 VisitOMPLoopDirective(D);
2923}
2924
Kelvin Libf594a52016-12-17 05:48:59 +00002925void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2926 const OMPTargetTeamsDirective *D) {
2927 VisitOMPExecutableDirective(D);
2928}
2929
Kelvin Li83c451e2016-12-25 04:52:54 +00002930void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2931 const OMPTargetTeamsDistributeDirective *D) {
2932 VisitOMPLoopDirective(D);
2933}
2934
Kelvin Li80e8f562016-12-29 22:16:30 +00002935void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2936 const OMPTargetTeamsDistributeParallelForDirective *D) {
2937 VisitOMPLoopDirective(D);
2938}
2939
Kelvin Li1851df52017-01-03 05:23:48 +00002940void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2941 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2942 VisitOMPLoopDirective(D);
2943}
2944
Kelvin Lida681182017-01-10 18:08:18 +00002945void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2946 const OMPTargetTeamsDistributeSimdDirective *D) {
2947 VisitOMPLoopDirective(D);
2948}
2949
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002950void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002951 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2952}
2953
2954bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2955 if (RegionOfInterest.isValid()) {
2956 SourceRange Range = getRawCursorExtent(C);
2957 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2958 return false;
2959 }
2960 return true;
2961}
2962
2963bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2964 while (!WL.empty()) {
2965 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002966 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002967
2968 // Set the Parent field, then back to its old value once we're done.
2969 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2970
2971 switch (LI.getKind()) {
2972 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002973 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002974 if (!D)
2975 continue;
2976
2977 // For now, perform default visitation for Decls.
2978 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2979 cast<DeclVisit>(&LI)->isFirst())))
2980 return true;
2981
2982 continue;
2983 }
2984 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002985 for (const TemplateArgumentLoc &Arg :
2986 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2987 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002988 return true;
2989 }
2990 continue;
2991 }
2992 case VisitorJob::TypeLocVisitKind: {
2993 // Perform default visitation for TypeLocs.
2994 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2995 return true;
2996 continue;
2997 }
2998 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002999 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003000 if (LabelStmt *stmt = LS->getStmt()) {
3001 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3002 TU))) {
3003 return true;
3004 }
3005 }
3006 continue;
3007 }
3008
3009 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3010 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3011 if (VisitNestedNameSpecifierLoc(V->get()))
3012 return true;
3013 continue;
3014 }
3015
3016 case VisitorJob::DeclarationNameInfoVisitKind: {
3017 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3018 ->get()))
3019 return true;
3020 continue;
3021 }
3022 case VisitorJob::MemberRefVisitKind: {
3023 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3024 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3025 return true;
3026 continue;
3027 }
3028 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003029 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003030 if (!S)
3031 continue;
3032
3033 // Update the current cursor.
3034 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3035 if (!IsInRegionOfInterest(Cursor))
3036 continue;
3037 switch (Visitor(Cursor, Parent, ClientData)) {
3038 case CXChildVisit_Break: return true;
3039 case CXChildVisit_Continue: break;
3040 case CXChildVisit_Recurse:
3041 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003042 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003043 EnqueueWorkList(WL, S);
3044 break;
3045 }
3046 continue;
3047 }
3048 case VisitorJob::MemberExprPartsKind: {
3049 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003050 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003051
3052 // Visit the nested-name-specifier
3053 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3054 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3055 return true;
3056
3057 // Visit the declaration name.
3058 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3059 return true;
3060
3061 // Visit the explicitly-specified template arguments, if any.
3062 if (M->hasExplicitTemplateArgs()) {
3063 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3064 *ArgEnd = Arg + M->getNumTemplateArgs();
3065 Arg != ArgEnd; ++Arg) {
3066 if (VisitTemplateArgumentLoc(*Arg))
3067 return true;
3068 }
3069 }
3070 continue;
3071 }
3072 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003073 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003074 // Visit nested-name-specifier, if present.
3075 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3076 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3077 return true;
3078 // Visit declaration name.
3079 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3080 return true;
3081 continue;
3082 }
3083 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003084 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003085 // Visit the nested-name-specifier.
3086 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3087 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3088 return true;
3089 // Visit the declaration name.
3090 if (VisitDeclarationNameInfo(O->getNameInfo()))
3091 return true;
3092 // Visit the overloaded declaration reference.
3093 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3094 return true;
3095 continue;
3096 }
3097 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003098 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003099 NamedDecl *Pack = E->getPack();
3100 if (isa<TemplateTypeParmDecl>(Pack)) {
3101 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3102 E->getPackLoc(), TU)))
3103 return true;
3104
3105 continue;
3106 }
3107
3108 if (isa<TemplateTemplateParmDecl>(Pack)) {
3109 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3110 E->getPackLoc(), TU)))
3111 return true;
3112
3113 continue;
3114 }
3115
3116 // Non-type template parameter packs and function parameter packs are
3117 // treated like DeclRefExpr cursors.
3118 continue;
3119 }
3120
3121 case VisitorJob::LambdaExprPartsKind: {
3122 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003123 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003124 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3125 CEnd = E->explicit_capture_end();
3126 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003127 // FIXME: Lambda init-captures.
3128 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003129 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003130
Guy Benyei11169dd2012-12-18 14:30:41 +00003131 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3132 C->getLocation(),
3133 TU)))
3134 return true;
3135 }
3136
Haojian Wuef87c262018-12-18 15:29:12 +00003137 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00003138 // Visit parameters and return type, if present.
Haojian Wuef87c262018-12-18 15:29:12 +00003139 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3140 if (E->hasExplicitParameters()) {
3141 // Visit parameters.
3142 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3143 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003144 return true;
Haojian Wuef87c262018-12-18 15:29:12 +00003145 }
3146 if (E->hasExplicitResultType()) {
3147 // Visit result type.
3148 if (Visit(Proto.getReturnLoc()))
3149 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003150 }
3151 }
3152 break;
3153 }
3154
3155 case VisitorJob::PostChildrenVisitKind:
3156 if (PostChildrenVisitor(Parent, ClientData))
3157 return true;
3158 break;
3159 }
3160 }
3161 return false;
3162}
3163
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003164bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003165 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003166 if (!WorkListFreeList.empty()) {
3167 WL = WorkListFreeList.back();
3168 WL->clear();
3169 WorkListFreeList.pop_back();
3170 }
3171 else {
3172 WL = new VisitorWorkList();
3173 WorkListCache.push_back(WL);
3174 }
3175 EnqueueWorkList(*WL, S);
3176 bool result = RunVisitorWorkList(*WL);
3177 WorkListFreeList.push_back(WL);
3178 return result;
3179}
3180
3181namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003182typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003183RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3184 const DeclarationNameInfo &NI, SourceRange QLoc,
3185 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003186 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3187 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3188 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3189
3190 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3191
3192 RefNamePieces Pieces;
3193
3194 if (WantQualifier && QLoc.isValid())
3195 Pieces.push_back(QLoc);
3196
3197 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3198 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003199
3200 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3201 Pieces.push_back(*TemplateArgsLoc);
3202
Guy Benyei11169dd2012-12-18 14:30:41 +00003203 if (Kind == DeclarationName::CXXOperatorName) {
3204 Pieces.push_back(SourceLocation::getFromRawEncoding(
3205 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3206 Pieces.push_back(SourceLocation::getFromRawEncoding(
3207 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3208 }
3209
3210 if (WantSinglePiece) {
3211 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3212 Pieces.clear();
3213 Pieces.push_back(R);
3214 }
3215
3216 return Pieces;
3217}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003218}
Guy Benyei11169dd2012-12-18 14:30:41 +00003219
3220//===----------------------------------------------------------------------===//
3221// Misc. API hooks.
3222//===----------------------------------------------------------------------===//
3223
Chad Rosier05c71aa2013-03-27 18:28:23 +00003224static void fatal_error_handler(void *user_data, const std::string& reason,
3225 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003226 // Write the result out to stderr avoiding errs() because raw_ostreams can
3227 // call report_fatal_error.
3228 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3229 ::abort();
3230}
3231
Chandler Carruth66660742014-06-27 16:37:27 +00003232namespace {
3233struct RegisterFatalErrorHandler {
3234 RegisterFatalErrorHandler() {
3235 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3236 }
3237};
3238}
3239
3240static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3241
Guy Benyei11169dd2012-12-18 14:30:41 +00003242CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3243 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003244 // We use crash recovery to make some of our APIs more reliable, implicitly
3245 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003246 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3247 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003248
Chandler Carruth66660742014-06-27 16:37:27 +00003249 // Look through the managed static to trigger construction of the managed
3250 // static which registers our fatal error handler. This ensures it is only
3251 // registered once.
3252 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003253
Adrian Prantlbc068582015-07-08 01:00:30 +00003254 // Initialize targets for clang module support.
3255 llvm::InitializeAllTargets();
3256 llvm::InitializeAllTargetMCs();
3257 llvm::InitializeAllAsmPrinters();
3258 llvm::InitializeAllAsmParsers();
3259
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003260 CIndexer *CIdxr = new CIndexer();
3261
Guy Benyei11169dd2012-12-18 14:30:41 +00003262 if (excludeDeclarationsFromPCH)
3263 CIdxr->setOnlyLocalDecls();
3264 if (displayDiagnostics)
3265 CIdxr->setDisplayDiagnostics();
3266
3267 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3268 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3269 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3270 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3271 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3272 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3273
3274 return CIdxr;
3275}
3276
3277void clang_disposeIndex(CXIndex CIdx) {
3278 if (CIdx)
3279 delete static_cast<CIndexer *>(CIdx);
3280}
3281
3282void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3283 if (CIdx)
3284 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3285}
3286
3287unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3288 if (CIdx)
3289 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3290 return 0;
3291}
3292
Alex Lorenz08615792017-12-04 21:56:36 +00003293void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3294 const char *Path) {
3295 if (CIdx)
3296 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3297}
3298
Guy Benyei11169dd2012-12-18 14:30:41 +00003299void clang_toggleCrashRecovery(unsigned isEnabled) {
3300 if (isEnabled)
3301 llvm::CrashRecoveryContext::Enable();
3302 else
3303 llvm::CrashRecoveryContext::Disable();
3304}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003305
Guy Benyei11169dd2012-12-18 14:30:41 +00003306CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3307 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003308 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003309 enum CXErrorCode Result =
3310 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003311 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003312 assert((TU && Result == CXError_Success) ||
3313 (!TU && Result != CXError_Success));
3314 return TU;
3315}
3316
3317enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3318 const char *ast_filename,
3319 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003320 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003321 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003322
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003323 if (!CIdx || !ast_filename || !out_TU)
3324 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003325
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003326 LOG_FUNC_SECTION {
3327 *Log << ast_filename;
3328 }
3329
Guy Benyei11169dd2012-12-18 14:30:41 +00003330 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3331 FileSystemOptions FileSystemOpts;
3332
Justin Bognerd512c1e2014-10-15 00:33:06 +00003333 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3334 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003335 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003336 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3337 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003338 FileSystemOpts, /*UseDebugInfo=*/false,
3339 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003340 /*CaptureDiagnostics=*/true,
3341 /*AllowPCHWithCompilerErrors=*/true,
3342 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003343 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003344 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003345}
3346
3347unsigned clang_defaultEditingTranslationUnitOptions() {
3348 return CXTranslationUnit_PrecompiledPreamble |
3349 CXTranslationUnit_CacheCompletionResults;
3350}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003351
Guy Benyei11169dd2012-12-18 14:30:41 +00003352CXTranslationUnit
3353clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3354 const char *source_filename,
3355 int num_command_line_args,
3356 const char * const *command_line_args,
3357 unsigned num_unsaved_files,
3358 struct CXUnsavedFile *unsaved_files) {
3359 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3360 return clang_parseTranslationUnit(CIdx, source_filename,
3361 command_line_args, num_command_line_args,
3362 unsaved_files, num_unsaved_files,
3363 Options);
3364}
3365
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003366static CXErrorCode
3367clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3368 const char *const *command_line_args,
3369 int num_command_line_args,
3370 ArrayRef<CXUnsavedFile> unsaved_files,
3371 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003372 // Set up the initial return values.
3373 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003374 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003375
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003376 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003377 if (!CIdx || !out_TU)
3378 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003379
Guy Benyei11169dd2012-12-18 14:30:41 +00003380 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3381
3382 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3383 setThreadBackgroundPriority();
3384
3385 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003386 bool CreatePreambleOnFirstParse =
3387 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003388 // FIXME: Add a flag for modules.
3389 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003390 = (options & (CXTranslationUnit_Incomplete |
3391 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003392 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003393 = options & CXTranslationUnit_CacheCompletionResults;
3394 bool IncludeBriefCommentsInCodeCompletion
3395 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003396 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3397 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003398 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3399 if (options & CXTranslationUnit_SkipFunctionBodies) {
3400 SkipFunctionBodies =
3401 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3402 ? SkipFunctionBodiesScope::Preamble
3403 : SkipFunctionBodiesScope::PreambleAndMainFile;
3404 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003405
3406 // Configure the diagnostics.
3407 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003408 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003409
Manuel Klimek016c0242016-03-01 10:56:19 +00003410 if (options & CXTranslationUnit_KeepGoing)
Ivan Donchevskii878271b2019-03-07 10:13:50 +00003411 Diags->setFatalsAsError(true);
Manuel Klimek016c0242016-03-01 10:56:19 +00003412
Guy Benyei11169dd2012-12-18 14:30:41 +00003413 // Recover resources if we crash before exiting this function.
3414 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3415 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003416 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003417
Ahmed Charlesb8984322014-03-07 20:03:18 +00003418 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3419 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003420
3421 // Recover resources if we crash before exiting this function.
3422 llvm::CrashRecoveryContextCleanupRegistrar<
3423 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3424
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003425 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003426 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003427 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003428 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003429 }
3430
Ahmed Charlesb8984322014-03-07 20:03:18 +00003431 std::unique_ptr<std::vector<const char *>> Args(
3432 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003433
3434 // Recover resources if we crash before exiting this method.
3435 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3436 ArgsCleanup(Args.get());
3437
3438 // Since the Clang C library is primarily used by batch tools dealing with
3439 // (often very broken) source code, where spell-checking can have a
3440 // significant negative impact on performance (particularly when
3441 // precompiled headers are involved), we disable it by default.
3442 // Only do this if we haven't found a spell-checking-related argument.
3443 bool FoundSpellCheckingArgument = false;
3444 for (int I = 0; I != num_command_line_args; ++I) {
3445 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3446 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3447 FoundSpellCheckingArgument = true;
3448 break;
3449 }
3450 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003451 Args->insert(Args->end(), command_line_args,
3452 command_line_args + num_command_line_args);
3453
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003454 if (!FoundSpellCheckingArgument)
3455 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3456
Guy Benyei11169dd2012-12-18 14:30:41 +00003457 // The 'source_filename' argument is optional. If the caller does not
3458 // specify it then it is assumed that the source file is specified
3459 // in the actual argument list.
3460 // Put the source file after command_line_args otherwise if '-x' flag is
3461 // present it will be unused.
3462 if (source_filename)
3463 Args->push_back(source_filename);
3464
3465 // Do we need the detailed preprocessing record?
3466 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3467 Args->push_back("-Xclang");
3468 Args->push_back("-detailed-preprocessing-record");
3469 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003470
3471 // Suppress any editor placeholder diagnostics.
3472 Args->push_back("-fallow-editor-placeholders");
3473
Guy Benyei11169dd2012-12-18 14:30:41 +00003474 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003475 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003476 // Unless the user specified that they want the preamble on the first parse
3477 // set it up to be created on the first reparse. This makes the first parse
3478 // faster, trading for a slower (first) reparse.
3479 unsigned PrecompilePreambleAfterNParses =
3480 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003481
Alex Lorenz08615792017-12-04 21:56:36 +00003482 LibclangInvocationReporter InvocationReporter(
3483 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003484 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3485 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003486 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003487 Args->data(), Args->data() + Args->size(),
3488 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003489 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3490 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003491 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3492 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003493 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003494 /*UserFilesAreVolatile=*/true, ForSerialization,
3495 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3496 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003497
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003498 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003499 if (!Unit && !ErrUnit)
3500 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003501
Guy Benyei11169dd2012-12-18 14:30:41 +00003502 if (NumErrors != Diags->getClient()->getNumErrors()) {
3503 // Make sure to check that 'Unit' is non-NULL.
3504 if (CXXIdx->getDisplayDiagnostics())
3505 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3506 }
3507
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003508 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3509 return CXError_ASTReadError;
3510
David Blaikieea4395e2017-01-06 19:49:01 +00003511 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003512 if (CXTranslationUnitImpl *TU = *out_TU) {
3513 TU->ParsingOptions = options;
3514 TU->Arguments.reserve(Args->size());
3515 for (const char *Arg : *Args)
3516 TU->Arguments.push_back(Arg);
3517 return CXError_Success;
3518 }
3519 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003520}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003521
3522CXTranslationUnit
3523clang_parseTranslationUnit(CXIndex CIdx,
3524 const char *source_filename,
3525 const char *const *command_line_args,
3526 int num_command_line_args,
3527 struct CXUnsavedFile *unsaved_files,
3528 unsigned num_unsaved_files,
3529 unsigned options) {
3530 CXTranslationUnit TU;
3531 enum CXErrorCode Result = clang_parseTranslationUnit2(
3532 CIdx, source_filename, command_line_args, num_command_line_args,
3533 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003534 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003535 assert((TU && Result == CXError_Success) ||
3536 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003537 return TU;
3538}
3539
3540enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003541 CXIndex CIdx, const char *source_filename,
3542 const char *const *command_line_args, int num_command_line_args,
3543 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3544 unsigned options, CXTranslationUnit *out_TU) {
3545 SmallVector<const char *, 4> Args;
3546 Args.push_back("clang");
3547 Args.append(command_line_args, command_line_args + num_command_line_args);
3548 return clang_parseTranslationUnit2FullArgv(
3549 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3550 num_unsaved_files, options, out_TU);
3551}
3552
3553enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3554 CXIndex CIdx, const char *source_filename,
3555 const char *const *command_line_args, int num_command_line_args,
3556 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3557 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003558 LOG_FUNC_SECTION {
3559 *Log << source_filename << ": ";
3560 for (int i = 0; i != num_command_line_args; ++i)
3561 *Log << command_line_args[i] << " ";
3562 }
3563
Alp Toker9d85b182014-07-07 01:23:14 +00003564 if (num_unsaved_files && !unsaved_files)
3565 return CXError_InvalidArguments;
3566
Alp Toker5c532982014-07-07 22:42:03 +00003567 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003568 auto ParseTranslationUnitImpl = [=, &result] {
3569 result = clang_parseTranslationUnit_Impl(
3570 CIdx, source_filename, command_line_args, num_command_line_args,
3571 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3572 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003573
Guy Benyei11169dd2012-12-18 14:30:41 +00003574 llvm::CrashRecoveryContext CRC;
3575
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003576 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003577 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3578 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3579 fprintf(stderr, " 'command_line_args' : [");
3580 for (int i = 0; i != num_command_line_args; ++i) {
3581 if (i)
3582 fprintf(stderr, ", ");
3583 fprintf(stderr, "'%s'", command_line_args[i]);
3584 }
3585 fprintf(stderr, "],\n");
3586 fprintf(stderr, " 'unsaved_files' : [");
3587 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3588 if (i)
3589 fprintf(stderr, ", ");
3590 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3591 unsaved_files[i].Length);
3592 }
3593 fprintf(stderr, "],\n");
3594 fprintf(stderr, " 'options' : %d,\n", options);
3595 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003596
3597 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003598 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003599 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003600 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003601 }
Alp Toker5c532982014-07-07 22:42:03 +00003602
3603 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003604}
3605
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003606CXString clang_Type_getObjCEncoding(CXType CT) {
3607 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3608 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3609 std::string encoding;
3610 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3611 encoding);
3612
3613 return cxstring::createDup(encoding);
3614}
3615
3616static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3617 if (C.kind == CXCursor_MacroDefinition) {
3618 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3619 return MDR->getName();
3620 } else if (C.kind == CXCursor_MacroExpansion) {
3621 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3622 return ME.getName();
3623 }
3624 return nullptr;
3625}
3626
3627unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3628 const IdentifierInfo *II = getMacroIdentifier(C);
3629 if (!II) {
3630 return false;
3631 }
3632 ASTUnit *ASTU = getCursorASTUnit(C);
3633 Preprocessor &PP = ASTU->getPreprocessor();
3634 if (const MacroInfo *MI = PP.getMacroInfo(II))
3635 return MI->isFunctionLike();
3636 return false;
3637}
3638
3639unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3640 const IdentifierInfo *II = getMacroIdentifier(C);
3641 if (!II) {
3642 return false;
3643 }
3644 ASTUnit *ASTU = getCursorASTUnit(C);
3645 Preprocessor &PP = ASTU->getPreprocessor();
3646 if (const MacroInfo *MI = PP.getMacroInfo(II))
3647 return MI->isBuiltinMacro();
3648 return false;
3649}
3650
3651unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3652 const Decl *D = getCursorDecl(C);
3653 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3654 if (!FD) {
3655 return false;
3656 }
3657 return FD->isInlined();
3658}
3659
3660static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3661 if (callExpr->getNumArgs() != 1) {
3662 return nullptr;
3663 }
3664
3665 StringLiteral *S = nullptr;
3666 auto *arg = callExpr->getArg(0);
3667 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3668 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3669 auto *subExpr = I->getSubExprAsWritten();
3670
3671 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3672 return nullptr;
3673 }
3674
3675 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3676 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3677 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3678 } else {
3679 return nullptr;
3680 }
3681 return S;
3682}
3683
David Blaikie59272572016-04-13 18:23:33 +00003684struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003685 CXEvalResultKind EvalType;
3686 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003687 unsigned long long unsignedVal;
3688 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003689 double floatVal;
3690 char *stringVal;
3691 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003692 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003693 ~ExprEvalResult() {
3694 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3695 EvalType != CXEval_Int) {
Alex Lorenza19cb2e2019-01-08 23:28:37 +00003696 delete[] EvalData.stringVal;
David Blaikie59272572016-04-13 18:23:33 +00003697 }
3698 }
3699};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003700
3701void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003702 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003703}
3704
3705CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3706 if (!E) {
3707 return CXEval_UnExposed;
3708 }
3709 return ((ExprEvalResult *)E)->EvalType;
3710}
3711
3712int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003713 return clang_EvalResult_getAsLongLong(E);
3714}
3715
3716long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003717 if (!E) {
3718 return 0;
3719 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003720 ExprEvalResult *Result = (ExprEvalResult*)E;
3721 if (Result->IsUnsignedInt)
3722 return Result->EvalData.unsignedVal;
3723 return Result->EvalData.intVal;
3724}
3725
3726unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3727 return ((ExprEvalResult *)E)->IsUnsignedInt;
3728}
3729
3730unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3731 if (!E) {
3732 return 0;
3733 }
3734
3735 ExprEvalResult *Result = (ExprEvalResult*)E;
3736 if (Result->IsUnsignedInt)
3737 return Result->EvalData.unsignedVal;
3738 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003739}
3740
3741double clang_EvalResult_getAsDouble(CXEvalResult E) {
3742 if (!E) {
3743 return 0;
3744 }
3745 return ((ExprEvalResult *)E)->EvalData.floatVal;
3746}
3747
3748const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3749 if (!E) {
3750 return nullptr;
3751 }
3752 return ((ExprEvalResult *)E)->EvalData.stringVal;
3753}
3754
3755static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3756 Expr::EvalResult ER;
3757 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003758 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003759 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003760
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003761 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003762 if (!expr->EvaluateAsRValue(ER, ctx))
3763 return nullptr;
3764
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003765 QualType rettype;
3766 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003767 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003768 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003769 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003770
David Blaikiebbc00882016-04-13 18:36:19 +00003771 if (ER.Val.isInt()) {
3772 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003773
3774 auto& val = ER.Val.getInt();
3775 if (val.isUnsigned()) {
3776 result->IsUnsignedInt = true;
3777 result->EvalData.unsignedVal = val.getZExtValue();
3778 } else {
3779 result->EvalData.intVal = val.getExtValue();
3780 }
3781
David Blaikiebbc00882016-04-13 18:36:19 +00003782 return result.release();
3783 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003784
David Blaikiebbc00882016-04-13 18:36:19 +00003785 if (ER.Val.isFloat()) {
3786 llvm::SmallVector<char, 100> Buffer;
3787 ER.Val.getFloat().toString(Buffer);
3788 std::string floatStr(Buffer.data(), Buffer.size());
3789 result->EvalType = CXEval_Float;
3790 bool ignored;
3791 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003792 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003793 llvm::APFloat::rmNearestTiesToEven, &ignored);
3794 result->EvalData.floatVal = apFloat.convertToDouble();
3795 return result.release();
3796 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003797
David Blaikiebbc00882016-04-13 18:36:19 +00003798 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3799 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3800 auto *subExpr = I->getSubExprAsWritten();
3801 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3802 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003803 const StringLiteral *StrE = nullptr;
3804 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003805 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003806
3807 if (ObjCExpr) {
3808 StrE = ObjCExpr->getString();
3809 result->EvalType = CXEval_ObjCStrLiteral;
3810 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003811 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003812 result->EvalType = CXEval_StrLiteral;
3813 }
3814
3815 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003816 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003817 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3818 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003819 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003820 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003821 }
3822 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3823 expr->getStmtClass() == Stmt::StringLiteralClass) {
3824 const StringLiteral *StrE = nullptr;
3825 const ObjCStringLiteral *ObjCExpr;
3826 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003827
David Blaikiebbc00882016-04-13 18:36:19 +00003828 if (ObjCExpr) {
3829 StrE = ObjCExpr->getString();
3830 result->EvalType = CXEval_ObjCStrLiteral;
3831 } else {
3832 StrE = cast<StringLiteral>(expr);
3833 result->EvalType = CXEval_StrLiteral;
3834 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003835
David Blaikiebbc00882016-04-13 18:36:19 +00003836 std::string strRef(StrE->getString().str());
3837 result->EvalData.stringVal = new char[strRef.size() + 1];
3838 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3839 result->EvalData.stringVal[strRef.size()] = '\0';
3840 return result.release();
3841 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003842
David Blaikiebbc00882016-04-13 18:36:19 +00003843 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3844 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003845
David Blaikiebbc00882016-04-13 18:36:19 +00003846 rettype = CC->getType();
3847 if (rettype.getAsString() == "CFStringRef" &&
3848 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003849
David Blaikiebbc00882016-04-13 18:36:19 +00003850 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3851 StringLiteral *S = getCFSTR_value(callExpr);
3852 if (S) {
3853 std::string strLiteral(S->getString().str());
3854 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003855
David Blaikiebbc00882016-04-13 18:36:19 +00003856 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3857 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3858 strLiteral.size());
3859 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003860 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003861 }
3862 }
3863
David Blaikiebbc00882016-04-13 18:36:19 +00003864 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3865 callExpr = static_cast<CallExpr *>(expr);
3866 rettype = callExpr->getCallReturnType(ctx);
3867
3868 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3869 return nullptr;
3870
3871 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3872 if (callExpr->getNumArgs() == 1 &&
3873 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3874 return nullptr;
3875 } else if (rettype.getAsString() == "CFStringRef") {
3876
3877 StringLiteral *S = getCFSTR_value(callExpr);
3878 if (S) {
3879 std::string strLiteral(S->getString().str());
3880 result->EvalType = CXEval_CFStr;
3881 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3882 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3883 strLiteral.size());
3884 result->EvalData.stringVal[strLiteral.size()] = '\0';
3885 return result.release();
3886 }
3887 }
3888 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3889 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3890 ValueDecl *V = D->getDecl();
3891 if (V->getKind() == Decl::Function) {
3892 std::string strName = V->getNameAsString();
3893 result->EvalType = CXEval_Other;
3894 result->EvalData.stringVal = new char[strName.size() + 1];
3895 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3896 result->EvalData.stringVal[strName.size()] = '\0';
3897 return result.release();
3898 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003899 }
3900
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003901 return nullptr;
3902}
3903
Alex Lorenz65317e12019-01-08 22:32:51 +00003904static const Expr *evaluateDeclExpr(const Decl *D) {
3905 if (!D)
Evgeniy Stepanov9b871492018-07-10 19:48:53 +00003906 return nullptr;
Alex Lorenz65317e12019-01-08 22:32:51 +00003907 if (auto *Var = dyn_cast<VarDecl>(D))
3908 return Var->getInit();
3909 else if (auto *Field = dyn_cast<FieldDecl>(D))
3910 return Field->getInClassInitializer();
3911 return nullptr;
3912}
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003913
Alex Lorenz65317e12019-01-08 22:32:51 +00003914static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
3915 assert(CS && "invalid compound statement");
3916 for (auto *bodyIterator : CS->body()) {
3917 if (const auto *E = dyn_cast<Expr>(bodyIterator))
3918 return E;
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003919 }
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00003920 return nullptr;
3921}
3922
Alex Lorenz65317e12019-01-08 22:32:51 +00003923CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3924 if (const Expr *E =
3925 clang_getCursorKind(C) == CXCursor_CompoundStmt
3926 ? evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)))
3927 : evaluateDeclExpr(getCursorDecl(C)))
3928 return const_cast<CXEvalResult>(
3929 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
3930 return nullptr;
3931}
3932
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003933unsigned clang_Cursor_hasAttrs(CXCursor C) {
3934 const Decl *D = getCursorDecl(C);
3935 if (!D) {
3936 return 0;
3937 }
3938
3939 if (D->hasAttrs()) {
3940 return 1;
3941 }
3942
3943 return 0;
3944}
Guy Benyei11169dd2012-12-18 14:30:41 +00003945unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3946 return CXSaveTranslationUnit_None;
3947}
3948
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003949static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3950 const char *FileName,
3951 unsigned options) {
3952 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003953 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3954 setThreadBackgroundPriority();
3955
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003956 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3957 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003958}
3959
3960int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3961 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003962 LOG_FUNC_SECTION {
3963 *Log << TU << ' ' << FileName;
3964 }
3965
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003966 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003967 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003968 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003969 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003970
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003971 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003972 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3973 if (!CXXUnit->hasSema())
3974 return CXSaveError_InvalidTU;
3975
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003976 CXSaveError result;
3977 auto SaveTranslationUnitImpl = [=, &result]() {
3978 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3979 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003980
Erik Verbruggen3cc39112017-11-14 09:34:39 +00003981 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003982 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003983
3984 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3985 PrintLibclangResourceUsage(TU);
3986
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003987 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003988 }
3989
3990 // We have an AST that has invalid nodes due to compiler errors.
3991 // Use a crash recovery thread for protection.
3992
3993 llvm::CrashRecoveryContext CRC;
3994
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003995 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003996 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3997 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3998 fprintf(stderr, " 'options' : %d,\n", options);
3999 fprintf(stderr, "}\n");
4000
4001 return CXSaveError_Unknown;
4002
4003 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4004 PrintLibclangResourceUsage(TU);
4005 }
4006
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004007 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004008}
4009
4010void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4011 if (CTUnit) {
4012 // If the translation unit has been marked as unsafe to free, just discard
4013 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004014 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4015 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004016 return;
4017
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004018 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004019 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004020 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4021 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004022 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004023 delete CTUnit;
4024 }
4025}
4026
Erik Verbruggen346066b2017-05-30 14:25:54 +00004027unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4028 if (CTUnit) {
4029 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4030
4031 if (Unit && Unit->isUnsafeToFree())
4032 return false;
4033
4034 Unit->ResetForParse();
4035 return true;
4036 }
4037
4038 return false;
4039}
4040
Guy Benyei11169dd2012-12-18 14:30:41 +00004041unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4042 return CXReparse_None;
4043}
4044
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004045static CXErrorCode
4046clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4047 ArrayRef<CXUnsavedFile> unsaved_files,
4048 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004049 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004050 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004051 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004052 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004053 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004054
4055 // Reset the associated diagnostics.
4056 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004057 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004058
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004059 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004060 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4061 setThreadBackgroundPriority();
4062
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004063 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004064 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004065
4066 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4067 new std::vector<ASTUnit::RemappedFile>());
4068
Guy Benyei11169dd2012-12-18 14:30:41 +00004069 // Recover resources if we crash before exiting this function.
4070 llvm::CrashRecoveryContextCleanupRegistrar<
4071 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004072
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004073 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004074 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004075 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004076 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004077 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004078
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004079 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4080 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004081 return CXError_Success;
4082 if (isASTReadError(CXXUnit))
4083 return CXError_ASTReadError;
4084 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004085}
4086
4087int clang_reparseTranslationUnit(CXTranslationUnit TU,
4088 unsigned num_unsaved_files,
4089 struct CXUnsavedFile *unsaved_files,
4090 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004091 LOG_FUNC_SECTION {
4092 *Log << TU;
4093 }
4094
Alp Toker9d85b182014-07-07 01:23:14 +00004095 if (num_unsaved_files && !unsaved_files)
4096 return CXError_InvalidArguments;
4097
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004098 CXErrorCode result;
4099 auto ReparseTranslationUnitImpl = [=, &result]() {
4100 result = clang_reparseTranslationUnit_Impl(
4101 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4102 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004103
Guy Benyei11169dd2012-12-18 14:30:41 +00004104 llvm::CrashRecoveryContext CRC;
4105
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004106 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004107 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004108 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004109 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004110 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4111 PrintLibclangResourceUsage(TU);
4112
Alp Toker5c532982014-07-07 22:42:03 +00004113 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004114}
4115
4116
4117CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004118 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004119 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004120 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004121 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004122
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004123 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004124 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004125}
4126
4127CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004128 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004129 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004130 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004131 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004132
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004133 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004134 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4135}
4136
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004137CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4138 if (isNotUsableTU(CTUnit)) {
4139 LOG_BAD_TU(CTUnit);
4140 return nullptr;
4141 }
4142
4143 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4144 impl->TranslationUnit = CTUnit;
4145 return impl;
4146}
4147
4148CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4149 if (!TargetInfo)
4150 return cxstring::createEmpty();
4151
4152 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4153 assert(!isNotUsableTU(CTUnit) &&
4154 "Unexpected unusable translation unit in TargetInfo");
4155
4156 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4157 std::string Triple =
4158 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4159 return cxstring::createDup(Triple);
4160}
4161
4162int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4163 if (!TargetInfo)
4164 return -1;
4165
4166 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4167 assert(!isNotUsableTU(CTUnit) &&
4168 "Unexpected unusable translation unit in TargetInfo");
4169
4170 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4171 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4172}
4173
4174void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4175 if (!TargetInfo)
4176 return;
4177
4178 delete TargetInfo;
4179}
4180
Guy Benyei11169dd2012-12-18 14:30:41 +00004181//===----------------------------------------------------------------------===//
4182// CXFile Operations.
4183//===----------------------------------------------------------------------===//
4184
Guy Benyei11169dd2012-12-18 14:30:41 +00004185CXString clang_getFileName(CXFile SFile) {
4186 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004187 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004188
4189 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004190 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004191}
4192
4193time_t clang_getFileTime(CXFile SFile) {
4194 if (!SFile)
4195 return 0;
4196
4197 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4198 return FEnt->getModificationTime();
4199}
4200
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004201CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004202 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004203 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004204 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004205 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004206
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004207 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004208
4209 FileManager &FMgr = CXXUnit->getFileManager();
4210 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4211}
4212
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004213const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4214 size_t *size) {
4215 if (isNotUsableTU(TU)) {
4216 LOG_BAD_TU(TU);
4217 return nullptr;
4218 }
4219
4220 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4221 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4222 bool Invalid = true;
4223 llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
4224 if (Invalid) {
4225 if (size)
4226 *size = 0;
4227 return nullptr;
4228 }
4229 if (size)
4230 *size = buf->getBufferSize();
4231 return buf->getBufferStart();
4232}
4233
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004234unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4235 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004236 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004237 LOG_BAD_TU(TU);
4238 return 0;
4239 }
4240
4241 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004242 return 0;
4243
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004244 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004245 FileEntry *FEnt = static_cast<FileEntry *>(file);
4246 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4247 .isFileMultipleIncludeGuarded(FEnt);
4248}
4249
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004250int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4251 if (!file || !outID)
4252 return 1;
4253
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004254 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004255 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4256 outID->data[0] = ID.getDevice();
4257 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004258 outID->data[2] = FEnt->getModificationTime();
4259 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004260}
4261
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004262int clang_File_isEqual(CXFile file1, CXFile file2) {
4263 if (file1 == file2)
4264 return true;
4265
4266 if (!file1 || !file2)
4267 return false;
4268
4269 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4270 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4271 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4272}
4273
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004274CXString clang_File_tryGetRealPathName(CXFile SFile) {
4275 if (!SFile)
4276 return cxstring::createNull();
4277
4278 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4279 return cxstring::createRef(FEnt->tryGetRealPathName());
4280}
4281
Guy Benyei11169dd2012-12-18 14:30:41 +00004282//===----------------------------------------------------------------------===//
4283// CXCursor Operations.
4284//===----------------------------------------------------------------------===//
4285
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004286static const Decl *getDeclFromExpr(const Stmt *E) {
4287 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004288 return getDeclFromExpr(CE->getSubExpr());
4289
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004290 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004291 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004292 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004293 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004294 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004295 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004296 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004297 if (PRE->isExplicitProperty())
4298 return PRE->getExplicitProperty();
4299 // It could be messaging both getter and setter as in:
4300 // ++myobj.myprop;
4301 // in which case prefer to associate the setter since it is less obvious
4302 // from inspecting the source that the setter is going to get called.
4303 if (PRE->isMessagingSetter())
4304 return PRE->getImplicitPropertySetter();
4305 return PRE->getImplicitPropertyGetter();
4306 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004307 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004308 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004309 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004310 if (Expr *Src = OVE->getSourceExpr())
4311 return getDeclFromExpr(Src);
4312
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004313 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004314 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004315 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004316 if (!CE->isElidable())
4317 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004318 if (const CXXInheritedCtorInitExpr *CE =
4319 dyn_cast<CXXInheritedCtorInitExpr>(E))
4320 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004321 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004322 return OME->getMethodDecl();
4323
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004324 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004325 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004326 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004327 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4328 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004329 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004330 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4331 isa<ParmVarDecl>(SizeOfPack->getPack()))
4332 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004333
4334 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004335}
4336
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004337static SourceLocation getLocationFromExpr(const Expr *E) {
4338 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004339 return getLocationFromExpr(CE->getSubExpr());
4340
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004341 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004342 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004343 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004344 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004345 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004346 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004347 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004348 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004349 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004350 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004351 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004352 return PropRef->getLocation();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004353
4354 return E->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00004355}
4356
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004357extern "C" {
4358
Guy Benyei11169dd2012-12-18 14:30:41 +00004359unsigned clang_visitChildren(CXCursor parent,
4360 CXCursorVisitor visitor,
4361 CXClientData client_data) {
4362 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4363 /*VisitPreprocessorLast=*/false);
4364 return CursorVis.VisitChildren(parent);
4365}
4366
4367#ifndef __has_feature
4368#define __has_feature(x) 0
4369#endif
4370#if __has_feature(blocks)
4371typedef enum CXChildVisitResult
4372 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4373
4374static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4375 CXClientData client_data) {
4376 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4377 return block(cursor, parent);
4378}
4379#else
4380// If we are compiled with a compiler that doesn't have native blocks support,
4381// define and call the block manually, so the
4382typedef struct _CXChildVisitResult
4383{
4384 void *isa;
4385 int flags;
4386 int reserved;
4387 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4388 CXCursor);
4389} *CXCursorVisitorBlock;
4390
4391static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4392 CXClientData client_data) {
4393 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4394 return block->invoke(block, cursor, parent);
4395}
4396#endif
4397
4398
4399unsigned clang_visitChildrenWithBlock(CXCursor parent,
4400 CXCursorVisitorBlock block) {
4401 return clang_visitChildren(parent, visitWithBlock, block);
4402}
4403
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004404static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004405 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004406 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004407
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004408 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004409 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004410 if (const ObjCPropertyImplDecl *PropImpl =
4411 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004412 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004413 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004414
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004415 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004416 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004417 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004418
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004419 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004420 }
4421
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004422 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004423 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004424
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004425 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004426 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4427 // and returns different names. NamedDecl returns the class name and
4428 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004429 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004430
4431 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004432 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004433
4434 SmallString<1024> S;
4435 llvm::raw_svector_ostream os(S);
4436 ND->printName(os);
4437
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004438 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004439}
4440
4441CXString clang_getCursorSpelling(CXCursor C) {
4442 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004443 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004444
4445 if (clang_isReference(C.kind)) {
4446 switch (C.kind) {
4447 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004448 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004449 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004450 }
4451 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004452 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004453 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004454 }
4455 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004456 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004457 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004458 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004459 }
4460 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004461 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004462 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004463 }
4464 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004465 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004466 assert(Type && "Missing type decl");
4467
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004468 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004469 getAsString());
4470 }
4471 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004472 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004473 assert(Template && "Missing template decl");
4474
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004475 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004476 }
4477
4478 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004479 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004480 assert(NS && "Missing namespace decl");
4481
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004482 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004483 }
4484
4485 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004486 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004487 assert(Field && "Missing member decl");
4488
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004489 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004490 }
4491
4492 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004493 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004494 assert(Label && "Missing label");
4495
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004496 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004497 }
4498
4499 case CXCursor_OverloadedDeclRef: {
4500 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004501 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4502 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004503 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004504 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004505 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004506 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004507 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004508 OverloadedTemplateStorage *Ovl
4509 = Storage.get<OverloadedTemplateStorage*>();
4510 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004511 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004512 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004513 }
4514
4515 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004516 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004517 assert(Var && "Missing variable decl");
4518
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004519 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004520 }
4521
4522 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004523 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004524 }
4525 }
4526
4527 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004528 const Expr *E = getCursorExpr(C);
4529
4530 if (C.kind == CXCursor_ObjCStringLiteral ||
4531 C.kind == CXCursor_StringLiteral) {
4532 const StringLiteral *SLit;
4533 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4534 SLit = OSL->getString();
4535 } else {
4536 SLit = cast<StringLiteral>(E);
4537 }
4538 SmallString<256> Buf;
4539 llvm::raw_svector_ostream OS(Buf);
4540 SLit->outputString(OS);
4541 return cxstring::createDup(OS.str());
4542 }
4543
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004544 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 if (D)
4546 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004547 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004548 }
4549
4550 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004551 const Stmt *S = getCursorStmt(C);
4552 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004553 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004554
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004555 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004556 }
4557
4558 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004559 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004560 ->getNameStart());
4561
4562 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004563 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004564 ->getNameStart());
4565
4566 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004567 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004568
4569 if (clang_isDeclaration(C.kind))
4570 return getDeclSpelling(getCursorDecl(C));
4571
4572 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004573 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004574 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004575 }
4576
4577 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004578 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004579 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004580 }
4581
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004582 if (C.kind == CXCursor_PackedAttr) {
4583 return cxstring::createRef("packed");
4584 }
4585
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004586 if (C.kind == CXCursor_VisibilityAttr) {
4587 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4588 switch (AA->getVisibility()) {
4589 case VisibilityAttr::VisibilityType::Default:
4590 return cxstring::createRef("default");
4591 case VisibilityAttr::VisibilityType::Hidden:
4592 return cxstring::createRef("hidden");
4593 case VisibilityAttr::VisibilityType::Protected:
4594 return cxstring::createRef("protected");
4595 }
4596 llvm_unreachable("unknown visibility type");
4597 }
4598
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004599 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004600}
4601
4602CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4603 unsigned pieceIndex,
4604 unsigned options) {
4605 if (clang_Cursor_isNull(C))
4606 return clang_getNullRange();
4607
4608 ASTContext &Ctx = getCursorContext(C);
4609
4610 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004611 const Stmt *S = getCursorStmt(C);
4612 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004613 if (pieceIndex > 0)
4614 return clang_getNullRange();
4615 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4616 }
4617
4618 return clang_getNullRange();
4619 }
4620
4621 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004622 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004623 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4624 if (pieceIndex >= ME->getNumSelectorLocs())
4625 return clang_getNullRange();
4626 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4627 }
4628 }
4629
4630 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4631 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004632 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004633 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4634 if (pieceIndex >= MD->getNumSelectorLocs())
4635 return clang_getNullRange();
4636 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4637 }
4638 }
4639
4640 if (C.kind == CXCursor_ObjCCategoryDecl ||
4641 C.kind == CXCursor_ObjCCategoryImplDecl) {
4642 if (pieceIndex > 0)
4643 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004644 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004645 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4646 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004647 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004648 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4649 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4650 }
4651
4652 if (C.kind == CXCursor_ModuleImportDecl) {
4653 if (pieceIndex > 0)
4654 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004655 if (const ImportDecl *ImportD =
4656 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004657 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4658 if (!Locs.empty())
4659 return cxloc::translateSourceRange(Ctx,
4660 SourceRange(Locs.front(), Locs.back()));
4661 }
4662 return clang_getNullRange();
4663 }
4664
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004665 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004666 C.kind == CXCursor_ConversionFunction ||
4667 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004668 if (pieceIndex > 0)
4669 return clang_getNullRange();
4670 if (const FunctionDecl *FD =
4671 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4672 DeclarationNameInfo FunctionName = FD->getNameInfo();
4673 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4674 }
4675 return clang_getNullRange();
4676 }
4677
Guy Benyei11169dd2012-12-18 14:30:41 +00004678 // FIXME: A CXCursor_InclusionDirective should give the location of the
4679 // filename, but we don't keep track of this.
4680
4681 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4682 // but we don't keep track of this.
4683
4684 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4685 // but we don't keep track of this.
4686
4687 // Default handling, give the location of the cursor.
4688
4689 if (pieceIndex > 0)
4690 return clang_getNullRange();
4691
4692 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4693 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4694 return cxloc::translateSourceRange(Ctx, Loc);
4695}
4696
Eli Bendersky44a206f2014-07-31 18:04:56 +00004697CXString clang_Cursor_getMangling(CXCursor C) {
4698 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4699 return cxstring::createEmpty();
4700
Eli Bendersky44a206f2014-07-31 18:04:56 +00004701 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004702 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004703 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4704 return cxstring::createEmpty();
4705
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004706 ASTContext &Ctx = D->getASTContext();
4707 index::CodegenNameGenerator CGNameGen(Ctx);
4708 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004709}
4710
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004711CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4712 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4713 return nullptr;
4714
4715 const Decl *D = getCursorDecl(C);
4716 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4717 return nullptr;
4718
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004719 ASTContext &Ctx = D->getASTContext();
4720 index::CodegenNameGenerator CGNameGen(Ctx);
4721 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004722 return cxstring::createSet(Manglings);
4723}
4724
Dave Lee1a532c92017-09-22 16:58:57 +00004725CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4726 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4727 return nullptr;
4728
4729 const Decl *D = getCursorDecl(C);
4730 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4731 return nullptr;
4732
4733 ASTContext &Ctx = D->getASTContext();
4734 index::CodegenNameGenerator CGNameGen(Ctx);
4735 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4736 return cxstring::createSet(Manglings);
4737}
4738
Jonathan Coe45ef5032018-01-16 10:19:56 +00004739CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4740 if (clang_Cursor_isNull(C))
4741 return 0;
4742 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4743}
4744
4745void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4746 if (Policy)
4747 delete static_cast<PrintingPolicy *>(Policy);
4748}
4749
4750unsigned
4751clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4752 enum CXPrintingPolicyProperty Property) {
4753 if (!Policy)
4754 return 0;
4755
4756 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4757 switch (Property) {
4758 case CXPrintingPolicy_Indentation:
4759 return P->Indentation;
4760 case CXPrintingPolicy_SuppressSpecifiers:
4761 return P->SuppressSpecifiers;
4762 case CXPrintingPolicy_SuppressTagKeyword:
4763 return P->SuppressTagKeyword;
4764 case CXPrintingPolicy_IncludeTagDefinition:
4765 return P->IncludeTagDefinition;
4766 case CXPrintingPolicy_SuppressScope:
4767 return P->SuppressScope;
4768 case CXPrintingPolicy_SuppressUnwrittenScope:
4769 return P->SuppressUnwrittenScope;
4770 case CXPrintingPolicy_SuppressInitializers:
4771 return P->SuppressInitializers;
4772 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4773 return P->ConstantArraySizeAsWritten;
4774 case CXPrintingPolicy_AnonymousTagLocations:
4775 return P->AnonymousTagLocations;
4776 case CXPrintingPolicy_SuppressStrongLifetime:
4777 return P->SuppressStrongLifetime;
4778 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4779 return P->SuppressLifetimeQualifiers;
4780 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4781 return P->SuppressTemplateArgsInCXXConstructors;
4782 case CXPrintingPolicy_Bool:
4783 return P->Bool;
4784 case CXPrintingPolicy_Restrict:
4785 return P->Restrict;
4786 case CXPrintingPolicy_Alignof:
4787 return P->Alignof;
4788 case CXPrintingPolicy_UnderscoreAlignof:
4789 return P->UnderscoreAlignof;
4790 case CXPrintingPolicy_UseVoidForZeroParams:
4791 return P->UseVoidForZeroParams;
4792 case CXPrintingPolicy_TerseOutput:
4793 return P->TerseOutput;
4794 case CXPrintingPolicy_PolishForDeclaration:
4795 return P->PolishForDeclaration;
4796 case CXPrintingPolicy_Half:
4797 return P->Half;
4798 case CXPrintingPolicy_MSWChar:
4799 return P->MSWChar;
4800 case CXPrintingPolicy_IncludeNewlines:
4801 return P->IncludeNewlines;
4802 case CXPrintingPolicy_MSVCFormatting:
4803 return P->MSVCFormatting;
4804 case CXPrintingPolicy_ConstantsAsWritten:
4805 return P->ConstantsAsWritten;
4806 case CXPrintingPolicy_SuppressImplicitBase:
4807 return P->SuppressImplicitBase;
4808 case CXPrintingPolicy_FullyQualifiedName:
4809 return P->FullyQualifiedName;
4810 }
4811
4812 assert(false && "Invalid CXPrintingPolicyProperty");
4813 return 0;
4814}
4815
4816void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4817 enum CXPrintingPolicyProperty Property,
4818 unsigned Value) {
4819 if (!Policy)
4820 return;
4821
4822 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4823 switch (Property) {
4824 case CXPrintingPolicy_Indentation:
4825 P->Indentation = Value;
4826 return;
4827 case CXPrintingPolicy_SuppressSpecifiers:
4828 P->SuppressSpecifiers = Value;
4829 return;
4830 case CXPrintingPolicy_SuppressTagKeyword:
4831 P->SuppressTagKeyword = Value;
4832 return;
4833 case CXPrintingPolicy_IncludeTagDefinition:
4834 P->IncludeTagDefinition = Value;
4835 return;
4836 case CXPrintingPolicy_SuppressScope:
4837 P->SuppressScope = Value;
4838 return;
4839 case CXPrintingPolicy_SuppressUnwrittenScope:
4840 P->SuppressUnwrittenScope = Value;
4841 return;
4842 case CXPrintingPolicy_SuppressInitializers:
4843 P->SuppressInitializers = Value;
4844 return;
4845 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4846 P->ConstantArraySizeAsWritten = Value;
4847 return;
4848 case CXPrintingPolicy_AnonymousTagLocations:
4849 P->AnonymousTagLocations = Value;
4850 return;
4851 case CXPrintingPolicy_SuppressStrongLifetime:
4852 P->SuppressStrongLifetime = Value;
4853 return;
4854 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4855 P->SuppressLifetimeQualifiers = Value;
4856 return;
4857 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4858 P->SuppressTemplateArgsInCXXConstructors = Value;
4859 return;
4860 case CXPrintingPolicy_Bool:
4861 P->Bool = Value;
4862 return;
4863 case CXPrintingPolicy_Restrict:
4864 P->Restrict = Value;
4865 return;
4866 case CXPrintingPolicy_Alignof:
4867 P->Alignof = Value;
4868 return;
4869 case CXPrintingPolicy_UnderscoreAlignof:
4870 P->UnderscoreAlignof = Value;
4871 return;
4872 case CXPrintingPolicy_UseVoidForZeroParams:
4873 P->UseVoidForZeroParams = Value;
4874 return;
4875 case CXPrintingPolicy_TerseOutput:
4876 P->TerseOutput = Value;
4877 return;
4878 case CXPrintingPolicy_PolishForDeclaration:
4879 P->PolishForDeclaration = Value;
4880 return;
4881 case CXPrintingPolicy_Half:
4882 P->Half = Value;
4883 return;
4884 case CXPrintingPolicy_MSWChar:
4885 P->MSWChar = Value;
4886 return;
4887 case CXPrintingPolicy_IncludeNewlines:
4888 P->IncludeNewlines = Value;
4889 return;
4890 case CXPrintingPolicy_MSVCFormatting:
4891 P->MSVCFormatting = Value;
4892 return;
4893 case CXPrintingPolicy_ConstantsAsWritten:
4894 P->ConstantsAsWritten = Value;
4895 return;
4896 case CXPrintingPolicy_SuppressImplicitBase:
4897 P->SuppressImplicitBase = Value;
4898 return;
4899 case CXPrintingPolicy_FullyQualifiedName:
4900 P->FullyQualifiedName = Value;
4901 return;
4902 }
4903
4904 assert(false && "Invalid CXPrintingPolicyProperty");
4905}
4906
4907CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4908 if (clang_Cursor_isNull(C))
4909 return cxstring::createEmpty();
4910
4911 if (clang_isDeclaration(C.kind)) {
4912 const Decl *D = getCursorDecl(C);
4913 if (!D)
4914 return cxstring::createEmpty();
4915
4916 SmallString<128> Str;
4917 llvm::raw_svector_ostream OS(Str);
4918 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4919 D->print(OS, UserPolicy ? *UserPolicy
4920 : getCursorContext(C).getPrintingPolicy());
4921
4922 return cxstring::createDup(OS.str());
4923 }
4924
4925 return cxstring::createEmpty();
4926}
4927
Guy Benyei11169dd2012-12-18 14:30:41 +00004928CXString clang_getCursorDisplayName(CXCursor C) {
4929 if (!clang_isDeclaration(C.kind))
4930 return clang_getCursorSpelling(C);
4931
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004932 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004933 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004934 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004935
4936 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004937 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004938 D = FunTmpl->getTemplatedDecl();
4939
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004940 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004941 SmallString<64> Str;
4942 llvm::raw_svector_ostream OS(Str);
4943 OS << *Function;
4944 if (Function->getPrimaryTemplate())
4945 OS << "<>";
4946 OS << "(";
4947 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4948 if (I)
4949 OS << ", ";
4950 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4951 }
4952
4953 if (Function->isVariadic()) {
4954 if (Function->getNumParams())
4955 OS << ", ";
4956 OS << "...";
4957 }
4958 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004959 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004960 }
4961
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004962 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004963 SmallString<64> Str;
4964 llvm::raw_svector_ostream OS(Str);
4965 OS << *ClassTemplate;
4966 OS << "<";
4967 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4968 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4969 if (I)
4970 OS << ", ";
4971
4972 NamedDecl *Param = Params->getParam(I);
4973 if (Param->getIdentifier()) {
4974 OS << Param->getIdentifier()->getName();
4975 continue;
4976 }
4977
4978 // There is no parameter name, which makes this tricky. Try to come up
4979 // with something useful that isn't too long.
4980 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4981 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4982 else if (NonTypeTemplateParmDecl *NTTP
4983 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4984 OS << NTTP->getType().getAsString(Policy);
4985 else
4986 OS << "template<...> class";
4987 }
4988
4989 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004990 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004991 }
4992
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004993 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00004994 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4995 // If the type was explicitly written, use that.
4996 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004997 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00004998
Benjamin Kramer9170e912013-02-22 15:46:01 +00004999 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00005000 llvm::raw_svector_ostream OS(Str);
5001 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00005002 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5003 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005004 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005005 }
5006
5007 return clang_getCursorSpelling(C);
5008}
5009
5010CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5011 switch (Kind) {
5012 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005013 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005014 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005015 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005016 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005017 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005018 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005019 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005020 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005021 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005022 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005023 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005024 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005025 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005026 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005027 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005028 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005029 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005030 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005031 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005032 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005033 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005034 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005035 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005036 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005037 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005038 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005039 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005040 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005041 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005042 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005043 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005044 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005045 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005046 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005047 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005048 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005049 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005050 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005051 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005052 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005053 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005054 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005055 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005056 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005057 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005058 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005059 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005060 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005061 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005062 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005063 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005064 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005065 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005066 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005067 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005068 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005069 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005070 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005071 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005072 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005073 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005074 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005075 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005076 case CXCursor_FixedPointLiteral:
5077 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005078 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005079 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005080 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005081 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005082 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005083 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005084 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005085 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005086 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005087 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005088 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005089 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005090 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005091 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005092 case CXCursor_OMPArraySectionExpr:
5093 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005094 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005095 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005096 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005097 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005098 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005099 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005100 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005101 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005102 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005103 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005104 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005105 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005106 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005107 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005108 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005109 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005110 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005111 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005112 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005113 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005114 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005115 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005116 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005117 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005118 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005119 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005120 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005121 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005122 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005123 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005124 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005125 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005126 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005127 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005128 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005129 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005130 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005131 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005132 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005133 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005134 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005135 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005136 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005137 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005138 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005139 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005140 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005141 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005142 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005143 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005144 case CXCursor_ObjCAvailabilityCheckExpr:
5145 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005146 case CXCursor_ObjCSelfExpr:
5147 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005148 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005149 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005150 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005151 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005152 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005153 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005154 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005155 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005156 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005157 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005158 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005159 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005160 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005161 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005162 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005163 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005164 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005165 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005166 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005167 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005168 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005169 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005170 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005171 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005172 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005173 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005174 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005175 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005176 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005177 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005178 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005179 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005180 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005181 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005182 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005183 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005184 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005185 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005186 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005187 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005188 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005189 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005190 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005191 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005192 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005193 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005194 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005195 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005196 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005197 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005198 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005199 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005200 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005201 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005202 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005203 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005204 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005205 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005206 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005207 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005208 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005209 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005210 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005211 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005212 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005213 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005214 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005215 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005216 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005217 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005218 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005219 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005220 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005221 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005222 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005223 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005224 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005225 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005226 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005227 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005228 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005229 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005230 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005231 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005232 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005233 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005234 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005235 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005236 case CXCursor_SEHLeaveStmt:
5237 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005238 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005239 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005240 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005241 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005242 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005243 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005244 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005245 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005246 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005247 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005248 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005249 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005250 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005251 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005252 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005253 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005254 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005255 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005256 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005257 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005258 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005259 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005260 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005261 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005262 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005263 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005264 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005265 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005266 case CXCursor_PackedAttr:
5267 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005268 case CXCursor_PureAttr:
5269 return cxstring::createRef("attribute(pure)");
5270 case CXCursor_ConstAttr:
5271 return cxstring::createRef("attribute(const)");
5272 case CXCursor_NoDuplicateAttr:
5273 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005274 case CXCursor_CUDAConstantAttr:
5275 return cxstring::createRef("attribute(constant)");
5276 case CXCursor_CUDADeviceAttr:
5277 return cxstring::createRef("attribute(device)");
5278 case CXCursor_CUDAGlobalAttr:
5279 return cxstring::createRef("attribute(global)");
5280 case CXCursor_CUDAHostAttr:
5281 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005282 case CXCursor_CUDASharedAttr:
5283 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005284 case CXCursor_VisibilityAttr:
5285 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005286 case CXCursor_DLLExport:
5287 return cxstring::createRef("attribute(dllexport)");
5288 case CXCursor_DLLImport:
5289 return cxstring::createRef("attribute(dllimport)");
Michael Wud092d0b2018-08-03 05:03:22 +00005290 case CXCursor_NSReturnsRetained:
5291 return cxstring::createRef("attribute(ns_returns_retained)");
5292 case CXCursor_NSReturnsNotRetained:
5293 return cxstring::createRef("attribute(ns_returns_not_retained)");
5294 case CXCursor_NSReturnsAutoreleased:
5295 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5296 case CXCursor_NSConsumesSelf:
5297 return cxstring::createRef("attribute(ns_consumes_self)");
5298 case CXCursor_NSConsumed:
5299 return cxstring::createRef("attribute(ns_consumed)");
5300 case CXCursor_ObjCException:
5301 return cxstring::createRef("attribute(objc_exception)");
5302 case CXCursor_ObjCNSObject:
5303 return cxstring::createRef("attribute(NSObject)");
5304 case CXCursor_ObjCIndependentClass:
5305 return cxstring::createRef("attribute(objc_independent_class)");
5306 case CXCursor_ObjCPreciseLifetime:
5307 return cxstring::createRef("attribute(objc_precise_lifetime)");
5308 case CXCursor_ObjCReturnsInnerPointer:
5309 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5310 case CXCursor_ObjCRequiresSuper:
5311 return cxstring::createRef("attribute(objc_requires_super)");
5312 case CXCursor_ObjCRootClass:
5313 return cxstring::createRef("attribute(objc_root_class)");
5314 case CXCursor_ObjCSubclassingRestricted:
5315 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5316 case CXCursor_ObjCExplicitProtocolImpl:
5317 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5318 case CXCursor_ObjCDesignatedInitializer:
5319 return cxstring::createRef("attribute(objc_designated_initializer)");
5320 case CXCursor_ObjCRuntimeVisible:
5321 return cxstring::createRef("attribute(objc_runtime_visible)");
5322 case CXCursor_ObjCBoxable:
5323 return cxstring::createRef("attribute(objc_boxable)");
Michael Wu58d837d2018-08-03 05:55:40 +00005324 case CXCursor_FlagEnum:
5325 return cxstring::createRef("attribute(flag_enum)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005326 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005327 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005328 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005329 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005330 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005331 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005332 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005333 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005334 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005335 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005336 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005337 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005338 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005339 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005340 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005341 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005342 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005343 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005344 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005345 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005346 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005347 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005348 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005349 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005350 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005351 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005352 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005353 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005354 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005355 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005356 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005357 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005358 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005359 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005360 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005361 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005362 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005363 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005364 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005365 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005366 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005367 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005368 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005369 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005370 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005371 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005372 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005373 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005374 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005375 return cxstring::createRef("OMPParallelDirective");
5376 case CXCursor_OMPSimdDirective:
5377 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005378 case CXCursor_OMPForDirective:
5379 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005380 case CXCursor_OMPForSimdDirective:
5381 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005382 case CXCursor_OMPSectionsDirective:
5383 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005384 case CXCursor_OMPSectionDirective:
5385 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005386 case CXCursor_OMPSingleDirective:
5387 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005388 case CXCursor_OMPMasterDirective:
5389 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005390 case CXCursor_OMPCriticalDirective:
5391 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005392 case CXCursor_OMPParallelForDirective:
5393 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005394 case CXCursor_OMPParallelForSimdDirective:
5395 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005396 case CXCursor_OMPParallelSectionsDirective:
5397 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005398 case CXCursor_OMPTaskDirective:
5399 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005400 case CXCursor_OMPTaskyieldDirective:
5401 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005402 case CXCursor_OMPBarrierDirective:
5403 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005404 case CXCursor_OMPTaskwaitDirective:
5405 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005406 case CXCursor_OMPTaskgroupDirective:
5407 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005408 case CXCursor_OMPFlushDirective:
5409 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005410 case CXCursor_OMPOrderedDirective:
5411 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005412 case CXCursor_OMPAtomicDirective:
5413 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005414 case CXCursor_OMPTargetDirective:
5415 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005416 case CXCursor_OMPTargetDataDirective:
5417 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005418 case CXCursor_OMPTargetEnterDataDirective:
5419 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005420 case CXCursor_OMPTargetExitDataDirective:
5421 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005422 case CXCursor_OMPTargetParallelDirective:
5423 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005424 case CXCursor_OMPTargetParallelForDirective:
5425 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005426 case CXCursor_OMPTargetUpdateDirective:
5427 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005428 case CXCursor_OMPTeamsDirective:
5429 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005430 case CXCursor_OMPCancellationPointDirective:
5431 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005432 case CXCursor_OMPCancelDirective:
5433 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005434 case CXCursor_OMPTaskLoopDirective:
5435 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005436 case CXCursor_OMPTaskLoopSimdDirective:
5437 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005438 case CXCursor_OMPDistributeDirective:
5439 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005440 case CXCursor_OMPDistributeParallelForDirective:
5441 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005442 case CXCursor_OMPDistributeParallelForSimdDirective:
5443 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005444 case CXCursor_OMPDistributeSimdDirective:
5445 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005446 case CXCursor_OMPTargetParallelForSimdDirective:
5447 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005448 case CXCursor_OMPTargetSimdDirective:
5449 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005450 case CXCursor_OMPTeamsDistributeDirective:
5451 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005452 case CXCursor_OMPTeamsDistributeSimdDirective:
5453 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005454 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5455 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005456 case CXCursor_OMPTeamsDistributeParallelForDirective:
5457 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005458 case CXCursor_OMPTargetTeamsDirective:
5459 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005460 case CXCursor_OMPTargetTeamsDistributeDirective:
5461 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005462 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5463 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005464 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5465 return cxstring::createRef(
5466 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005467 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5468 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005469 case CXCursor_OverloadCandidate:
5470 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005471 case CXCursor_TypeAliasTemplateDecl:
5472 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005473 case CXCursor_StaticAssert:
5474 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005475 case CXCursor_FriendDecl:
Sven van Haastregtdc2c9302019-02-11 11:00:56 +00005476 return cxstring::createRef("FriendDecl");
5477 case CXCursor_ConvergentAttr:
5478 return cxstring::createRef("attribute(convergent)");
Emilio Cobos Alvarez0a3fe502019-02-25 21:24:52 +00005479 case CXCursor_WarnUnusedAttr:
5480 return cxstring::createRef("attribute(warn_unused)");
5481 case CXCursor_WarnUnusedResultAttr:
5482 return cxstring::createRef("attribute(warn_unused_result)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005483 }
5484
5485 llvm_unreachable("Unhandled CXCursorKind");
5486}
5487
5488struct GetCursorData {
5489 SourceLocation TokenBeginLoc;
5490 bool PointsAtMacroArgExpansion;
5491 bool VisitedObjCPropertyImplDecl;
5492 SourceLocation VisitedDeclaratorDeclStartLoc;
5493 CXCursor &BestCursor;
5494
5495 GetCursorData(SourceManager &SM,
5496 SourceLocation tokenBegin, CXCursor &outputCursor)
5497 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5498 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5499 VisitedObjCPropertyImplDecl = false;
5500 }
5501};
5502
5503static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5504 CXCursor parent,
5505 CXClientData client_data) {
5506 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5507 CXCursor *BestCursor = &Data->BestCursor;
5508
5509 // If we point inside a macro argument we should provide info of what the
5510 // token is so use the actual cursor, don't replace it with a macro expansion
5511 // cursor.
5512 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5513 return CXChildVisit_Recurse;
5514
5515 if (clang_isDeclaration(cursor.kind)) {
5516 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005517 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005518 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5519 if (MD->isImplicit())
5520 return CXChildVisit_Break;
5521
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005522 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005523 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5524 // Check that when we have multiple @class references in the same line,
5525 // that later ones do not override the previous ones.
5526 // If we have:
5527 // @class Foo, Bar;
5528 // source ranges for both start at '@', so 'Bar' will end up overriding
5529 // 'Foo' even though the cursor location was at 'Foo'.
5530 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5531 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005532 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005533 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5534 if (PrevID != ID &&
5535 !PrevID->isThisDeclarationADefinition() &&
5536 !ID->isThisDeclarationADefinition())
5537 return CXChildVisit_Break;
5538 }
5539
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005540 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005541 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5542 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5543 // Check that when we have multiple declarators in the same line,
5544 // that later ones do not override the previous ones.
5545 // If we have:
5546 // int Foo, Bar;
5547 // source ranges for both start at 'int', so 'Bar' will end up overriding
5548 // 'Foo' even though the cursor location was at 'Foo'.
5549 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5550 return CXChildVisit_Break;
5551 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5552
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005553 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005554 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5555 (void)PropImp;
5556 // Check that when we have multiple @synthesize in the same line,
5557 // that later ones do not override the previous ones.
5558 // If we have:
5559 // @synthesize Foo, Bar;
5560 // source ranges for both start at '@', so 'Bar' will end up overriding
5561 // 'Foo' even though the cursor location was at 'Foo'.
5562 if (Data->VisitedObjCPropertyImplDecl)
5563 return CXChildVisit_Break;
5564 Data->VisitedObjCPropertyImplDecl = true;
5565 }
5566 }
5567
5568 if (clang_isExpression(cursor.kind) &&
5569 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005570 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005571 // Avoid having the cursor of an expression replace the declaration cursor
5572 // when the expression source range overlaps the declaration range.
5573 // This can happen for C++ constructor expressions whose range generally
5574 // include the variable declaration, e.g.:
5575 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5576 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5577 D->getLocation() == Data->TokenBeginLoc)
5578 return CXChildVisit_Break;
5579 }
5580 }
5581
5582 // If our current best cursor is the construction of a temporary object,
5583 // don't replace that cursor with a type reference, because we want
5584 // clang_getCursor() to point at the constructor.
5585 if (clang_isExpression(BestCursor->kind) &&
5586 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5587 cursor.kind == CXCursor_TypeRef) {
5588 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5589 // as having the actual point on the type reference.
5590 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5591 return CXChildVisit_Recurse;
5592 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005593
5594 // If we already have an Objective-C superclass reference, don't
5595 // update it further.
5596 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5597 return CXChildVisit_Break;
5598
Guy Benyei11169dd2012-12-18 14:30:41 +00005599 *BestCursor = cursor;
5600 return CXChildVisit_Recurse;
5601}
5602
5603CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005604 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005605 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005606 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005607 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005608
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005609 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005610 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5611
5612 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5613 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5614
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005615 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005616 CXFile SearchFile;
5617 unsigned SearchLine, SearchColumn;
5618 CXFile ResultFile;
5619 unsigned ResultLine, ResultColumn;
5620 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5621 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5622 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005623
5624 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5625 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005626 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005627 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005628 SearchFileName = clang_getFileName(SearchFile);
5629 ResultFileName = clang_getFileName(ResultFile);
5630 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5631 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005632 *Log << llvm::format("(%s:%d:%d) = %s",
5633 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5634 clang_getCString(KindSpelling))
5635 << llvm::format("(%s:%d:%d):%s%s",
5636 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5637 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005638 clang_disposeString(SearchFileName);
5639 clang_disposeString(ResultFileName);
5640 clang_disposeString(KindSpelling);
5641 clang_disposeString(USR);
5642
5643 CXCursor Definition = clang_getCursorDefinition(Result);
5644 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5645 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5646 CXString DefinitionKindSpelling
5647 = clang_getCursorKindSpelling(Definition.kind);
5648 CXFile DefinitionFile;
5649 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005650 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005651 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005652 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005653 *Log << llvm::format(" -> %s(%s:%d:%d)",
5654 clang_getCString(DefinitionKindSpelling),
5655 clang_getCString(DefinitionFileName),
5656 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005657 clang_disposeString(DefinitionFileName);
5658 clang_disposeString(DefinitionKindSpelling);
5659 }
5660 }
5661
5662 return Result;
5663}
5664
5665CXCursor clang_getNullCursor(void) {
5666 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5667}
5668
5669unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005670 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5671 // can't set consistently. For example, when visiting a DeclStmt we will set
5672 // it but we don't set it on the result of clang_getCursorDefinition for
5673 // a reference of the same declaration.
5674 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5675 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5676 // to provide that kind of info.
5677 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005678 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005679 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005680 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005681
Guy Benyei11169dd2012-12-18 14:30:41 +00005682 return X == Y;
5683}
5684
5685unsigned clang_hashCursor(CXCursor C) {
5686 unsigned Index = 0;
5687 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5688 Index = 1;
5689
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005690 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005691 std::make_pair(C.kind, C.data[Index]));
5692}
5693
5694unsigned clang_isInvalid(enum CXCursorKind K) {
5695 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5696}
5697
5698unsigned clang_isDeclaration(enum CXCursorKind K) {
5699 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005700 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5701}
5702
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005703unsigned clang_isInvalidDeclaration(CXCursor C) {
5704 if (clang_isDeclaration(C.kind)) {
5705 if (const Decl *D = getCursorDecl(C))
5706 return D->isInvalidDecl();
5707 }
5708
5709 return 0;
5710}
5711
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005712unsigned clang_isReference(enum CXCursorKind K) {
5713 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5714}
Guy Benyei11169dd2012-12-18 14:30:41 +00005715
5716unsigned clang_isExpression(enum CXCursorKind K) {
5717 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5718}
5719
5720unsigned clang_isStatement(enum CXCursorKind K) {
5721 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5722}
5723
5724unsigned clang_isAttribute(enum CXCursorKind K) {
5725 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5726}
5727
5728unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5729 return K == CXCursor_TranslationUnit;
5730}
5731
5732unsigned clang_isPreprocessing(enum CXCursorKind K) {
5733 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5734}
5735
5736unsigned clang_isUnexposed(enum CXCursorKind K) {
5737 switch (K) {
5738 case CXCursor_UnexposedDecl:
5739 case CXCursor_UnexposedExpr:
5740 case CXCursor_UnexposedStmt:
5741 case CXCursor_UnexposedAttr:
5742 return true;
5743 default:
5744 return false;
5745 }
5746}
5747
5748CXCursorKind clang_getCursorKind(CXCursor C) {
5749 return C.kind;
5750}
5751
5752CXSourceLocation clang_getCursorLocation(CXCursor C) {
5753 if (clang_isReference(C.kind)) {
5754 switch (C.kind) {
5755 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005756 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005757 = getCursorObjCSuperClassRef(C);
5758 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5759 }
5760
5761 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005762 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005763 = getCursorObjCProtocolRef(C);
5764 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5765 }
5766
5767 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005768 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005769 = getCursorObjCClassRef(C);
5770 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5771 }
5772
5773 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005774 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005775 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5776 }
5777
5778 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005779 std::pair<const TemplateDecl *, SourceLocation> P =
5780 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005781 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5782 }
5783
5784 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005785 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005786 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5787 }
5788
5789 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005790 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005791 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5792 }
5793
5794 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005795 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005796 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5797 }
5798
5799 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005800 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005801 if (!BaseSpec)
5802 return clang_getNullLocation();
5803
5804 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5805 return cxloc::translateSourceLocation(getCursorContext(C),
5806 TSInfo->getTypeLoc().getBeginLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005807
Guy Benyei11169dd2012-12-18 14:30:41 +00005808 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005809 BaseSpec->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005810 }
5811
5812 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005813 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005814 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5815 }
5816
5817 case CXCursor_OverloadedDeclRef:
5818 return cxloc::translateSourceLocation(getCursorContext(C),
5819 getCursorOverloadedDeclRef(C).second);
5820
5821 default:
5822 // FIXME: Need a way to enumerate all non-reference cases.
5823 llvm_unreachable("Missed a reference kind");
5824 }
5825 }
5826
5827 if (clang_isExpression(C.kind))
5828 return cxloc::translateSourceLocation(getCursorContext(C),
5829 getLocationFromExpr(getCursorExpr(C)));
5830
5831 if (clang_isStatement(C.kind))
5832 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005833 getCursorStmt(C)->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005834
5835 if (C.kind == CXCursor_PreprocessingDirective) {
5836 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5837 return cxloc::translateSourceLocation(getCursorContext(C), L);
5838 }
5839
5840 if (C.kind == CXCursor_MacroExpansion) {
5841 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005842 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005843 return cxloc::translateSourceLocation(getCursorContext(C), L);
5844 }
5845
5846 if (C.kind == CXCursor_MacroDefinition) {
5847 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5848 return cxloc::translateSourceLocation(getCursorContext(C), L);
5849 }
5850
5851 if (C.kind == CXCursor_InclusionDirective) {
5852 SourceLocation L
5853 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5854 return cxloc::translateSourceLocation(getCursorContext(C), L);
5855 }
5856
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005857 if (clang_isAttribute(C.kind)) {
5858 SourceLocation L
5859 = cxcursor::getCursorAttr(C)->getLocation();
5860 return cxloc::translateSourceLocation(getCursorContext(C), L);
5861 }
5862
Guy Benyei11169dd2012-12-18 14:30:41 +00005863 if (!clang_isDeclaration(C.kind))
5864 return clang_getNullLocation();
5865
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005866 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005867 if (!D)
5868 return clang_getNullLocation();
5869
5870 SourceLocation Loc = D->getLocation();
5871 // FIXME: Multiple variables declared in a single declaration
5872 // currently lack the information needed to correctly determine their
5873 // ranges when accounting for the type-specifier. We use context
5874 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5875 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005876 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005877 if (!cxcursor::isFirstInDeclGroup(C))
5878 Loc = VD->getLocation();
5879 }
5880
5881 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005882 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005883 Loc = MD->getSelectorStartLoc();
5884
5885 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5886}
5887
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005888} // end extern "C"
5889
Guy Benyei11169dd2012-12-18 14:30:41 +00005890CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5891 assert(TU);
5892
5893 // Guard against an invalid SourceLocation, or we may assert in one
5894 // of the following calls.
5895 if (SLoc.isInvalid())
5896 return clang_getNullCursor();
5897
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005898 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005899
5900 // Translate the given source location to make it point at the beginning of
5901 // the token under the cursor.
5902 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5903 CXXUnit->getASTContext().getLangOpts());
5904
5905 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5906 if (SLoc.isValid()) {
5907 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5908 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5909 /*VisitPreprocessorLast=*/true,
5910 /*VisitIncludedEntities=*/false,
5911 SourceLocation(SLoc));
5912 CursorVis.visitFileRegion();
5913 }
5914
5915 return Result;
5916}
5917
5918static SourceRange getRawCursorExtent(CXCursor C) {
5919 if (clang_isReference(C.kind)) {
5920 switch (C.kind) {
5921 case CXCursor_ObjCSuperClassRef:
5922 return getCursorObjCSuperClassRef(C).second;
5923
5924 case CXCursor_ObjCProtocolRef:
5925 return getCursorObjCProtocolRef(C).second;
5926
5927 case CXCursor_ObjCClassRef:
5928 return getCursorObjCClassRef(C).second;
5929
5930 case CXCursor_TypeRef:
5931 return getCursorTypeRef(C).second;
5932
5933 case CXCursor_TemplateRef:
5934 return getCursorTemplateRef(C).second;
5935
5936 case CXCursor_NamespaceRef:
5937 return getCursorNamespaceRef(C).second;
5938
5939 case CXCursor_MemberRef:
5940 return getCursorMemberRef(C).second;
5941
5942 case CXCursor_CXXBaseSpecifier:
5943 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5944
5945 case CXCursor_LabelRef:
5946 return getCursorLabelRef(C).second;
5947
5948 case CXCursor_OverloadedDeclRef:
5949 return getCursorOverloadedDeclRef(C).second;
5950
5951 case CXCursor_VariableRef:
5952 return getCursorVariableRef(C).second;
5953
5954 default:
5955 // FIXME: Need a way to enumerate all non-reference cases.
5956 llvm_unreachable("Missed a reference kind");
5957 }
5958 }
5959
5960 if (clang_isExpression(C.kind))
5961 return getCursorExpr(C)->getSourceRange();
5962
5963 if (clang_isStatement(C.kind))
5964 return getCursorStmt(C)->getSourceRange();
5965
5966 if (clang_isAttribute(C.kind))
5967 return getCursorAttr(C)->getRange();
5968
5969 if (C.kind == CXCursor_PreprocessingDirective)
5970 return cxcursor::getCursorPreprocessingDirective(C);
5971
5972 if (C.kind == CXCursor_MacroExpansion) {
5973 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005974 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005975 return TU->mapRangeFromPreamble(Range);
5976 }
5977
5978 if (C.kind == CXCursor_MacroDefinition) {
5979 ASTUnit *TU = getCursorASTUnit(C);
5980 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5981 return TU->mapRangeFromPreamble(Range);
5982 }
5983
5984 if (C.kind == CXCursor_InclusionDirective) {
5985 ASTUnit *TU = getCursorASTUnit(C);
5986 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5987 return TU->mapRangeFromPreamble(Range);
5988 }
5989
5990 if (C.kind == CXCursor_TranslationUnit) {
5991 ASTUnit *TU = getCursorASTUnit(C);
5992 FileID MainID = TU->getSourceManager().getMainFileID();
5993 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5994 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5995 return SourceRange(Start, End);
5996 }
5997
5998 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005999 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006000 if (!D)
6001 return SourceRange();
6002
6003 SourceRange R = D->getSourceRange();
6004 // FIXME: Multiple variables declared in a single declaration
6005 // currently lack the information needed to correctly determine their
6006 // ranges when accounting for the type-specifier. We use context
6007 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6008 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006009 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006010 if (!cxcursor::isFirstInDeclGroup(C))
6011 R.setBegin(VD->getLocation());
6012 }
6013 return R;
6014 }
6015 return SourceRange();
6016}
6017
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006018/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00006019/// the decl-specifier-seq for declarations.
6020static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6021 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006022 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006023 if (!D)
6024 return SourceRange();
6025
6026 SourceRange R = D->getSourceRange();
6027
6028 // Adjust the start of the location for declarations preceded by
6029 // declaration specifiers.
6030 SourceLocation StartLoc;
6031 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6032 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006033 StartLoc = TI->getTypeLoc().getBeginLoc();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006034 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006035 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006036 StartLoc = TI->getTypeLoc().getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006037 }
6038
6039 if (StartLoc.isValid() && R.getBegin().isValid() &&
6040 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6041 R.setBegin(StartLoc);
6042
6043 // FIXME: Multiple variables declared in a single declaration
6044 // currently lack the information needed to correctly determine their
6045 // ranges when accounting for the type-specifier. We use context
6046 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6047 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006048 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006049 if (!cxcursor::isFirstInDeclGroup(C))
6050 R.setBegin(VD->getLocation());
6051 }
6052
6053 return R;
6054 }
6055
6056 return getRawCursorExtent(C);
6057}
6058
Guy Benyei11169dd2012-12-18 14:30:41 +00006059CXSourceRange clang_getCursorExtent(CXCursor C) {
6060 SourceRange R = getRawCursorExtent(C);
6061 if (R.isInvalid())
6062 return clang_getNullRange();
6063
6064 return cxloc::translateSourceRange(getCursorContext(C), R);
6065}
6066
6067CXCursor clang_getCursorReferenced(CXCursor C) {
6068 if (clang_isInvalid(C.kind))
6069 return clang_getNullCursor();
6070
6071 CXTranslationUnit tu = getCursorTU(C);
6072 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006073 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006074 if (!D)
6075 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006076 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006077 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006078 if (const ObjCPropertyImplDecl *PropImpl =
6079 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006080 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6081 return MakeCXCursor(Property, tu);
6082
6083 return C;
6084 }
6085
6086 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006087 const Expr *E = getCursorExpr(C);
6088 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006089 if (D) {
6090 CXCursor declCursor = MakeCXCursor(D, tu);
6091 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6092 declCursor);
6093 return declCursor;
6094 }
6095
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006096 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006097 return MakeCursorOverloadedDeclRef(Ovl, tu);
6098
6099 return clang_getNullCursor();
6100 }
6101
6102 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006103 const Stmt *S = getCursorStmt(C);
6104 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006105 if (LabelDecl *label = Goto->getLabel())
6106 if (LabelStmt *labelS = label->getStmt())
6107 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6108
6109 return clang_getNullCursor();
6110 }
Richard Smith66a81862015-05-04 02:25:31 +00006111
Guy Benyei11169dd2012-12-18 14:30:41 +00006112 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006113 if (const MacroDefinitionRecord *Def =
6114 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006115 return MakeMacroDefinitionCursor(Def, tu);
6116 }
6117
6118 if (!clang_isReference(C.kind))
6119 return clang_getNullCursor();
6120
6121 switch (C.kind) {
6122 case CXCursor_ObjCSuperClassRef:
6123 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6124
6125 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006126 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6127 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006128 return MakeCXCursor(Def, tu);
6129
6130 return MakeCXCursor(Prot, tu);
6131 }
6132
6133 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006134 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6135 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006136 return MakeCXCursor(Def, tu);
6137
6138 return MakeCXCursor(Class, tu);
6139 }
6140
6141 case CXCursor_TypeRef:
6142 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6143
6144 case CXCursor_TemplateRef:
6145 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6146
6147 case CXCursor_NamespaceRef:
6148 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6149
6150 case CXCursor_MemberRef:
6151 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6152
6153 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006154 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006155 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6156 tu ));
6157 }
6158
6159 case CXCursor_LabelRef:
6160 // FIXME: We end up faking the "parent" declaration here because we
6161 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006162 return MakeCXCursor(getCursorLabelRef(C).first,
6163 cxtu::getASTUnit(tu)->getASTContext()
6164 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006165 tu);
6166
6167 case CXCursor_OverloadedDeclRef:
6168 return C;
6169
6170 case CXCursor_VariableRef:
6171 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6172
6173 default:
6174 // We would prefer to enumerate all non-reference cursor kinds here.
6175 llvm_unreachable("Unhandled reference cursor kind");
6176 }
6177}
6178
6179CXCursor clang_getCursorDefinition(CXCursor C) {
6180 if (clang_isInvalid(C.kind))
6181 return clang_getNullCursor();
6182
6183 CXTranslationUnit TU = getCursorTU(C);
6184
6185 bool WasReference = false;
6186 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6187 C = clang_getCursorReferenced(C);
6188 WasReference = true;
6189 }
6190
6191 if (C.kind == CXCursor_MacroExpansion)
6192 return clang_getCursorReferenced(C);
6193
6194 if (!clang_isDeclaration(C.kind))
6195 return clang_getNullCursor();
6196
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006197 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006198 if (!D)
6199 return clang_getNullCursor();
6200
6201 switch (D->getKind()) {
6202 // Declaration kinds that don't really separate the notions of
6203 // declaration and definition.
6204 case Decl::Namespace:
6205 case Decl::Typedef:
6206 case Decl::TypeAlias:
6207 case Decl::TypeAliasTemplate:
6208 case Decl::TemplateTypeParm:
6209 case Decl::EnumConstant:
6210 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006211 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006212 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006213 case Decl::IndirectField:
6214 case Decl::ObjCIvar:
6215 case Decl::ObjCAtDefsField:
6216 case Decl::ImplicitParam:
6217 case Decl::ParmVar:
6218 case Decl::NonTypeTemplateParm:
6219 case Decl::TemplateTemplateParm:
6220 case Decl::ObjCCategoryImpl:
6221 case Decl::ObjCImplementation:
6222 case Decl::AccessSpec:
6223 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006224 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006225 case Decl::ObjCPropertyImpl:
6226 case Decl::FileScopeAsm:
6227 case Decl::StaticAssert:
6228 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006229 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006230 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006231 case Decl::Label: // FIXME: Is this right??
6232 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006233 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006234 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006235 case Decl::OMPThreadPrivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00006236 case Decl::OMPAllocate:
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