blob: b3d2974b43b0df73ac9430cdfc95405863695088 [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Guy Benyei11169dd2012-12-18 14:30:41 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the main API hooks in the Clang-C Source Indexing
10// library.
11//
12//===----------------------------------------------------------------------===//
13
Guy Benyei11169dd2012-12-18 14:30:41 +000014#include "CIndexDiagnostic.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000015#include "CIndexer.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000016#include "CLog.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000017#include "CXCursor.h"
18#include "CXSourceLocation.h"
19#include "CXString.h"
20#include "CXTranslationUnit.h"
21#include "CXType.h"
22#include "CursorVisitor.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000023#include "clang/AST/Attr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000024#include "clang/AST/StmtVisitor.h"
25#include "clang/Basic/Diagnostic.h"
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000026#include "clang/Basic/DiagnosticCategories.h"
27#include "clang/Basic/DiagnosticIDs.h"
Richard Smith0a7b2972018-07-03 21:34:13 +000028#include "clang/Basic/Stack.h"
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +000029#include "clang/Basic/TargetInfo.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000030#include "clang/Basic/Version.h"
31#include "clang/Frontend/ASTUnit.h"
32#include "clang/Frontend/CompilerInstance.h"
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +000033#include "clang/Index/CodegenNameGenerator.h"
Dmitri Gribenko9e605112013-11-13 22:16:51 +000034#include "clang/Index/CommentToXML.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000035#include "clang/Lex/HeaderSearch.h"
36#include "clang/Lex/Lexer.h"
37#include "clang/Lex/PreprocessingRecord.h"
38#include "clang/Lex/Preprocessor.h"
39#include "llvm/ADT/Optional.h"
40#include "llvm/ADT/STLExtras.h"
41#include "llvm/ADT/StringSwitch.h"
Alp Toker1d257e12014-06-04 03:28:55 +000042#include "llvm/Config/llvm-config.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000043#include "llvm/Support/Compiler.h"
44#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000045#include "llvm/Support/Format.h"
Chandler Carruth37ad2582014-06-27 15:14:39 +000046#include "llvm/Support/ManagedStatic.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000047#include "llvm/Support/MemoryBuffer.h"
48#include "llvm/Support/Mutex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000049#include "llvm/Support/Program.h"
50#include "llvm/Support/SaveAndRestore.h"
51#include "llvm/Support/Signals.h"
Adrian Prantlbc068582015-07-08 01:00:30 +000052#include "llvm/Support/TargetSelect.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000053#include "llvm/Support/Threading.h"
54#include "llvm/Support/Timer.h"
55#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000056
Alp Toker1a86ad22014-07-06 06:24:00 +000057#if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
58#define USE_DARWIN_THREADS
59#endif
60
61#ifdef USE_DARWIN_THREADS
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +000062#include <pthread.h>
63#endif
Guy Benyei11169dd2012-12-18 14:30:41 +000064
65using namespace clang;
66using namespace clang::cxcursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000067using namespace clang::cxtu;
68using namespace clang::cxindex;
69
David Blaikieea4395e2017-01-06 19:49:01 +000070CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
71 std::unique_ptr<ASTUnit> AU) {
Dmitri Gribenkod36209e2013-01-26 21:32:42 +000072 if (!AU)
Craig Topper69186e72014-06-08 08:38:04 +000073 return nullptr;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000074 assert(CIdx);
Guy Benyei11169dd2012-12-18 14:30:41 +000075 CXTranslationUnit D = new CXTranslationUnitImpl();
76 D->CIdx = CIdx;
David Blaikieea4395e2017-01-06 19:49:01 +000077 D->TheASTUnit = AU.release();
Dmitri Gribenko74895212013-02-03 13:52:47 +000078 D->StringPool = new cxstring::CXStringPool();
Craig Topper69186e72014-06-08 08:38:04 +000079 D->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000080 D->OverridenCursorsPool = createOverridenCXCursorsPool();
Craig Topper69186e72014-06-08 08:38:04 +000081 D->CommentToXML = nullptr;
Alex Lorenz690f0e22017-12-07 20:37:50 +000082 D->ParsingOptions = 0;
83 D->Arguments = {};
Guy Benyei11169dd2012-12-18 14:30:41 +000084 return D;
85}
86
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000087bool cxtu::isASTReadError(ASTUnit *AU) {
88 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
89 DEnd = AU->stored_diag_end();
90 D != DEnd; ++D) {
91 if (D->getLevel() >= DiagnosticsEngine::Error &&
92 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
93 diag::DiagCat_AST_Deserialization_Issue)
94 return true;
95 }
96 return false;
97}
98
Guy Benyei11169dd2012-12-18 14:30:41 +000099cxtu::CXTUOwner::~CXTUOwner() {
100 if (TU)
101 clang_disposeTranslationUnit(TU);
102}
103
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000104/// Compare two source ranges to determine their relative position in
Guy Benyei11169dd2012-12-18 14:30:41 +0000105/// the translation unit.
106static RangeComparisonResult RangeCompare(SourceManager &SM,
107 SourceRange R1,
108 SourceRange R2) {
109 assert(R1.isValid() && "First range is invalid?");
110 assert(R2.isValid() && "Second range is invalid?");
111 if (R1.getEnd() != R2.getBegin() &&
112 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
113 return RangeBefore;
114 if (R2.getEnd() != R1.getBegin() &&
115 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
116 return RangeAfter;
117 return RangeOverlap;
118}
119
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000120/// Determine if a source location falls within, before, or after a
Guy Benyei11169dd2012-12-18 14:30:41 +0000121/// a given source range.
122static RangeComparisonResult LocationCompare(SourceManager &SM,
123 SourceLocation L, SourceRange R) {
124 assert(R.isValid() && "First range is invalid?");
125 assert(L.isValid() && "Second range is invalid?");
126 if (L == R.getBegin() || L == R.getEnd())
127 return RangeOverlap;
128 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
129 return RangeBefore;
130 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
131 return RangeAfter;
132 return RangeOverlap;
133}
134
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000135/// Translate a Clang source range into a CIndex source range.
Guy Benyei11169dd2012-12-18 14:30:41 +0000136///
137/// Clang internally represents ranges where the end location points to the
138/// start of the token at the end. However, for external clients it is more
139/// useful to have a CXSourceRange be a proper half-open interval. This routine
140/// does the appropriate translation.
141CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
142 const LangOptions &LangOpts,
143 const CharSourceRange &R) {
144 // We want the last character in this location, so we will adjust the
145 // location accordingly.
146 SourceLocation EndLoc = R.getEnd();
Richard Smithb5f81712018-04-30 05:25:48 +0000147 bool IsTokenRange = R.isTokenRange();
148 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc)) {
149 CharSourceRange Expansion = SM.getExpansionRange(EndLoc);
150 EndLoc = Expansion.getEnd();
151 IsTokenRange = Expansion.isTokenRange();
152 }
153 if (IsTokenRange && EndLoc.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000154 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
155 SM, LangOpts);
156 EndLoc = EndLoc.getLocWithOffset(Length);
157 }
158
Bill Wendlingeade3622013-01-23 08:25:41 +0000159 CXSourceRange Result = {
Dmitri Gribenkof9304482013-01-23 15:56:07 +0000160 { &SM, &LangOpts },
Bill Wendlingeade3622013-01-23 08:25:41 +0000161 R.getBegin().getRawEncoding(),
162 EndLoc.getRawEncoding()
163 };
Guy Benyei11169dd2012-12-18 14:30:41 +0000164 return Result;
165}
166
167//===----------------------------------------------------------------------===//
168// Cursor visitor.
169//===----------------------------------------------------------------------===//
170
171static SourceRange getRawCursorExtent(CXCursor C);
172static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
173
Guy Benyei11169dd2012-12-18 14:30:41 +0000174RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
175 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
176}
177
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000178/// Visit the given cursor and, if requested by the visitor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000179/// its children.
180///
181/// \param Cursor the cursor to visit.
182///
183/// \param CheckedRegionOfInterest if true, then the caller already checked
184/// that this cursor is within the region of interest.
185///
186/// \returns true if the visitation should be aborted, false if it
187/// should continue.
188bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
189 if (clang_isInvalid(Cursor.kind))
190 return false;
191
192 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000193 const Decl *D = getCursorDecl(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +0000194 if (!D) {
195 assert(0 && "Invalid declaration cursor");
196 return true; // abort.
197 }
198
199 // Ignore implicit declarations, unless it's an objc method because
200 // currently we should report implicit methods for properties when indexing.
201 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
202 return false;
203 }
204
205 // If we have a range of interest, and this cursor doesn't intersect with it,
206 // we're done.
207 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
208 SourceRange Range = getRawCursorExtent(Cursor);
209 if (Range.isInvalid() || CompareRegionOfInterest(Range))
210 return false;
211 }
212
213 switch (Visitor(Cursor, Parent, ClientData)) {
214 case CXChildVisit_Break:
215 return true;
216
217 case CXChildVisit_Continue:
218 return false;
219
220 case CXChildVisit_Recurse: {
221 bool ret = VisitChildren(Cursor);
222 if (PostChildrenVisitor)
223 if (PostChildrenVisitor(Cursor, ClientData))
224 return true;
225 return ret;
226 }
227 }
228
229 llvm_unreachable("Invalid CXChildVisitResult!");
230}
231
232static bool visitPreprocessedEntitiesInRange(SourceRange R,
233 PreprocessingRecord &PPRec,
234 CursorVisitor &Visitor) {
235 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
236 FileID FID;
237
238 if (!Visitor.shouldVisitIncludedEntities()) {
239 // If the begin/end of the range lie in the same FileID, do the optimization
240 // where we skip preprocessed entities that do not come from the same FileID.
241 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
242 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
243 FID = FileID();
244 }
245
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000246 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
247 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000248 PPRec, FID);
249}
250
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000251bool CursorVisitor::visitFileRegion() {
Guy Benyei11169dd2012-12-18 14:30:41 +0000252 if (RegionOfInterest.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000253 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000254
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000255 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000256 SourceManager &SM = Unit->getSourceManager();
257
258 std::pair<FileID, unsigned>
259 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
260 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
261
262 if (End.first != Begin.first) {
263 // If the end does not reside in the same file, try to recover by
264 // picking the end of the file of begin location.
265 End.first = Begin.first;
266 End.second = SM.getFileIDSize(Begin.first);
267 }
268
269 assert(Begin.first == End.first);
270 if (Begin.second > End.second)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000271 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000272
273 FileID File = Begin.first;
274 unsigned Offset = Begin.second;
275 unsigned Length = End.second - Begin.second;
276
277 if (!VisitDeclsOnly && !VisitPreprocessorLast)
278 if (visitPreprocessedEntitiesInRegion())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000279 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000280
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000281 if (visitDeclsFromFileRegion(File, Offset, Length))
282 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000283
284 if (!VisitDeclsOnly && VisitPreprocessorLast)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000285 return visitPreprocessedEntitiesInRegion();
286
287 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000288}
289
290static bool isInLexicalContext(Decl *D, DeclContext *DC) {
291 if (!DC)
292 return false;
293
294 for (DeclContext *DeclDC = D->getLexicalDeclContext();
295 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
296 if (DeclDC == DC)
297 return true;
298 }
299 return false;
300}
301
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000302bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
Guy Benyei11169dd2012-12-18 14:30:41 +0000303 unsigned Offset, unsigned Length) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000304 ASTUnit *Unit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000305 SourceManager &SM = Unit->getSourceManager();
306 SourceRange Range = RegionOfInterest;
307
308 SmallVector<Decl *, 16> Decls;
309 Unit->findFileRegionDecls(File, Offset, Length, Decls);
310
311 // If we didn't find any file level decls for the file, try looking at the
312 // file that it was included from.
313 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
314 bool Invalid = false;
315 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
316 if (Invalid)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000317 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000318
319 SourceLocation Outer;
320 if (SLEntry.isFile())
321 Outer = SLEntry.getFile().getIncludeLoc();
322 else
323 Outer = SLEntry.getExpansion().getExpansionLocStart();
324 if (Outer.isInvalid())
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000325 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000326
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000327 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
Guy Benyei11169dd2012-12-18 14:30:41 +0000328 Length = 0;
329 Unit->findFileRegionDecls(File, Offset, Length, Decls);
330 }
331
332 assert(!Decls.empty());
333
334 bool VisitedAtLeastOnce = false;
Craig Topper69186e72014-06-08 08:38:04 +0000335 DeclContext *CurDC = nullptr;
Craig Topper2341c0d2013-07-04 03:08:24 +0000336 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
337 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000338 Decl *D = *DIt;
339 if (D->getSourceRange().isInvalid())
340 continue;
341
342 if (isInLexicalContext(D, CurDC))
343 continue;
344
345 CurDC = dyn_cast<DeclContext>(D);
346
347 if (TagDecl *TD = dyn_cast<TagDecl>(D))
348 if (!TD->isFreeStanding())
349 continue;
350
351 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
352 if (CompRes == RangeBefore)
353 continue;
354 if (CompRes == RangeAfter)
355 break;
356
357 assert(CompRes == RangeOverlap);
358 VisitedAtLeastOnce = true;
359
360 if (isa<ObjCContainerDecl>(D)) {
361 FileDI_current = &DIt;
362 FileDE_current = DE;
363 } else {
Craig Topper69186e72014-06-08 08:38:04 +0000364 FileDI_current = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000365 }
366
367 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000368 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000369 }
370
371 if (VisitedAtLeastOnce)
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000372 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000373
374 // No Decls overlapped with the range. Move up the lexical context until there
375 // is a context that contains the range or we reach the translation unit
376 // level.
377 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
378 : (*(DIt-1))->getLexicalDeclContext();
379
380 while (DC && !DC->isTranslationUnit()) {
381 Decl *D = cast<Decl>(DC);
382 SourceRange CurDeclRange = D->getSourceRange();
383 if (CurDeclRange.isInvalid())
384 break;
385
386 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000387 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
388 return true; // visitation break.
Guy Benyei11169dd2012-12-18 14:30:41 +0000389 }
390
391 DC = D->getLexicalDeclContext();
392 }
Argyrios Kyrtzidis951f61f2013-03-08 20:42:33 +0000393
394 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000395}
396
397bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
398 if (!AU->getPreprocessor().getPreprocessingRecord())
399 return false;
400
401 PreprocessingRecord &PPRec
402 = *AU->getPreprocessor().getPreprocessingRecord();
403 SourceManager &SM = AU->getSourceManager();
404
405 if (RegionOfInterest.isValid()) {
406 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
407 SourceLocation B = MappedRange.getBegin();
408 SourceLocation E = MappedRange.getEnd();
409
410 if (AU->isInPreambleFileID(B)) {
411 if (SM.isLoadedSourceLocation(E))
412 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
413 PPRec, *this);
414
415 // Beginning of range lies in the preamble but it also extends beyond
416 // it into the main file. Split the range into 2 parts, one covering
417 // the preamble and another covering the main file. This allows subsequent
418 // calls to visitPreprocessedEntitiesInRange to accept a source range that
419 // lies in the same FileID, allowing it to skip preprocessed entities that
420 // do not come from the same FileID.
421 bool breaked =
422 visitPreprocessedEntitiesInRange(
423 SourceRange(B, AU->getEndOfPreambleFileID()),
424 PPRec, *this);
425 if (breaked) return true;
426 return visitPreprocessedEntitiesInRange(
427 SourceRange(AU->getStartOfMainFileID(), E),
428 PPRec, *this);
429 }
430
431 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
432 }
433
434 bool OnlyLocalDecls
435 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
436
437 if (OnlyLocalDecls)
438 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
439 PPRec);
440
441 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
442}
443
444template<typename InputIterator>
445bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
446 InputIterator Last,
447 PreprocessingRecord &PPRec,
448 FileID FID) {
449 for (; First != Last; ++First) {
450 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
451 continue;
452
453 PreprocessedEntity *PPE = *First;
Argyrios Kyrtzidis1030f262013-05-07 20:37:17 +0000454 if (!PPE)
455 continue;
456
Guy Benyei11169dd2012-12-18 14:30:41 +0000457 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
458 if (Visit(MakeMacroExpansionCursor(ME, TU)))
459 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000460
Guy Benyei11169dd2012-12-18 14:30:41 +0000461 continue;
462 }
Richard Smith66a81862015-05-04 02:25:31 +0000463
464 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000465 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
466 return true;
Richard Smith66a81862015-05-04 02:25:31 +0000467
Guy Benyei11169dd2012-12-18 14:30:41 +0000468 continue;
469 }
470
471 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
472 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
473 return true;
474
475 continue;
476 }
477 }
478
479 return false;
480}
481
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000482/// Visit the children of the given cursor.
Guy Benyei11169dd2012-12-18 14:30:41 +0000483///
484/// \returns true if the visitation should be aborted, false if it
485/// should continue.
486bool CursorVisitor::VisitChildren(CXCursor Cursor) {
487 if (clang_isReference(Cursor.kind) &&
488 Cursor.kind != CXCursor_CXXBaseSpecifier) {
489 // By definition, references have no children.
490 return false;
491 }
492
493 // Set the Parent field to Cursor, then back to its old value once we're
494 // done.
495 SetParentRAII SetParent(Parent, StmtParent, Cursor);
496
497 if (clang_isDeclaration(Cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +0000498 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +0000499 if (!D)
500 return false;
501
502 return VisitAttributes(D) || Visit(D);
503 }
504
505 if (clang_isStatement(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000506 if (const Stmt *S = getCursorStmt(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000507 return Visit(S);
508
509 return false;
510 }
511
512 if (clang_isExpression(Cursor.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +0000513 if (const Expr *E = getCursorExpr(Cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +0000514 return Visit(E);
515
516 return false;
517 }
518
519 if (clang_isTranslationUnit(Cursor.kind)) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +0000520 CXTranslationUnit TU = getCursorTU(Cursor);
521 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +0000522
523 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
524 for (unsigned I = 0; I != 2; ++I) {
525 if (VisitOrder[I]) {
526 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
527 RegionOfInterest.isInvalid()) {
528 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
529 TLEnd = CXXUnit->top_level_end();
530 TL != TLEnd; ++TL) {
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000531 const Optional<bool> V = handleDeclForVisitation(*TL);
532 if (!V.hasValue())
533 continue;
534 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000535 }
536 } else if (VisitDeclContext(
537 CXXUnit->getASTContext().getTranslationUnitDecl()))
538 return true;
539 continue;
540 }
541
542 // Walk the preprocessing record.
543 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
544 visitPreprocessedEntitiesInRegion();
545 }
546
547 return false;
548 }
549
550 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000551 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000552 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
553 return Visit(BaseTSInfo->getTypeLoc());
554 }
555 }
556 }
557
558 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +0000559 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +0000560 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
Richard Smithb1f9a282013-10-31 01:56:18 +0000561 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
Richard Smithb87c4652013-10-31 21:23:20 +0000562 return Visit(cxcursor::MakeCursorObjCClassRef(
563 ObjT->getInterface(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000564 A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +0000565 }
566
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000567 // If pointing inside a macro definition, check if the token is an identifier
568 // that was ever defined as a macro. In such a case, create a "pseudo" macro
569 // expansion cursor for that token.
570 SourceLocation BeginLoc = RegionOfInterest.getBegin();
571 if (Cursor.kind == CXCursor_MacroDefinition &&
572 BeginLoc == RegionOfInterest.getEnd()) {
573 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +0000574 const MacroInfo *MI =
575 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
Richard Smith66a81862015-05-04 02:25:31 +0000576 if (MacroDefinitionRecord *MacroDef =
577 checkForMacroInMacroDefinition(MI, Loc, TU))
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +0000578 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
579 }
580
Guy Benyei11169dd2012-12-18 14:30:41 +0000581 // Nothing to visit at the moment.
582 return false;
583}
584
585bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
586 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
587 if (Visit(TSInfo->getTypeLoc()))
588 return true;
589
590 if (Stmt *Body = B->getBody())
591 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
592
593 return false;
594}
595
Ted Kremenek03325582013-02-21 01:29:01 +0000596Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000597 if (RegionOfInterest.isValid()) {
598 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
599 if (Range.isInvalid())
David Blaikie7a30dc52013-02-21 01:47:18 +0000600 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000601
602 switch (CompareRegionOfInterest(Range)) {
603 case RangeBefore:
604 // This declaration comes before the region of interest; skip it.
David Blaikie7a30dc52013-02-21 01:47:18 +0000605 return None;
Guy Benyei11169dd2012-12-18 14:30:41 +0000606
607 case RangeAfter:
608 // This declaration comes after the region of interest; we're done.
609 return false;
610
611 case RangeOverlap:
612 // This declaration overlaps the region of interest; visit it.
613 break;
614 }
615 }
616 return true;
617}
618
619bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
620 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
621
622 // FIXME: Eventually remove. This part of a hack to support proper
623 // iteration over all Decls contained lexically within an ObjC container.
624 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
625 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
626
627 for ( ; I != E; ++I) {
628 Decl *D = *I;
629 if (D->getLexicalDeclContext() != DC)
630 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000631 const Optional<bool> V = handleDeclForVisitation(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000632 if (!V.hasValue())
633 continue;
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000634 return V.getValue();
Guy Benyei11169dd2012-12-18 14:30:41 +0000635 }
636 return false;
637}
638
Argyrios Kyrtzidise7c91042016-07-01 19:10:54 +0000639Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
640 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
641
642 // Ignore synthesized ivars here, otherwise if we have something like:
643 // @synthesize prop = _prop;
644 // and '_prop' is not declared, we will encounter a '_prop' ivar before
645 // encountering the 'prop' synthesize declaration and we will think that
646 // we passed the region-of-interest.
647 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
648 if (ivarD->getSynthesize())
649 return None;
650 }
651
652 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
653 // declarations is a mismatch with the compiler semantics.
654 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
655 auto *ID = cast<ObjCInterfaceDecl>(D);
656 if (!ID->isThisDeclarationADefinition())
657 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
658
659 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
660 auto *PD = cast<ObjCProtocolDecl>(D);
661 if (!PD->isThisDeclarationADefinition())
662 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
663 }
664
665 const Optional<bool> V = shouldVisitCursor(Cursor);
666 if (!V.hasValue())
667 return None;
668 if (!V.getValue())
669 return false;
670 if (Visit(Cursor, true))
671 return true;
672 return None;
673}
674
Guy Benyei11169dd2012-12-18 14:30:41 +0000675bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
676 llvm_unreachable("Translation units are visited directly by Visit()");
677}
678
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +0000679bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
680 if (VisitTemplateParameters(D->getTemplateParameters()))
681 return true;
682
683 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
684}
685
Guy Benyei11169dd2012-12-18 14:30:41 +0000686bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
687 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
688 return Visit(TSInfo->getTypeLoc());
689
690 return false;
691}
692
693bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
694 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
695 return Visit(TSInfo->getTypeLoc());
696
697 return false;
698}
699
700bool CursorVisitor::VisitTagDecl(TagDecl *D) {
701 return VisitDeclContext(D);
702}
703
704bool CursorVisitor::VisitClassTemplateSpecializationDecl(
705 ClassTemplateSpecializationDecl *D) {
706 bool ShouldVisitBody = false;
707 switch (D->getSpecializationKind()) {
708 case TSK_Undeclared:
709 case TSK_ImplicitInstantiation:
710 // Nothing to visit
711 return false;
712
713 case TSK_ExplicitInstantiationDeclaration:
714 case TSK_ExplicitInstantiationDefinition:
715 break;
716
717 case TSK_ExplicitSpecialization:
718 ShouldVisitBody = true;
719 break;
720 }
721
722 // Visit the template arguments used in the specialization.
723 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
724 TypeLoc TL = SpecType->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +0000725 if (TemplateSpecializationTypeLoc TSTLoc =
726 TL.getAs<TemplateSpecializationTypeLoc>()) {
727 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
728 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000729 return true;
730 }
731 }
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000732
733 return ShouldVisitBody && VisitCXXRecordDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000734}
735
736bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
737 ClassTemplatePartialSpecializationDecl *D) {
738 // FIXME: Visit the "outer" template parameter lists on the TagDecl
739 // before visiting these template parameters.
740 if (VisitTemplateParameters(D->getTemplateParameters()))
741 return true;
742
743 // Visit the partial specialization arguments.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +0000744 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
745 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
746 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
Guy Benyei11169dd2012-12-18 14:30:41 +0000747 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
748 return true;
749
750 return VisitCXXRecordDecl(D);
751}
752
753bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
754 // Visit the default argument.
755 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
756 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
757 if (Visit(DefArg->getTypeLoc()))
758 return true;
759
760 return false;
761}
762
763bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
764 if (Expr *Init = D->getInitExpr())
765 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
766 return false;
767}
768
769bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000770 unsigned NumParamList = DD->getNumTemplateParameterLists();
771 for (unsigned i = 0; i < NumParamList; i++) {
772 TemplateParameterList* Params = DD->getTemplateParameterList(i);
773 if (VisitTemplateParameters(Params))
774 return true;
775 }
776
Guy Benyei11169dd2012-12-18 14:30:41 +0000777 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
778 if (Visit(TSInfo->getTypeLoc()))
779 return true;
780
781 // Visit the nested-name-specifier, if present.
782 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
783 if (VisitNestedNameSpecifierLoc(QualifierLoc))
784 return true;
785
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000786 return false;
787}
788
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000789static bool HasTrailingReturnType(FunctionDecl *ND) {
790 const QualType Ty = ND->getType();
791 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
792 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT))
793 return FT->hasTrailingReturn();
794 }
795
796 return false;
797}
798
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000799/// Compare two base or member initializers based on their source order.
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000800static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
801 CXXCtorInitializer *const *Y) {
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000802 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
803}
804
Guy Benyei11169dd2012-12-18 14:30:41 +0000805bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Argyrios Kyrtzidis2ec76742013-04-05 21:04:10 +0000806 unsigned NumParamList = ND->getNumTemplateParameterLists();
807 for (unsigned i = 0; i < NumParamList; i++) {
808 TemplateParameterList* Params = ND->getTemplateParameterList(i);
809 if (VisitTemplateParameters(Params))
810 return true;
811 }
812
Guy Benyei11169dd2012-12-18 14:30:41 +0000813 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
814 // Visit the function declaration's syntactic components in the order
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000815 // written. This requires a bit of work.
816 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
817 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000818 const bool HasTrailingRT = HasTrailingReturnType(ND);
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000819
820 // If we have a function declared directly (without the use of a typedef),
821 // visit just the return type. Otherwise, just visit the function's type
822 // now.
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000823 if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT &&
824 Visit(FTL.getReturnLoc())) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000825 (!FTL && Visit(TL)))
826 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000827
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000828 // Visit the nested-name-specifier, if present.
829 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
830 if (VisitNestedNameSpecifierLoc(QualifierLoc))
Guy Benyei11169dd2012-12-18 14:30:41 +0000831 return true;
832
833 // Visit the declaration name.
Argyrios Kyrtzidis4a4d2b42014-02-09 08:13:47 +0000834 if (!isa<CXXDestructorDecl>(ND))
835 if (VisitDeclarationNameInfo(ND->getNameInfo()))
836 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000837
838 // FIXME: Visit explicitly-specified template arguments!
839
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000840 // Visit the function parameters, if we have a function type.
841 if (FTL && VisitFunctionTypeLoc(FTL, true))
842 return true;
Ivan Donchevskii1d187132018-01-03 14:35:48 +0000843
844 // Visit the function's trailing return type.
845 if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc()))
846 return true;
847
Ivan Donchevskii1c27b152018-01-03 10:33:21 +0000848 // FIXME: Attributes?
849 }
850
Guy Benyei11169dd2012-12-18 14:30:41 +0000851 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
852 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
853 // Find the initializers that were written in the source.
854 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
Aaron Ballman0ad78302014-03-13 17:34:31 +0000855 for (auto *I : Constructor->inits()) {
856 if (!I->isWritten())
Guy Benyei11169dd2012-12-18 14:30:41 +0000857 continue;
858
Aaron Ballman0ad78302014-03-13 17:34:31 +0000859 WrittenInits.push_back(I);
Guy Benyei11169dd2012-12-18 14:30:41 +0000860 }
861
862 // Sort the initializers in source order
Benjamin Kramer4cadf292014-03-07 21:51:58 +0000863 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
864 &CompareCXXCtorInitializers);
865
Guy Benyei11169dd2012-12-18 14:30:41 +0000866 // Visit the initializers in source order
867 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
868 CXXCtorInitializer *Init = WrittenInits[I];
869 if (Init->isAnyMemberInitializer()) {
870 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
871 Init->getMemberLocation(), TU)))
872 return true;
873 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
874 if (Visit(TInfo->getTypeLoc()))
875 return true;
876 }
877
878 // Visit the initializer value.
879 if (Expr *Initializer = Init->getInit())
880 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
881 return true;
882 }
883 }
884
885 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
886 return true;
887 }
888
889 return false;
890}
891
892bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
893 if (VisitDeclaratorDecl(D))
894 return true;
895
896 if (Expr *BitWidth = D->getBitWidth())
897 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
898
Benjamin Kramer99f97592017-11-15 12:20:41 +0000899 if (Expr *Init = D->getInClassInitializer())
900 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
901
Guy Benyei11169dd2012-12-18 14:30:41 +0000902 return false;
903}
904
905bool CursorVisitor::VisitVarDecl(VarDecl *D) {
906 if (VisitDeclaratorDecl(D))
907 return true;
908
909 if (Expr *Init = D->getInit())
910 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
911
912 return false;
913}
914
915bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
916 if (VisitDeclaratorDecl(D))
917 return true;
918
919 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
920 if (Expr *DefArg = D->getDefaultArgument())
921 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
922
923 return false;
924}
925
926bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
927 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
928 // before visiting these template parameters.
929 if (VisitTemplateParameters(D->getTemplateParameters()))
930 return true;
931
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000932 auto* FD = D->getTemplatedDecl();
933 return VisitAttributes(FD) || VisitFunctionDecl(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000934}
935
936bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
937 // FIXME: Visit the "outer" template parameter lists on the TagDecl
938 // before visiting these template parameters.
939 if (VisitTemplateParameters(D->getTemplateParameters()))
940 return true;
941
Jonathan Coe578ac7a2017-10-16 23:43:02 +0000942 auto* CD = D->getTemplatedDecl();
943 return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000944}
945
946bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
947 if (VisitTemplateParameters(D->getTemplateParameters()))
948 return true;
949
950 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
951 VisitTemplateArgumentLoc(D->getDefaultArgument()))
952 return true;
953
954 return false;
955}
956
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000957bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
958 // Visit the bound, if it's explicit.
959 if (D->hasExplicitBound()) {
960 if (auto TInfo = D->getTypeSourceInfo()) {
961 if (Visit(TInfo->getTypeLoc()))
962 return true;
963 }
964 }
965
966 return false;
967}
968
Guy Benyei11169dd2012-12-18 14:30:41 +0000969bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Alp Toker314cc812014-01-25 16:55:45 +0000970 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +0000971 if (Visit(TSInfo->getTypeLoc()))
972 return true;
973
David Majnemer59f77922016-06-24 04:05:48 +0000974 for (const auto *P : ND->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000975 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000976 return true;
977 }
978
Alexander Kornienko1a9f1842015-12-28 15:24:08 +0000979 return ND->isThisDeclarationADefinition() &&
980 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
Guy Benyei11169dd2012-12-18 14:30:41 +0000981}
982
983template <typename DeclIt>
984static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
985 SourceManager &SM, SourceLocation EndLoc,
986 SmallVectorImpl<Decl *> &Decls) {
987 DeclIt next = *DI_current;
988 while (++next != DE_current) {
989 Decl *D_next = *next;
990 if (!D_next)
991 break;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000992 SourceLocation L = D_next->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +0000993 if (!L.isValid())
994 break;
995 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
996 *DI_current = next;
997 Decls.push_back(D_next);
998 continue;
999 }
1000 break;
1001 }
1002}
1003
Guy Benyei11169dd2012-12-18 14:30:41 +00001004bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
1005 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
1006 // an @implementation can lexically contain Decls that are not properly
1007 // nested in the AST. When we identify such cases, we need to retrofit
1008 // this nesting here.
1009 if (!DI_current && !FileDI_current)
1010 return VisitDeclContext(D);
1011
1012 // Scan the Decls that immediately come after the container
1013 // in the current DeclContext. If any fall within the
1014 // container's lexical region, stash them into a vector
1015 // for later processing.
1016 SmallVector<Decl *, 24> DeclsInContainer;
1017 SourceLocation EndLoc = D->getSourceRange().getEnd();
1018 SourceManager &SM = AU->getSourceManager();
1019 if (EndLoc.isValid()) {
1020 if (DI_current) {
1021 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
1022 DeclsInContainer);
1023 } else {
1024 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1025 DeclsInContainer);
1026 }
1027 }
1028
1029 // The common case.
1030 if (DeclsInContainer.empty())
1031 return VisitDeclContext(D);
1032
1033 // Get all the Decls in the DeclContext, and sort them with the
1034 // additional ones we've collected. Then visit them.
Aaron Ballman629afae2014-03-07 19:56:05 +00001035 for (auto *SubDecl : D->decls()) {
1036 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001037 SubDecl->getBeginLoc().isInvalid())
Guy Benyei11169dd2012-12-18 14:30:41 +00001038 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00001039 DeclsInContainer.push_back(SubDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001040 }
1041
1042 // Now sort the Decls so that they appear in lexical order.
Fangrui Song55fab262018-09-26 22:16:28 +00001043 llvm::sort(DeclsInContainer,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001044 [&SM](Decl *A, Decl *B) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001045 SourceLocation L_A = A->getBeginLoc();
1046 SourceLocation L_B = B->getBeginLoc();
1047 return L_A != L_B ? SM.isBeforeInTranslationUnit(L_A, L_B)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001048 : SM.isBeforeInTranslationUnit(A->getEndLoc(),
1049 B->getEndLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001050 });
Guy Benyei11169dd2012-12-18 14:30:41 +00001051
1052 // Now visit the decls.
1053 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1054 E = DeclsInContainer.end(); I != E; ++I) {
1055 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
Ted Kremenek03325582013-02-21 01:29:01 +00001056 const Optional<bool> &V = shouldVisitCursor(Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00001057 if (!V.hasValue())
1058 continue;
1059 if (!V.getValue())
1060 return false;
1061 if (Visit(Cursor, true))
1062 return true;
1063 }
1064 return false;
1065}
1066
1067bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1068 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1069 TU)))
1070 return true;
1071
Douglas Gregore9d95f12015-07-07 03:57:35 +00001072 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1073 return true;
1074
Guy Benyei11169dd2012-12-18 14:30:41 +00001075 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1076 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1077 E = ND->protocol_end(); I != E; ++I, ++PL)
1078 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1079 return true;
1080
1081 return VisitObjCContainerDecl(ND);
1082}
1083
1084bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1085 if (!PID->isThisDeclarationADefinition())
1086 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1087
1088 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1089 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1090 E = PID->protocol_end(); I != E; ++I, ++PL)
1091 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1092 return true;
1093
1094 return VisitObjCContainerDecl(PID);
1095}
1096
1097bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1098 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1099 return true;
1100
1101 // FIXME: This implements a workaround with @property declarations also being
1102 // installed in the DeclContext for the @interface. Eventually this code
1103 // should be removed.
1104 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1105 if (!CDecl || !CDecl->IsClassExtension())
1106 return false;
1107
1108 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1109 if (!ID)
1110 return false;
1111
1112 IdentifierInfo *PropertyId = PD->getIdentifier();
1113 ObjCPropertyDecl *prevDecl =
Manman Ren5b786402016-01-28 18:49:28 +00001114 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1115 PD->getQueryKind());
Guy Benyei11169dd2012-12-18 14:30:41 +00001116
1117 if (!prevDecl)
1118 return false;
1119
1120 // Visit synthesized methods since they will be skipped when visiting
1121 // the @interface.
1122 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1123 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1124 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1125 return true;
1126
1127 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1128 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1129 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1130 return true;
1131
1132 return false;
1133}
1134
Douglas Gregore9d95f12015-07-07 03:57:35 +00001135bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1136 if (!typeParamList)
1137 return false;
1138
1139 for (auto *typeParam : *typeParamList) {
1140 // Visit the type parameter.
1141 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1142 return true;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001143 }
1144
1145 return false;
1146}
1147
Guy Benyei11169dd2012-12-18 14:30:41 +00001148bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1149 if (!D->isThisDeclarationADefinition()) {
1150 // Forward declaration is treated like a reference.
1151 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1152 }
1153
Douglas Gregore9d95f12015-07-07 03:57:35 +00001154 // Objective-C type parameters.
1155 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1156 return true;
1157
Guy Benyei11169dd2012-12-18 14:30:41 +00001158 // Issue callbacks for super class.
1159 if (D->getSuperClass() &&
1160 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1161 D->getSuperClassLoc(),
1162 TU)))
1163 return true;
1164
Douglas Gregore9d95f12015-07-07 03:57:35 +00001165 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1166 if (Visit(SuperClassTInfo->getTypeLoc()))
1167 return true;
1168
Guy Benyei11169dd2012-12-18 14:30:41 +00001169 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1170 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1171 E = D->protocol_end(); I != E; ++I, ++PL)
1172 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1173 return true;
1174
1175 return VisitObjCContainerDecl(D);
1176}
1177
1178bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1179 return VisitObjCContainerDecl(D);
1180}
1181
1182bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1183 // 'ID' could be null when dealing with invalid code.
1184 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1185 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1186 return true;
1187
1188 return VisitObjCImplDecl(D);
1189}
1190
1191bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1192#if 0
1193 // Issue callbacks for super class.
1194 // FIXME: No source location information!
1195 if (D->getSuperClass() &&
1196 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1197 D->getSuperClassLoc(),
1198 TU)))
1199 return true;
1200#endif
1201
1202 return VisitObjCImplDecl(D);
1203}
1204
1205bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1206 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1207 if (PD->isIvarNameSpecified())
1208 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1209
1210 return false;
1211}
1212
1213bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1214 return VisitDeclContext(D);
1215}
1216
1217bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1218 // Visit nested-name-specifier.
1219 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1220 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1221 return true;
1222
1223 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1224 D->getTargetNameLoc(), TU));
1225}
1226
1227bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1228 // Visit nested-name-specifier.
1229 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1230 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1231 return true;
1232 }
1233
1234 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1235 return true;
1236
1237 return VisitDeclarationNameInfo(D->getNameInfo());
1238}
1239
1240bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1241 // Visit nested-name-specifier.
1242 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1243 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1244 return true;
1245
1246 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1247 D->getIdentLocation(), TU));
1248}
1249
1250bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1251 // Visit nested-name-specifier.
1252 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1253 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1254 return true;
1255 }
1256
1257 return VisitDeclarationNameInfo(D->getNameInfo());
1258}
1259
1260bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1261 UnresolvedUsingTypenameDecl *D) {
1262 // Visit nested-name-specifier.
1263 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1264 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1265 return true;
1266
1267 return false;
1268}
1269
Olivier Goffart81978012016-06-09 16:15:55 +00001270bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1271 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1272 return true;
Richard Trieuf3b77662016-09-13 01:37:01 +00001273 if (StringLiteral *Message = D->getMessage())
1274 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1275 return true;
Olivier Goffart81978012016-06-09 16:15:55 +00001276 return false;
1277}
1278
Olivier Goffartd211c642016-11-04 06:29:27 +00001279bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1280 if (NamedDecl *FriendD = D->getFriendDecl()) {
1281 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1282 return true;
1283 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1284 if (Visit(TI->getTypeLoc()))
1285 return true;
1286 }
1287 return false;
1288}
1289
Guy Benyei11169dd2012-12-18 14:30:41 +00001290bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1291 switch (Name.getName().getNameKind()) {
1292 case clang::DeclarationName::Identifier:
1293 case clang::DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001294 case clang::DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001295 case clang::DeclarationName::CXXOperatorName:
1296 case clang::DeclarationName::CXXUsingDirective:
1297 return false;
Richard Smith35845152017-02-07 01:37:30 +00001298
Guy Benyei11169dd2012-12-18 14:30:41 +00001299 case clang::DeclarationName::CXXConstructorName:
1300 case clang::DeclarationName::CXXDestructorName:
1301 case clang::DeclarationName::CXXConversionFunctionName:
1302 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1303 return Visit(TSInfo->getTypeLoc());
1304 return false;
1305
1306 case clang::DeclarationName::ObjCZeroArgSelector:
1307 case clang::DeclarationName::ObjCOneArgSelector:
1308 case clang::DeclarationName::ObjCMultiArgSelector:
1309 // FIXME: Per-identifier location info?
1310 return false;
1311 }
1312
1313 llvm_unreachable("Invalid DeclarationName::Kind!");
1314}
1315
1316bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1317 SourceRange Range) {
1318 // FIXME: This whole routine is a hack to work around the lack of proper
1319 // source information in nested-name-specifiers (PR5791). Since we do have
1320 // a beginning source location, we can visit the first component of the
1321 // nested-name-specifier, if it's a single-token component.
1322 if (!NNS)
1323 return false;
1324
1325 // Get the first component in the nested-name-specifier.
1326 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1327 NNS = Prefix;
1328
1329 switch (NNS->getKind()) {
1330 case NestedNameSpecifier::Namespace:
1331 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1332 TU));
1333
1334 case NestedNameSpecifier::NamespaceAlias:
1335 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1336 Range.getBegin(), TU));
1337
1338 case NestedNameSpecifier::TypeSpec: {
1339 // If the type has a form where we know that the beginning of the source
1340 // range matches up with a reference cursor. Visit the appropriate reference
1341 // cursor.
1342 const Type *T = NNS->getAsType();
1343 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1344 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1345 if (const TagType *Tag = dyn_cast<TagType>(T))
1346 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1347 if (const TemplateSpecializationType *TST
1348 = dyn_cast<TemplateSpecializationType>(T))
1349 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1350 break;
1351 }
1352
1353 case NestedNameSpecifier::TypeSpecWithTemplate:
1354 case NestedNameSpecifier::Global:
1355 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001356 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001357 break;
1358 }
1359
1360 return false;
1361}
1362
1363bool
1364CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1365 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1366 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1367 Qualifiers.push_back(Qualifier);
1368
1369 while (!Qualifiers.empty()) {
1370 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1371 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1372 switch (NNS->getKind()) {
1373 case NestedNameSpecifier::Namespace:
1374 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1375 Q.getLocalBeginLoc(),
1376 TU)))
1377 return true;
1378
1379 break;
1380
1381 case NestedNameSpecifier::NamespaceAlias:
1382 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1383 Q.getLocalBeginLoc(),
1384 TU)))
1385 return true;
1386
1387 break;
1388
1389 case NestedNameSpecifier::TypeSpec:
1390 case NestedNameSpecifier::TypeSpecWithTemplate:
1391 if (Visit(Q.getTypeLoc()))
1392 return true;
1393
1394 break;
1395
1396 case NestedNameSpecifier::Global:
1397 case NestedNameSpecifier::Identifier:
Nikola Smiljanic67860242014-09-26 00:28:20 +00001398 case NestedNameSpecifier::Super:
Guy Benyei11169dd2012-12-18 14:30:41 +00001399 break;
1400 }
1401 }
1402
1403 return false;
1404}
1405
1406bool CursorVisitor::VisitTemplateParameters(
1407 const TemplateParameterList *Params) {
1408 if (!Params)
1409 return false;
1410
1411 for (TemplateParameterList::const_iterator P = Params->begin(),
1412 PEnd = Params->end();
1413 P != PEnd; ++P) {
1414 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1415 return true;
1416 }
1417
1418 return false;
1419}
1420
1421bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1422 switch (Name.getKind()) {
1423 case TemplateName::Template:
1424 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1425
1426 case TemplateName::OverloadedTemplate:
1427 // Visit the overloaded template set.
1428 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1429 return true;
1430
1431 return false;
1432
Richard Smithb23c5e82019-05-09 03:31:27 +00001433 case TemplateName::AssumedTemplate:
1434 // FIXME: Visit DeclarationName?
1435 return false;
1436
Guy Benyei11169dd2012-12-18 14:30:41 +00001437 case TemplateName::DependentTemplate:
1438 // FIXME: Visit nested-name-specifier.
1439 return false;
1440
1441 case TemplateName::QualifiedTemplate:
1442 // FIXME: Visit nested-name-specifier.
1443 return Visit(MakeCursorTemplateRef(
1444 Name.getAsQualifiedTemplateName()->getDecl(),
1445 Loc, TU));
1446
1447 case TemplateName::SubstTemplateTemplateParm:
1448 return Visit(MakeCursorTemplateRef(
1449 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1450 Loc, TU));
1451
1452 case TemplateName::SubstTemplateTemplateParmPack:
1453 return Visit(MakeCursorTemplateRef(
1454 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1455 Loc, TU));
1456 }
1457
1458 llvm_unreachable("Invalid TemplateName::Kind!");
1459}
1460
1461bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1462 switch (TAL.getArgument().getKind()) {
1463 case TemplateArgument::Null:
1464 case TemplateArgument::Integral:
1465 case TemplateArgument::Pack:
1466 return false;
1467
1468 case TemplateArgument::Type:
1469 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1470 return Visit(TSInfo->getTypeLoc());
1471 return false;
1472
1473 case TemplateArgument::Declaration:
1474 if (Expr *E = TAL.getSourceDeclExpression())
1475 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1476 return false;
1477
1478 case TemplateArgument::NullPtr:
1479 if (Expr *E = TAL.getSourceNullPtrExpression())
1480 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1481 return false;
1482
1483 case TemplateArgument::Expression:
1484 if (Expr *E = TAL.getSourceExpression())
1485 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1486 return false;
1487
1488 case TemplateArgument::Template:
1489 case TemplateArgument::TemplateExpansion:
1490 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1491 return true;
1492
1493 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1494 TAL.getTemplateNameLoc());
1495 }
1496
1497 llvm_unreachable("Invalid TemplateArgument::Kind!");
1498}
1499
1500bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1501 return VisitDeclContext(D);
1502}
1503
1504bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1505 return Visit(TL.getUnqualifiedLoc());
1506}
1507
1508bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1509 ASTContext &Context = AU->getASTContext();
1510
1511 // Some builtin types (such as Objective-C's "id", "sel", and
1512 // "Class") have associated declarations. Create cursors for those.
1513 QualType VisitType;
1514 switch (TL.getTypePtr()->getKind()) {
1515
1516 case BuiltinType::Void:
1517 case BuiltinType::NullPtr:
1518 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001519#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1520 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001521#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001522#define EXT_OPAQUE_TYPE(ExtTYpe, Id, Ext) \
1523 case BuiltinType::Id:
1524#include "clang/Basic/OpenCLExtensionTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001525 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001526 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001527 case BuiltinType::OCLClkEvent:
1528 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001529 case BuiltinType::OCLReserveID:
Guy Benyei11169dd2012-12-18 14:30:41 +00001530#define BUILTIN_TYPE(Id, SingletonId)
1531#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1532#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1533#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1534#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1535#include "clang/AST/BuiltinTypes.def"
1536 break;
1537
1538 case BuiltinType::ObjCId:
1539 VisitType = Context.getObjCIdType();
1540 break;
1541
1542 case BuiltinType::ObjCClass:
1543 VisitType = Context.getObjCClassType();
1544 break;
1545
1546 case BuiltinType::ObjCSel:
1547 VisitType = Context.getObjCSelType();
1548 break;
1549 }
1550
1551 if (!VisitType.isNull()) {
1552 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1553 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1554 TU));
1555 }
1556
1557 return false;
1558}
1559
1560bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1561 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1562}
1563
1564bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1565 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1566}
1567
1568bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1569 if (TL.isDefinition())
1570 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1571
1572 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1573}
1574
1575bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1576 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1577}
1578
1579bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001580 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001581}
1582
Manman Rene6be26c2016-09-13 17:25:08 +00001583bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001584 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getBeginLoc(), TU)))
Manman Rene6be26c2016-09-13 17:25:08 +00001585 return true;
1586 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1587 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1588 TU)))
1589 return true;
1590 }
1591
1592 return false;
1593}
1594
Guy Benyei11169dd2012-12-18 14:30:41 +00001595bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1596 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1597 return true;
1598
Douglas Gregore9d95f12015-07-07 03:57:35 +00001599 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1600 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1601 return true;
1602 }
1603
Guy Benyei11169dd2012-12-18 14:30:41 +00001604 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1605 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1606 TU)))
1607 return true;
1608 }
1609
1610 return false;
1611}
1612
1613bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1614 return Visit(TL.getPointeeLoc());
1615}
1616
1617bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1618 return Visit(TL.getInnerLoc());
1619}
1620
Leonard Chanc72aaf62019-05-07 03:20:17 +00001621bool CursorVisitor::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
1622 return Visit(TL.getInnerLoc());
1623}
1624
Guy Benyei11169dd2012-12-18 14:30:41 +00001625bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1626 return Visit(TL.getPointeeLoc());
1627}
1628
1629bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1630 return Visit(TL.getPointeeLoc());
1631}
1632
1633bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1634 return Visit(TL.getPointeeLoc());
1635}
1636
1637bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1638 return Visit(TL.getPointeeLoc());
1639}
1640
1641bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1642 return Visit(TL.getPointeeLoc());
1643}
1644
1645bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1646 return Visit(TL.getModifiedLoc());
1647}
1648
1649bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1650 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001651 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001652 return true;
1653
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001654 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1655 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001656 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1657 return true;
1658
1659 return false;
1660}
1661
1662bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1663 if (Visit(TL.getElementLoc()))
1664 return true;
1665
1666 if (Expr *Size = TL.getSizeExpr())
1667 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1668
1669 return false;
1670}
1671
Reid Kleckner8a365022013-06-24 17:51:48 +00001672bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1673 return Visit(TL.getOriginalLoc());
1674}
1675
Reid Kleckner0503a872013-12-05 01:23:43 +00001676bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1677 return Visit(TL.getOriginalLoc());
1678}
1679
Richard Smith600b5262017-01-26 20:40:47 +00001680bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1681 DeducedTemplateSpecializationTypeLoc TL) {
1682 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1683 TL.getTemplateNameLoc()))
1684 return true;
1685
1686 return false;
1687}
1688
Guy Benyei11169dd2012-12-18 14:30:41 +00001689bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1690 TemplateSpecializationTypeLoc TL) {
1691 // Visit the template name.
1692 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1693 TL.getTemplateNameLoc()))
1694 return true;
1695
1696 // Visit the template arguments.
1697 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1698 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1699 return true;
1700
1701 return false;
1702}
1703
1704bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1705 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1706}
1707
1708bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1709 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1710 return Visit(TSInfo->getTypeLoc());
1711
1712 return false;
1713}
1714
1715bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1716 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1717 return Visit(TSInfo->getTypeLoc());
1718
1719 return false;
1720}
1721
1722bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001723 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001724}
1725
1726bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1727 DependentTemplateSpecializationTypeLoc TL) {
1728 // Visit the nested-name-specifier, if there is one.
1729 if (TL.getQualifierLoc() &&
1730 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1731 return true;
1732
1733 // Visit the template arguments.
1734 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1735 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1736 return true;
1737
1738 return false;
1739}
1740
1741bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1742 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1743 return true;
1744
1745 return Visit(TL.getNamedTypeLoc());
1746}
1747
1748bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1749 return Visit(TL.getPatternLoc());
1750}
1751
1752bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1753 if (Expr *E = TL.getUnderlyingExpr())
1754 return Visit(MakeCXCursor(E, StmtParent, TU));
1755
1756 return false;
1757}
1758
1759bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1760 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1761}
1762
1763bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1764 return Visit(TL.getValueLoc());
1765}
1766
Xiuli Pan9c14e282016-01-09 12:53:17 +00001767bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1768 return Visit(TL.getValueLoc());
1769}
1770
Guy Benyei11169dd2012-12-18 14:30:41 +00001771#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1772bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1773 return Visit##PARENT##Loc(TL); \
1774}
1775
1776DEFAULT_TYPELOC_IMPL(Complex, Type)
1777DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1778DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1779DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1780DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001781DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
Erich Keanef702b022018-07-13 19:46:04 +00001782DEFAULT_TYPELOC_IMPL(DependentVector, Type)
Guy Benyei11169dd2012-12-18 14:30:41 +00001783DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1784DEFAULT_TYPELOC_IMPL(Vector, Type)
1785DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1786DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1787DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1788DEFAULT_TYPELOC_IMPL(Record, TagType)
1789DEFAULT_TYPELOC_IMPL(Enum, TagType)
1790DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1791DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1792DEFAULT_TYPELOC_IMPL(Auto, Type)
1793
1794bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1795 // Visit the nested-name-specifier, if present.
1796 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1797 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1798 return true;
1799
1800 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001801 for (const auto &I : D->bases()) {
1802 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001803 return true;
1804 }
1805 }
1806
1807 return VisitTagDecl(D);
1808}
1809
1810bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001811 for (const auto *I : D->attrs())
Michael Wu40ff1052018-08-03 05:20:23 +00001812 if ((TU->ParsingOptions & CXTranslationUnit_VisitImplicitAttributes ||
1813 !I->isImplicit()) &&
1814 Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001815 return true;
1816
1817 return false;
1818}
1819
1820//===----------------------------------------------------------------------===//
1821// Data-recursive visitor methods.
1822//===----------------------------------------------------------------------===//
1823
1824namespace {
1825#define DEF_JOB(NAME, DATA, KIND)\
1826class NAME : public VisitorJob {\
1827public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001828 NAME(const DATA *d, CXCursor parent) : \
1829 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001830 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001831 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001832};
1833
1834DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1835DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1836DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1837DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001838DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1839DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1840DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1841#undef DEF_JOB
1842
James Y Knight04ec5bf2015-12-24 02:59:37 +00001843class ExplicitTemplateArgsVisit : public VisitorJob {
1844public:
1845 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1846 const TemplateArgumentLoc *End, CXCursor parent)
1847 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1848 End) {}
1849 static bool classof(const VisitorJob *VJ) {
1850 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1851 }
1852 const TemplateArgumentLoc *begin() const {
1853 return static_cast<const TemplateArgumentLoc *>(data[0]);
1854 }
1855 const TemplateArgumentLoc *end() {
1856 return static_cast<const TemplateArgumentLoc *>(data[1]);
1857 }
1858};
Guy Benyei11169dd2012-12-18 14:30:41 +00001859class DeclVisit : public VisitorJob {
1860public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001861 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001862 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001863 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001864 static bool classof(const VisitorJob *VJ) {
1865 return VJ->getKind() == DeclVisitKind;
1866 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001867 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001868 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001869};
1870class TypeLocVisit : public VisitorJob {
1871public:
1872 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1873 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1874 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1875
1876 static bool classof(const VisitorJob *VJ) {
1877 return VJ->getKind() == TypeLocVisitKind;
1878 }
1879
1880 TypeLoc get() const {
1881 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001882 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001883 }
1884};
1885
1886class LabelRefVisit : public VisitorJob {
1887public:
1888 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1889 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1890 labelLoc.getPtrEncoding()) {}
1891
1892 static bool classof(const VisitorJob *VJ) {
1893 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1894 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001895 const LabelDecl *get() const {
1896 return static_cast<const LabelDecl *>(data[0]);
1897 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001898 SourceLocation getLoc() const {
1899 return SourceLocation::getFromPtrEncoding(data[1]); }
1900};
1901
1902class NestedNameSpecifierLocVisit : public VisitorJob {
1903public:
1904 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1905 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1906 Qualifier.getNestedNameSpecifier(),
1907 Qualifier.getOpaqueData()) { }
1908
1909 static bool classof(const VisitorJob *VJ) {
1910 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1911 }
1912
1913 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001914 return NestedNameSpecifierLoc(
1915 const_cast<NestedNameSpecifier *>(
1916 static_cast<const NestedNameSpecifier *>(data[0])),
1917 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001918 }
1919};
1920
1921class DeclarationNameInfoVisit : public VisitorJob {
1922public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001923 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001924 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001925 static bool classof(const VisitorJob *VJ) {
1926 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1927 }
1928 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001929 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001930 switch (S->getStmtClass()) {
1931 default:
1932 llvm_unreachable("Unhandled Stmt");
1933 case clang::Stmt::MSDependentExistsStmtClass:
1934 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1935 case Stmt::CXXDependentScopeMemberExprClass:
1936 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1937 case Stmt::DependentScopeDeclRefExprClass:
1938 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001939 case Stmt::OMPCriticalDirectiveClass:
1940 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001941 }
1942 }
1943};
1944class MemberRefVisit : public VisitorJob {
1945public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001946 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001947 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1948 L.getPtrEncoding()) {}
1949 static bool classof(const VisitorJob *VJ) {
1950 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1951 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001952 const FieldDecl *get() const {
1953 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001954 }
1955 SourceLocation getLoc() const {
1956 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1957 }
1958};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001959class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001960 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001961 VisitorWorkList &WL;
1962 CXCursor Parent;
1963public:
1964 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1965 : WL(wl), Parent(parent) {}
1966
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001967 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1968 void VisitBlockExpr(const BlockExpr *B);
1969 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1970 void VisitCompoundStmt(const CompoundStmt *S);
1971 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1972 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1973 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1974 void VisitCXXNewExpr(const CXXNewExpr *E);
1975 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1976 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1977 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1978 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1979 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1980 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1981 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1982 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001983 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001984 void VisitDeclRefExpr(const DeclRefExpr *D);
1985 void VisitDeclStmt(const DeclStmt *S);
1986 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1987 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1988 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1989 void VisitForStmt(const ForStmt *FS);
1990 void VisitGotoStmt(const GotoStmt *GS);
1991 void VisitIfStmt(const IfStmt *If);
1992 void VisitInitListExpr(const InitListExpr *IE);
1993 void VisitMemberExpr(const MemberExpr *M);
1994 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1995 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1996 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1997 void VisitOverloadExpr(const OverloadExpr *E);
1998 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1999 void VisitStmt(const Stmt *S);
2000 void VisitSwitchStmt(const SwitchStmt *S);
2001 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002002 void VisitTypeTraitExpr(const TypeTraitExpr *E);
2003 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
2004 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
2005 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
2006 void VisitVAArgExpr(const VAArgExpr *E);
2007 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
2008 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
2009 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
2010 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002011 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00002012 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002013 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002014 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002015 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002016 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002017 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002018 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002019 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00002020 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002021 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002022 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002023 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002024 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002025 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00002026 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002027 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00002028 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002029 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002030 void
2031 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00002032 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00002033 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002034 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00002035 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002036 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00002037 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00002038 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00002039 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002040 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002041 void
2042 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002043 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002044 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002045 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002046 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002047 void VisitOMPDistributeParallelForDirective(
2048 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00002049 void VisitOMPDistributeParallelForSimdDirective(
2050 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002051 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002052 void VisitOMPTargetParallelForSimdDirective(
2053 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002054 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002055 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002056 void VisitOMPTeamsDistributeSimdDirective(
2057 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002058 void VisitOMPTeamsDistributeParallelForSimdDirective(
2059 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002060 void VisitOMPTeamsDistributeParallelForDirective(
2061 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002062 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002063 void VisitOMPTargetTeamsDistributeDirective(
2064 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002065 void VisitOMPTargetTeamsDistributeParallelForDirective(
2066 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002067 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2068 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002069 void VisitOMPTargetTeamsDistributeSimdDirective(
2070 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002071
Guy Benyei11169dd2012-12-18 14:30:41 +00002072private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002073 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002074 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002075 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2076 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002077 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2078 void AddStmt(const Stmt *S);
2079 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002080 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002081 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002082 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002083};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002084} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002085
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002086void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002087 // 'S' should always be non-null, since it comes from the
2088 // statement we are visiting.
2089 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2090}
2091
2092void
2093EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2094 if (Qualifier)
2095 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2096}
2097
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002098void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002099 if (S)
2100 WL.push_back(StmtVisit(S, Parent));
2101}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002102void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002103 if (D)
2104 WL.push_back(DeclVisit(D, Parent, isFirst));
2105}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002106void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2107 unsigned NumTemplateArgs) {
2108 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002109}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002110void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002111 if (D)
2112 WL.push_back(MemberRefVisit(D, L, Parent));
2113}
2114void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2115 if (TI)
2116 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2117 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002118void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002119 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002120 for (const Stmt *SubStmt : S->children()) {
2121 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002122 }
2123 if (size == WL.size())
2124 return;
2125 // Now reverse the entries we just added. This will match the DFS
2126 // ordering performed by the worklist.
2127 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2128 std::reverse(I, E);
2129}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002130namespace {
2131class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2132 EnqueueVisitor *Visitor;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002133 /// Process clauses with list of variables.
Alexey Bataev756c1962013-09-24 03:17:45 +00002134 template <typename T>
2135 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002136public:
2137 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2138#define OPENMP_CLAUSE(Name, Class) \
2139 void Visit##Class(const Class *C);
2140#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002141 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002142 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002143};
2144
Alexey Bataev3392d762016-02-16 11:18:12 +00002145void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2146 const OMPClauseWithPreInit *C) {
2147 Visitor->AddStmt(C->getPreInitStmt());
2148}
2149
Alexey Bataev005248a2016-02-25 05:25:57 +00002150void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2151 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002152 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002153 Visitor->AddStmt(C->getPostUpdateExpr());
2154}
2155
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002156void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002157 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002158 Visitor->AddStmt(C->getCondition());
2159}
2160
Alexey Bataev3778b602014-07-17 07:32:53 +00002161void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2162 Visitor->AddStmt(C->getCondition());
2163}
2164
Alexey Bataev568a8332014-03-06 06:15:19 +00002165void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002166 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002167 Visitor->AddStmt(C->getNumThreads());
2168}
2169
Alexey Bataev62c87d22014-03-21 04:51:18 +00002170void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2171 Visitor->AddStmt(C->getSafelen());
2172}
2173
Alexey Bataev66b15b52015-08-21 11:14:16 +00002174void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2175 Visitor->AddStmt(C->getSimdlen());
2176}
2177
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002178void OMPClauseEnqueue::VisitOMPAllocatorClause(const OMPAllocatorClause *C) {
2179 Visitor->AddStmt(C->getAllocator());
2180}
2181
Alexander Musman8bd31e62014-05-27 15:12:19 +00002182void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2183 Visitor->AddStmt(C->getNumForLoops());
2184}
2185
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002186void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002187
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002188void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2189
Alexey Bataev56dafe82014-06-20 07:16:17 +00002190void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002191 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002192 Visitor->AddStmt(C->getChunkSize());
2193}
2194
Alexey Bataev10e775f2015-07-30 11:36:16 +00002195void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2196 Visitor->AddStmt(C->getNumForLoops());
2197}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002198
Alexey Bataev236070f2014-06-20 11:19:47 +00002199void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2200
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002201void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2202
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002203void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2204
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002205void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2206
Alexey Bataevdea47612014-07-23 07:46:59 +00002207void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2208
Alexey Bataev67a4f222014-07-23 10:25:33 +00002209void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2210
Alexey Bataev459dec02014-07-24 06:46:57 +00002211void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2212
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002213void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2214
Alexey Bataev346265e2015-09-25 10:37:12 +00002215void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2216
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002217void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2218
Alexey Bataevb825de12015-12-07 10:51:44 +00002219void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2220
Kelvin Li1408f912018-09-26 04:28:39 +00002221void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2222 const OMPUnifiedAddressClause *) {}
2223
Patrick Lyster4a370b92018-10-01 13:47:43 +00002224void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2225 const OMPUnifiedSharedMemoryClause *) {}
2226
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00002227void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2228 const OMPReverseOffloadClause *) {}
2229
Patrick Lyster3fe9e392018-10-11 14:41:10 +00002230void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2231 const OMPDynamicAllocatorsClause *) {}
2232
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00002233void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2234 const OMPAtomicDefaultMemOrderClause *) {}
2235
Michael Wonge710d542015-08-07 16:16:36 +00002236void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2237 Visitor->AddStmt(C->getDevice());
2238}
2239
Kelvin Li099bb8c2015-11-24 20:50:12 +00002240void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002241 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002242 Visitor->AddStmt(C->getNumTeams());
2243}
2244
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002245void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002246 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002247 Visitor->AddStmt(C->getThreadLimit());
2248}
2249
Alexey Bataeva0569352015-12-01 10:17:31 +00002250void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2251 Visitor->AddStmt(C->getPriority());
2252}
2253
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002254void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2255 Visitor->AddStmt(C->getGrainsize());
2256}
2257
Alexey Bataev382967a2015-12-08 12:06:20 +00002258void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2259 Visitor->AddStmt(C->getNumTasks());
2260}
2261
Alexey Bataev28c75412015-12-15 08:19:24 +00002262void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2263 Visitor->AddStmt(C->getHint());
2264}
2265
Alexey Bataev756c1962013-09-24 03:17:45 +00002266template<typename T>
2267void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002268 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002269 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002270 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002271}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002272
Alexey Bataeve04483e2019-03-27 14:14:31 +00002273void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) {
2274 VisitOMPClauseList(C);
2275 Visitor->AddStmt(C->getAllocator());
2276}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002277void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002278 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002279 for (const auto *E : C->private_copies()) {
2280 Visitor->AddStmt(E);
2281 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002282}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002283void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2284 const OMPFirstprivateClause *C) {
2285 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002286 VisitOMPClauseWithPreInit(C);
2287 for (const auto *E : C->private_copies()) {
2288 Visitor->AddStmt(E);
2289 }
2290 for (const auto *E : C->inits()) {
2291 Visitor->AddStmt(E);
2292 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002293}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002294void OMPClauseEnqueue::VisitOMPLastprivateClause(
2295 const OMPLastprivateClause *C) {
2296 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002297 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002298 for (auto *E : C->private_copies()) {
2299 Visitor->AddStmt(E);
2300 }
2301 for (auto *E : C->source_exprs()) {
2302 Visitor->AddStmt(E);
2303 }
2304 for (auto *E : C->destination_exprs()) {
2305 Visitor->AddStmt(E);
2306 }
2307 for (auto *E : C->assignment_ops()) {
2308 Visitor->AddStmt(E);
2309 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002310}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002311void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002312 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002313}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002314void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2315 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002316 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002317 for (auto *E : C->privates()) {
2318 Visitor->AddStmt(E);
2319 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002320 for (auto *E : C->lhs_exprs()) {
2321 Visitor->AddStmt(E);
2322 }
2323 for (auto *E : C->rhs_exprs()) {
2324 Visitor->AddStmt(E);
2325 }
2326 for (auto *E : C->reduction_ops()) {
2327 Visitor->AddStmt(E);
2328 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002329}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002330void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2331 const OMPTaskReductionClause *C) {
2332 VisitOMPClauseList(C);
2333 VisitOMPClauseWithPostUpdate(C);
2334 for (auto *E : C->privates()) {
2335 Visitor->AddStmt(E);
2336 }
2337 for (auto *E : C->lhs_exprs()) {
2338 Visitor->AddStmt(E);
2339 }
2340 for (auto *E : C->rhs_exprs()) {
2341 Visitor->AddStmt(E);
2342 }
2343 for (auto *E : C->reduction_ops()) {
2344 Visitor->AddStmt(E);
2345 }
2346}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002347void OMPClauseEnqueue::VisitOMPInReductionClause(
2348 const OMPInReductionClause *C) {
2349 VisitOMPClauseList(C);
2350 VisitOMPClauseWithPostUpdate(C);
2351 for (auto *E : C->privates()) {
2352 Visitor->AddStmt(E);
2353 }
2354 for (auto *E : C->lhs_exprs()) {
2355 Visitor->AddStmt(E);
2356 }
2357 for (auto *E : C->rhs_exprs()) {
2358 Visitor->AddStmt(E);
2359 }
2360 for (auto *E : C->reduction_ops()) {
2361 Visitor->AddStmt(E);
2362 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002363 for (auto *E : C->taskgroup_descriptors())
2364 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002365}
Alexander Musman8dba6642014-04-22 13:09:42 +00002366void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2367 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002368 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002369 for (const auto *E : C->privates()) {
2370 Visitor->AddStmt(E);
2371 }
Alexander Musman3276a272015-03-21 10:12:56 +00002372 for (const auto *E : C->inits()) {
2373 Visitor->AddStmt(E);
2374 }
2375 for (const auto *E : C->updates()) {
2376 Visitor->AddStmt(E);
2377 }
2378 for (const auto *E : C->finals()) {
2379 Visitor->AddStmt(E);
2380 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002381 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002382 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002383}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002384void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2385 VisitOMPClauseList(C);
2386 Visitor->AddStmt(C->getAlignment());
2387}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002388void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2389 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002390 for (auto *E : C->source_exprs()) {
2391 Visitor->AddStmt(E);
2392 }
2393 for (auto *E : C->destination_exprs()) {
2394 Visitor->AddStmt(E);
2395 }
2396 for (auto *E : C->assignment_ops()) {
2397 Visitor->AddStmt(E);
2398 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002399}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002400void
2401OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2402 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002403 for (auto *E : C->source_exprs()) {
2404 Visitor->AddStmt(E);
2405 }
2406 for (auto *E : C->destination_exprs()) {
2407 Visitor->AddStmt(E);
2408 }
2409 for (auto *E : C->assignment_ops()) {
2410 Visitor->AddStmt(E);
2411 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002412}
Alexey Bataev6125da92014-07-21 11:26:11 +00002413void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2414 VisitOMPClauseList(C);
2415}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002416void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2417 VisitOMPClauseList(C);
2418}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002419void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2420 VisitOMPClauseList(C);
2421}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002422void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2423 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002424 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002425 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002426}
Alexey Bataev3392d762016-02-16 11:18:12 +00002427void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2428 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002429void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2430 VisitOMPClauseList(C);
2431}
Samuel Antaoec172c62016-05-26 17:49:04 +00002432void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2433 VisitOMPClauseList(C);
2434}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002435void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2436 VisitOMPClauseList(C);
2437}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002438void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2439 VisitOMPClauseList(C);
2440}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002441}
Alexey Bataev756c1962013-09-24 03:17:45 +00002442
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002443void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2444 unsigned size = WL.size();
2445 OMPClauseEnqueue Visitor(this);
2446 Visitor.Visit(S);
2447 if (size == WL.size())
2448 return;
2449 // Now reverse the entries we just added. This will match the DFS
2450 // ordering performed by the worklist.
2451 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2452 std::reverse(I, E);
2453}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002454void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002455 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2456}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002457void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002458 AddDecl(B->getBlockDecl());
2459}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002460void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002461 EnqueueChildren(E);
2462 AddTypeLoc(E->getTypeSourceInfo());
2463}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002464void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002465 for (auto &I : llvm::reverse(S->body()))
2466 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002467}
2468void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002469VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002470 AddStmt(S->getSubStmt());
2471 AddDeclarationNameInfo(S);
2472 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2473 AddNestedNameSpecifierLoc(QualifierLoc);
2474}
2475
2476void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002477VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002478 if (E->hasExplicitTemplateArgs())
2479 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002480 AddDeclarationNameInfo(E);
2481 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2482 AddNestedNameSpecifierLoc(QualifierLoc);
2483 if (!E->isImplicitAccess())
2484 AddStmt(E->getBase());
2485}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002486void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002487 // Enqueue the initializer , if any.
2488 AddStmt(E->getInitializer());
2489 // Enqueue the array size, if any.
Richard Smithb9fb1212019-05-06 03:47:15 +00002490 AddStmt(E->getArraySize().getValueOr(nullptr));
Guy Benyei11169dd2012-12-18 14:30:41 +00002491 // Enqueue the allocated type.
2492 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2493 // Enqueue the placement arguments.
2494 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2495 AddStmt(E->getPlacementArg(I-1));
2496}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002497void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002498 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2499 AddStmt(CE->getArg(I-1));
2500 AddStmt(CE->getCallee());
2501 AddStmt(CE->getArg(0));
2502}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002503void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2504 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002505 // Visit the name of the type being destroyed.
2506 AddTypeLoc(E->getDestroyedTypeInfo());
2507 // Visit the scope type that looks disturbingly like the nested-name-specifier
2508 // but isn't.
2509 AddTypeLoc(E->getScopeTypeInfo());
2510 // Visit the nested-name-specifier.
2511 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2512 AddNestedNameSpecifierLoc(QualifierLoc);
2513 // Visit base expression.
2514 AddStmt(E->getBase());
2515}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002516void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2517 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002518 AddTypeLoc(E->getTypeSourceInfo());
2519}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002520void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2521 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002522 EnqueueChildren(E);
2523 AddTypeLoc(E->getTypeSourceInfo());
2524}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002525void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002526 EnqueueChildren(E);
2527 if (E->isTypeOperand())
2528 AddTypeLoc(E->getTypeOperandSourceInfo());
2529}
2530
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002531void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2532 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002533 EnqueueChildren(E);
2534 AddTypeLoc(E->getTypeSourceInfo());
2535}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002536void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002537 EnqueueChildren(E);
2538 if (E->isTypeOperand())
2539 AddTypeLoc(E->getTypeOperandSourceInfo());
2540}
2541
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002542void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002543 EnqueueChildren(S);
2544 AddDecl(S->getExceptionDecl());
2545}
2546
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002547void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002548 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002549 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002550 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002551}
2552
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002553void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002554 if (DR->hasExplicitTemplateArgs())
2555 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002556 WL.push_back(DeclRefExprParts(DR, Parent));
2557}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002558void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2559 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002560 if (E->hasExplicitTemplateArgs())
2561 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002562 AddDeclarationNameInfo(E);
2563 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2564}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002565void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002566 unsigned size = WL.size();
2567 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002568 for (const auto *D : S->decls()) {
2569 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002570 isFirst = false;
2571 }
2572 if (size == WL.size())
2573 return;
2574 // Now reverse the entries we just added. This will match the DFS
2575 // ordering performed by the worklist.
2576 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2577 std::reverse(I, E);
2578}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002579void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002580 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002581 for (const DesignatedInitExpr::Designator &D :
2582 llvm::reverse(E->designators())) {
2583 if (D.isFieldDesignator()) {
2584 if (FieldDecl *Field = D.getField())
2585 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002586 continue;
2587 }
David Majnemerf7e36092016-06-23 00:15:04 +00002588 if (D.isArrayDesignator()) {
2589 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002590 continue;
2591 }
David Majnemerf7e36092016-06-23 00:15:04 +00002592 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2593 AddStmt(E->getArrayRangeEnd(D));
2594 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 }
2596}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002597void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002598 EnqueueChildren(E);
2599 AddTypeLoc(E->getTypeInfoAsWritten());
2600}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002601void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 AddStmt(FS->getBody());
2603 AddStmt(FS->getInc());
2604 AddStmt(FS->getCond());
2605 AddDecl(FS->getConditionVariable());
2606 AddStmt(FS->getInit());
2607}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002608void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002609 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2610}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002611void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002612 AddStmt(If->getElse());
2613 AddStmt(If->getThen());
2614 AddStmt(If->getCond());
2615 AddDecl(If->getConditionVariable());
2616}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002617void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 // We care about the syntactic form of the initializer list, only.
2619 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2620 IE = Syntactic;
2621 EnqueueChildren(IE);
2622}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002623void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002624 WL.push_back(MemberExprParts(M, Parent));
2625
2626 // If the base of the member access expression is an implicit 'this', don't
2627 // visit it.
2628 // FIXME: If we ever want to show these implicit accesses, this will be
2629 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002630 if (M->isImplicitAccess())
2631 return;
2632
2633 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002634 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002635 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2636 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2637 if (FD->isAnonymousStructOrUnion()) {
2638 AddStmt(SubME->getBase());
2639 return;
2640 }
2641 }
2642 }
2643
2644 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002645}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002646void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002647 AddTypeLoc(E->getEncodedTypeSourceInfo());
2648}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002649void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002650 EnqueueChildren(M);
2651 AddTypeLoc(M->getClassReceiverTypeInfo());
2652}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002653void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002654 // Visit the components of the offsetof expression.
2655 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002656 const OffsetOfNode &Node = E->getComponent(I-1);
2657 switch (Node.getKind()) {
2658 case OffsetOfNode::Array:
2659 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2660 break;
2661 case OffsetOfNode::Field:
2662 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2663 break;
2664 case OffsetOfNode::Identifier:
2665 case OffsetOfNode::Base:
2666 continue;
2667 }
2668 }
2669 // Visit the type into which we're computing the offset.
2670 AddTypeLoc(E->getTypeSourceInfo());
2671}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002672void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002673 if (E->hasExplicitTemplateArgs())
2674 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002675 WL.push_back(OverloadExprParts(E, Parent));
2676}
2677void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002678 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002679 EnqueueChildren(E);
2680 if (E->isArgumentType())
2681 AddTypeLoc(E->getArgumentTypeInfo());
2682}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002683void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002684 EnqueueChildren(S);
2685}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002686void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002687 AddStmt(S->getBody());
2688 AddStmt(S->getCond());
2689 AddDecl(S->getConditionVariable());
2690}
2691
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002692void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002693 AddStmt(W->getBody());
2694 AddStmt(W->getCond());
2695 AddDecl(W->getConditionVariable());
2696}
2697
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002698void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002699 for (unsigned I = E->getNumArgs(); I > 0; --I)
2700 AddTypeLoc(E->getArg(I-1));
2701}
2702
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002703void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002704 AddTypeLoc(E->getQueriedTypeSourceInfo());
2705}
2706
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002707void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002708 EnqueueChildren(E);
2709}
2710
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002711void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002712 VisitOverloadExpr(U);
2713 if (!U->isImplicitAccess())
2714 AddStmt(U->getBase());
2715}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002716void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002717 AddStmt(E->getSubExpr());
2718 AddTypeLoc(E->getWrittenTypeInfo());
2719}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002720void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002721 WL.push_back(SizeOfPackExprParts(E, Parent));
2722}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002723void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002724 // If the opaque value has a source expression, just transparently
2725 // visit that. This is useful for (e.g.) pseudo-object expressions.
2726 if (Expr *SourceExpr = E->getSourceExpr())
2727 return Visit(SourceExpr);
2728}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002729void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002730 AddStmt(E->getBody());
2731 WL.push_back(LambdaExprParts(E, Parent));
2732}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002733void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002734 // Treat the expression like its syntactic form.
2735 Visit(E->getSyntacticForm());
2736}
2737
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002738void EnqueueVisitor::VisitOMPExecutableDirective(
2739 const OMPExecutableDirective *D) {
2740 EnqueueChildren(D);
2741 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2742 E = D->clauses().end();
2743 I != E; ++I)
2744 EnqueueChildren(*I);
2745}
2746
Alexander Musman3aaab662014-08-19 11:27:13 +00002747void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2748 VisitOMPExecutableDirective(D);
2749}
2750
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002751void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2752 VisitOMPExecutableDirective(D);
2753}
2754
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002755void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002756 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002757}
2758
Alexey Bataevf29276e2014-06-18 04:14:57 +00002759void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002760 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002761}
2762
Alexander Musmanf82886e2014-09-18 05:12:34 +00002763void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2764 VisitOMPLoopDirective(D);
2765}
2766
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002767void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2768 VisitOMPExecutableDirective(D);
2769}
2770
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002771void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2772 VisitOMPExecutableDirective(D);
2773}
2774
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002775void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2776 VisitOMPExecutableDirective(D);
2777}
2778
Alexander Musman80c22892014-07-17 08:54:58 +00002779void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2780 VisitOMPExecutableDirective(D);
2781}
2782
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002783void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2784 VisitOMPExecutableDirective(D);
2785 AddDeclarationNameInfo(D);
2786}
2787
Alexey Bataev4acb8592014-07-07 13:01:15 +00002788void
2789EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002790 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002791}
2792
Alexander Musmane4e893b2014-09-23 09:33:00 +00002793void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2794 const OMPParallelForSimdDirective *D) {
2795 VisitOMPLoopDirective(D);
2796}
2797
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002798void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2799 const OMPParallelSectionsDirective *D) {
2800 VisitOMPExecutableDirective(D);
2801}
2802
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002803void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2804 VisitOMPExecutableDirective(D);
2805}
2806
Alexey Bataev68446b72014-07-18 07:47:19 +00002807void
2808EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2809 VisitOMPExecutableDirective(D);
2810}
2811
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002812void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2813 VisitOMPExecutableDirective(D);
2814}
2815
Alexey Bataev2df347a2014-07-18 10:17:07 +00002816void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2817 VisitOMPExecutableDirective(D);
2818}
2819
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002820void EnqueueVisitor::VisitOMPTaskgroupDirective(
2821 const OMPTaskgroupDirective *D) {
2822 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002823 if (const Expr *E = D->getReductionRef())
2824 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002825}
2826
Alexey Bataev6125da92014-07-21 11:26:11 +00002827void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2828 VisitOMPExecutableDirective(D);
2829}
2830
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002831void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2832 VisitOMPExecutableDirective(D);
2833}
2834
Alexey Bataev0162e452014-07-22 10:10:35 +00002835void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2836 VisitOMPExecutableDirective(D);
2837}
2838
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002839void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2840 VisitOMPExecutableDirective(D);
2841}
2842
Michael Wong65f367f2015-07-21 13:44:28 +00002843void EnqueueVisitor::VisitOMPTargetDataDirective(const
2844 OMPTargetDataDirective *D) {
2845 VisitOMPExecutableDirective(D);
2846}
2847
Samuel Antaodf67fc42016-01-19 19:15:56 +00002848void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2849 const OMPTargetEnterDataDirective *D) {
2850 VisitOMPExecutableDirective(D);
2851}
2852
Samuel Antao72590762016-01-19 20:04:50 +00002853void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2854 const OMPTargetExitDataDirective *D) {
2855 VisitOMPExecutableDirective(D);
2856}
2857
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002858void EnqueueVisitor::VisitOMPTargetParallelDirective(
2859 const OMPTargetParallelDirective *D) {
2860 VisitOMPExecutableDirective(D);
2861}
2862
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002863void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2864 const OMPTargetParallelForDirective *D) {
2865 VisitOMPLoopDirective(D);
2866}
2867
Alexey Bataev13314bf2014-10-09 04:18:56 +00002868void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2869 VisitOMPExecutableDirective(D);
2870}
2871
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002872void EnqueueVisitor::VisitOMPCancellationPointDirective(
2873 const OMPCancellationPointDirective *D) {
2874 VisitOMPExecutableDirective(D);
2875}
2876
Alexey Bataev80909872015-07-02 11:25:17 +00002877void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2878 VisitOMPExecutableDirective(D);
2879}
2880
Alexey Bataev49f6e782015-12-01 04:18:41 +00002881void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2882 VisitOMPLoopDirective(D);
2883}
2884
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002885void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2886 const OMPTaskLoopSimdDirective *D) {
2887 VisitOMPLoopDirective(D);
2888}
2889
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002890void EnqueueVisitor::VisitOMPDistributeDirective(
2891 const OMPDistributeDirective *D) {
2892 VisitOMPLoopDirective(D);
2893}
2894
Carlo Bertolli9925f152016-06-27 14:55:37 +00002895void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2896 const OMPDistributeParallelForDirective *D) {
2897 VisitOMPLoopDirective(D);
2898}
2899
Kelvin Li4a39add2016-07-05 05:00:15 +00002900void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2901 const OMPDistributeParallelForSimdDirective *D) {
2902 VisitOMPLoopDirective(D);
2903}
2904
Kelvin Li787f3fc2016-07-06 04:45:38 +00002905void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2906 const OMPDistributeSimdDirective *D) {
2907 VisitOMPLoopDirective(D);
2908}
2909
Kelvin Lia579b912016-07-14 02:54:56 +00002910void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2911 const OMPTargetParallelForSimdDirective *D) {
2912 VisitOMPLoopDirective(D);
2913}
2914
Kelvin Li986330c2016-07-20 22:57:10 +00002915void EnqueueVisitor::VisitOMPTargetSimdDirective(
2916 const OMPTargetSimdDirective *D) {
2917 VisitOMPLoopDirective(D);
2918}
2919
Kelvin Li02532872016-08-05 14:37:37 +00002920void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2921 const OMPTeamsDistributeDirective *D) {
2922 VisitOMPLoopDirective(D);
2923}
2924
Kelvin Li4e325f72016-10-25 12:50:55 +00002925void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2926 const OMPTeamsDistributeSimdDirective *D) {
2927 VisitOMPLoopDirective(D);
2928}
2929
Kelvin Li579e41c2016-11-30 23:51:03 +00002930void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2931 const OMPTeamsDistributeParallelForSimdDirective *D) {
2932 VisitOMPLoopDirective(D);
2933}
2934
Kelvin Li7ade93f2016-12-09 03:24:30 +00002935void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2936 const OMPTeamsDistributeParallelForDirective *D) {
2937 VisitOMPLoopDirective(D);
2938}
2939
Kelvin Libf594a52016-12-17 05:48:59 +00002940void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2941 const OMPTargetTeamsDirective *D) {
2942 VisitOMPExecutableDirective(D);
2943}
2944
Kelvin Li83c451e2016-12-25 04:52:54 +00002945void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2946 const OMPTargetTeamsDistributeDirective *D) {
2947 VisitOMPLoopDirective(D);
2948}
2949
Kelvin Li80e8f562016-12-29 22:16:30 +00002950void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2951 const OMPTargetTeamsDistributeParallelForDirective *D) {
2952 VisitOMPLoopDirective(D);
2953}
2954
Kelvin Li1851df52017-01-03 05:23:48 +00002955void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2956 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2957 VisitOMPLoopDirective(D);
2958}
2959
Kelvin Lida681182017-01-10 18:08:18 +00002960void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2961 const OMPTargetTeamsDistributeSimdDirective *D) {
2962 VisitOMPLoopDirective(D);
2963}
2964
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002965void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002966 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2967}
2968
2969bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2970 if (RegionOfInterest.isValid()) {
2971 SourceRange Range = getRawCursorExtent(C);
2972 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2973 return false;
2974 }
2975 return true;
2976}
2977
2978bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2979 while (!WL.empty()) {
2980 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002981 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002982
2983 // Set the Parent field, then back to its old value once we're done.
2984 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2985
2986 switch (LI.getKind()) {
2987 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002988 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002989 if (!D)
2990 continue;
2991
2992 // For now, perform default visitation for Decls.
2993 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2994 cast<DeclVisit>(&LI)->isFirst())))
2995 return true;
2996
2997 continue;
2998 }
2999 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00003000 for (const TemplateArgumentLoc &Arg :
3001 *cast<ExplicitTemplateArgsVisit>(&LI)) {
3002 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00003003 return true;
3004 }
3005 continue;
3006 }
3007 case VisitorJob::TypeLocVisitKind: {
3008 // Perform default visitation for TypeLocs.
3009 if (Visit(cast<TypeLocVisit>(&LI)->get()))
3010 return true;
3011 continue;
3012 }
3013 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003014 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003015 if (LabelStmt *stmt = LS->getStmt()) {
3016 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3017 TU))) {
3018 return true;
3019 }
3020 }
3021 continue;
3022 }
3023
3024 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3025 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3026 if (VisitNestedNameSpecifierLoc(V->get()))
3027 return true;
3028 continue;
3029 }
3030
3031 case VisitorJob::DeclarationNameInfoVisitKind: {
3032 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3033 ->get()))
3034 return true;
3035 continue;
3036 }
3037 case VisitorJob::MemberRefVisitKind: {
3038 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3039 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3040 return true;
3041 continue;
3042 }
3043 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003044 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003045 if (!S)
3046 continue;
3047
3048 // Update the current cursor.
3049 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3050 if (!IsInRegionOfInterest(Cursor))
3051 continue;
3052 switch (Visitor(Cursor, Parent, ClientData)) {
3053 case CXChildVisit_Break: return true;
3054 case CXChildVisit_Continue: break;
3055 case CXChildVisit_Recurse:
3056 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003057 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003058 EnqueueWorkList(WL, S);
3059 break;
3060 }
3061 continue;
3062 }
3063 case VisitorJob::MemberExprPartsKind: {
3064 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003065 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003066
3067 // Visit the nested-name-specifier
3068 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3069 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3070 return true;
3071
3072 // Visit the declaration name.
3073 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3074 return true;
3075
3076 // Visit the explicitly-specified template arguments, if any.
3077 if (M->hasExplicitTemplateArgs()) {
3078 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3079 *ArgEnd = Arg + M->getNumTemplateArgs();
3080 Arg != ArgEnd; ++Arg) {
3081 if (VisitTemplateArgumentLoc(*Arg))
3082 return true;
3083 }
3084 }
3085 continue;
3086 }
3087 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003088 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003089 // Visit nested-name-specifier, if present.
3090 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3091 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3092 return true;
3093 // Visit declaration name.
3094 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3095 return true;
3096 continue;
3097 }
3098 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003099 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003100 // Visit the nested-name-specifier.
3101 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3102 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3103 return true;
3104 // Visit the declaration name.
3105 if (VisitDeclarationNameInfo(O->getNameInfo()))
3106 return true;
3107 // Visit the overloaded declaration reference.
3108 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3109 return true;
3110 continue;
3111 }
3112 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003113 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003114 NamedDecl *Pack = E->getPack();
3115 if (isa<TemplateTypeParmDecl>(Pack)) {
3116 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3117 E->getPackLoc(), TU)))
3118 return true;
3119
3120 continue;
3121 }
3122
3123 if (isa<TemplateTemplateParmDecl>(Pack)) {
3124 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3125 E->getPackLoc(), TU)))
3126 return true;
3127
3128 continue;
3129 }
3130
3131 // Non-type template parameter packs and function parameter packs are
3132 // treated like DeclRefExpr cursors.
3133 continue;
3134 }
3135
3136 case VisitorJob::LambdaExprPartsKind: {
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003137 // Visit non-init captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003138 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003139 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3140 CEnd = E->explicit_capture_end();
3141 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003142 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003143 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003144
Guy Benyei11169dd2012-12-18 14:30:41 +00003145 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3146 C->getLocation(),
3147 TU)))
3148 return true;
3149 }
Nikolai Kosjar2eebf4d92019-05-21 09:21:35 +00003150 // Visit init captures
3151 for (auto InitExpr : E->capture_inits()) {
3152 if (Visit(InitExpr))
3153 return true;
3154 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003155
Haojian Wuef87c262018-12-18 15:29:12 +00003156 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00003157 // Visit parameters and return type, if present.
Haojian Wuef87c262018-12-18 15:29:12 +00003158 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3159 if (E->hasExplicitParameters()) {
3160 // Visit parameters.
3161 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3162 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003163 return true;
Haojian Wuef87c262018-12-18 15:29:12 +00003164 }
3165 if (E->hasExplicitResultType()) {
3166 // Visit result type.
3167 if (Visit(Proto.getReturnLoc()))
3168 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003169 }
3170 }
3171 break;
3172 }
3173
3174 case VisitorJob::PostChildrenVisitKind:
3175 if (PostChildrenVisitor(Parent, ClientData))
3176 return true;
3177 break;
3178 }
3179 }
3180 return false;
3181}
3182
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003183bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003184 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003185 if (!WorkListFreeList.empty()) {
3186 WL = WorkListFreeList.back();
3187 WL->clear();
3188 WorkListFreeList.pop_back();
3189 }
3190 else {
3191 WL = new VisitorWorkList();
3192 WorkListCache.push_back(WL);
3193 }
3194 EnqueueWorkList(*WL, S);
3195 bool result = RunVisitorWorkList(*WL);
3196 WorkListFreeList.push_back(WL);
3197 return result;
3198}
3199
3200namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003201typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003202RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3203 const DeclarationNameInfo &NI, SourceRange QLoc,
3204 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003205 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3206 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3207 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3208
3209 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3210
3211 RefNamePieces Pieces;
3212
3213 if (WantQualifier && QLoc.isValid())
3214 Pieces.push_back(QLoc);
3215
3216 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3217 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003218
3219 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3220 Pieces.push_back(*TemplateArgsLoc);
3221
Guy Benyei11169dd2012-12-18 14:30:41 +00003222 if (Kind == DeclarationName::CXXOperatorName) {
3223 Pieces.push_back(SourceLocation::getFromRawEncoding(
3224 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3225 Pieces.push_back(SourceLocation::getFromRawEncoding(
3226 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3227 }
3228
3229 if (WantSinglePiece) {
3230 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3231 Pieces.clear();
3232 Pieces.push_back(R);
3233 }
3234
3235 return Pieces;
3236}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003237}
Guy Benyei11169dd2012-12-18 14:30:41 +00003238
3239//===----------------------------------------------------------------------===//
3240// Misc. API hooks.
3241//===----------------------------------------------------------------------===//
3242
Chad Rosier05c71aa2013-03-27 18:28:23 +00003243static void fatal_error_handler(void *user_data, const std::string& reason,
3244 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003245 // Write the result out to stderr avoiding errs() because raw_ostreams can
3246 // call report_fatal_error.
3247 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3248 ::abort();
3249}
3250
Chandler Carruth66660742014-06-27 16:37:27 +00003251namespace {
3252struct RegisterFatalErrorHandler {
3253 RegisterFatalErrorHandler() {
3254 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3255 }
3256};
3257}
3258
3259static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3260
Guy Benyei11169dd2012-12-18 14:30:41 +00003261CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3262 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003263 // We use crash recovery to make some of our APIs more reliable, implicitly
3264 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003265 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3266 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003267
Chandler Carruth66660742014-06-27 16:37:27 +00003268 // Look through the managed static to trigger construction of the managed
3269 // static which registers our fatal error handler. This ensures it is only
3270 // registered once.
3271 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003272
Adrian Prantlbc068582015-07-08 01:00:30 +00003273 // Initialize targets for clang module support.
3274 llvm::InitializeAllTargets();
3275 llvm::InitializeAllTargetMCs();
3276 llvm::InitializeAllAsmPrinters();
3277 llvm::InitializeAllAsmParsers();
3278
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003279 CIndexer *CIdxr = new CIndexer();
3280
Guy Benyei11169dd2012-12-18 14:30:41 +00003281 if (excludeDeclarationsFromPCH)
3282 CIdxr->setOnlyLocalDecls();
3283 if (displayDiagnostics)
3284 CIdxr->setDisplayDiagnostics();
3285
3286 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3287 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3288 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3289 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3290 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3291 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3292
3293 return CIdxr;
3294}
3295
3296void clang_disposeIndex(CXIndex CIdx) {
3297 if (CIdx)
3298 delete static_cast<CIndexer *>(CIdx);
3299}
3300
3301void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3302 if (CIdx)
3303 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3304}
3305
3306unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3307 if (CIdx)
3308 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3309 return 0;
3310}
3311
Alex Lorenz08615792017-12-04 21:56:36 +00003312void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3313 const char *Path) {
3314 if (CIdx)
3315 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3316}
3317
Guy Benyei11169dd2012-12-18 14:30:41 +00003318void clang_toggleCrashRecovery(unsigned isEnabled) {
3319 if (isEnabled)
3320 llvm::CrashRecoveryContext::Enable();
3321 else
3322 llvm::CrashRecoveryContext::Disable();
3323}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003324
Guy Benyei11169dd2012-12-18 14:30:41 +00003325CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3326 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003327 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003328 enum CXErrorCode Result =
3329 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003330 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003331 assert((TU && Result == CXError_Success) ||
3332 (!TU && Result != CXError_Success));
3333 return TU;
3334}
3335
3336enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3337 const char *ast_filename,
3338 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003339 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003340 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003341
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003342 if (!CIdx || !ast_filename || !out_TU)
3343 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003344
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003345 LOG_FUNC_SECTION {
3346 *Log << ast_filename;
3347 }
3348
Guy Benyei11169dd2012-12-18 14:30:41 +00003349 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3350 FileSystemOptions FileSystemOpts;
3351
Justin Bognerd512c1e2014-10-15 00:33:06 +00003352 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3353 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003354 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003355 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3356 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003357 FileSystemOpts, /*UseDebugInfo=*/false,
3358 CXXIdx->getOnlyLocalDecls(), None,
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003359 CaptureDiagsKind::All,
David Blaikie6f7382d2014-08-10 19:08:04 +00003360 /*AllowPCHWithCompilerErrors=*/true,
3361 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003362 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003363 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003364}
3365
3366unsigned clang_defaultEditingTranslationUnitOptions() {
3367 return CXTranslationUnit_PrecompiledPreamble |
3368 CXTranslationUnit_CacheCompletionResults;
3369}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003370
Guy Benyei11169dd2012-12-18 14:30:41 +00003371CXTranslationUnit
3372clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3373 const char *source_filename,
3374 int num_command_line_args,
3375 const char * const *command_line_args,
3376 unsigned num_unsaved_files,
3377 struct CXUnsavedFile *unsaved_files) {
3378 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3379 return clang_parseTranslationUnit(CIdx, source_filename,
3380 command_line_args, num_command_line_args,
3381 unsaved_files, num_unsaved_files,
3382 Options);
3383}
3384
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003385static CXErrorCode
3386clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3387 const char *const *command_line_args,
3388 int num_command_line_args,
3389 ArrayRef<CXUnsavedFile> unsaved_files,
3390 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003391 // Set up the initial return values.
3392 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003393 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003394
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003395 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003396 if (!CIdx || !out_TU)
3397 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003398
Guy Benyei11169dd2012-12-18 14:30:41 +00003399 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3400
3401 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3402 setThreadBackgroundPriority();
3403
3404 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003405 bool CreatePreambleOnFirstParse =
3406 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003407 // FIXME: Add a flag for modules.
3408 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003409 = (options & (CXTranslationUnit_Incomplete |
3410 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003411 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003412 = options & CXTranslationUnit_CacheCompletionResults;
3413 bool IncludeBriefCommentsInCodeCompletion
3414 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003415 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3416 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003417 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3418 if (options & CXTranslationUnit_SkipFunctionBodies) {
3419 SkipFunctionBodies =
3420 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3421 ? SkipFunctionBodiesScope::Preamble
3422 : SkipFunctionBodiesScope::PreambleAndMainFile;
3423 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003424
3425 // Configure the diagnostics.
3426 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003427 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003428
Manuel Klimek016c0242016-03-01 10:56:19 +00003429 if (options & CXTranslationUnit_KeepGoing)
Ivan Donchevskii878271b2019-03-07 10:13:50 +00003430 Diags->setFatalsAsError(true);
Manuel Klimek016c0242016-03-01 10:56:19 +00003431
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003432 CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::All;
3433 if (options & CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles)
3434 CaptureDiagnostics = CaptureDiagsKind::AllWithoutNonErrorsFromIncludes;
3435
Guy Benyei11169dd2012-12-18 14:30:41 +00003436 // Recover resources if we crash before exiting this function.
3437 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3438 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003439 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003440
Ahmed Charlesb8984322014-03-07 20:03:18 +00003441 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3442 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003443
3444 // Recover resources if we crash before exiting this function.
3445 llvm::CrashRecoveryContextCleanupRegistrar<
3446 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3447
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003448 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003449 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003450 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003451 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003452 }
3453
Ahmed Charlesb8984322014-03-07 20:03:18 +00003454 std::unique_ptr<std::vector<const char *>> Args(
3455 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003456
3457 // Recover resources if we crash before exiting this method.
3458 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3459 ArgsCleanup(Args.get());
3460
3461 // Since the Clang C library is primarily used by batch tools dealing with
3462 // (often very broken) source code, where spell-checking can have a
3463 // significant negative impact on performance (particularly when
3464 // precompiled headers are involved), we disable it by default.
3465 // Only do this if we haven't found a spell-checking-related argument.
3466 bool FoundSpellCheckingArgument = false;
3467 for (int I = 0; I != num_command_line_args; ++I) {
3468 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3469 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3470 FoundSpellCheckingArgument = true;
3471 break;
3472 }
3473 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003474 Args->insert(Args->end(), command_line_args,
3475 command_line_args + num_command_line_args);
3476
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003477 if (!FoundSpellCheckingArgument)
3478 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3479
Guy Benyei11169dd2012-12-18 14:30:41 +00003480 // The 'source_filename' argument is optional. If the caller does not
3481 // specify it then it is assumed that the source file is specified
3482 // in the actual argument list.
3483 // Put the source file after command_line_args otherwise if '-x' flag is
3484 // present it will be unused.
3485 if (source_filename)
3486 Args->push_back(source_filename);
3487
3488 // Do we need the detailed preprocessing record?
3489 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3490 Args->push_back("-Xclang");
3491 Args->push_back("-detailed-preprocessing-record");
3492 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003493
3494 // Suppress any editor placeholder diagnostics.
3495 Args->push_back("-fallow-editor-placeholders");
3496
Guy Benyei11169dd2012-12-18 14:30:41 +00003497 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003498 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003499 // Unless the user specified that they want the preamble on the first parse
3500 // set it up to be created on the first reparse. This makes the first parse
3501 // faster, trading for a slower (first) reparse.
3502 unsigned PrecompilePreambleAfterNParses =
3503 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003504
Alex Lorenz08615792017-12-04 21:56:36 +00003505 LibclangInvocationReporter InvocationReporter(
3506 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003507 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3508 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003509 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003510 Args->data(), Args->data() + Args->size(),
3511 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003512 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00003513 CaptureDiagnostics, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003514 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3515 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003516 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003517 /*UserFilesAreVolatile=*/true, ForSerialization,
3518 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3519 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003520
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003521 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003522 if (!Unit && !ErrUnit)
3523 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003524
Guy Benyei11169dd2012-12-18 14:30:41 +00003525 if (NumErrors != Diags->getClient()->getNumErrors()) {
3526 // Make sure to check that 'Unit' is non-NULL.
3527 if (CXXIdx->getDisplayDiagnostics())
3528 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3529 }
3530
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003531 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3532 return CXError_ASTReadError;
3533
David Blaikieea4395e2017-01-06 19:49:01 +00003534 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003535 if (CXTranslationUnitImpl *TU = *out_TU) {
3536 TU->ParsingOptions = options;
3537 TU->Arguments.reserve(Args->size());
3538 for (const char *Arg : *Args)
3539 TU->Arguments.push_back(Arg);
3540 return CXError_Success;
3541 }
3542 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003543}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003544
3545CXTranslationUnit
3546clang_parseTranslationUnit(CXIndex CIdx,
3547 const char *source_filename,
3548 const char *const *command_line_args,
3549 int num_command_line_args,
3550 struct CXUnsavedFile *unsaved_files,
3551 unsigned num_unsaved_files,
3552 unsigned options) {
3553 CXTranslationUnit TU;
3554 enum CXErrorCode Result = clang_parseTranslationUnit2(
3555 CIdx, source_filename, command_line_args, num_command_line_args,
3556 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003557 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003558 assert((TU && Result == CXError_Success) ||
3559 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003560 return TU;
3561}
3562
3563enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003564 CXIndex CIdx, const char *source_filename,
3565 const char *const *command_line_args, int num_command_line_args,
3566 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3567 unsigned options, CXTranslationUnit *out_TU) {
3568 SmallVector<const char *, 4> Args;
3569 Args.push_back("clang");
3570 Args.append(command_line_args, command_line_args + num_command_line_args);
3571 return clang_parseTranslationUnit2FullArgv(
3572 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3573 num_unsaved_files, options, out_TU);
3574}
3575
3576enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3577 CXIndex CIdx, const char *source_filename,
3578 const char *const *command_line_args, int num_command_line_args,
3579 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3580 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003581 LOG_FUNC_SECTION {
3582 *Log << source_filename << ": ";
3583 for (int i = 0; i != num_command_line_args; ++i)
3584 *Log << command_line_args[i] << " ";
3585 }
3586
Alp Toker9d85b182014-07-07 01:23:14 +00003587 if (num_unsaved_files && !unsaved_files)
3588 return CXError_InvalidArguments;
3589
Alp Toker5c532982014-07-07 22:42:03 +00003590 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003591 auto ParseTranslationUnitImpl = [=, &result] {
3592 result = clang_parseTranslationUnit_Impl(
3593 CIdx, source_filename, command_line_args, num_command_line_args,
3594 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3595 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003596
Guy Benyei11169dd2012-12-18 14:30:41 +00003597 llvm::CrashRecoveryContext CRC;
3598
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003599 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003600 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3601 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3602 fprintf(stderr, " 'command_line_args' : [");
3603 for (int i = 0; i != num_command_line_args; ++i) {
3604 if (i)
3605 fprintf(stderr, ", ");
3606 fprintf(stderr, "'%s'", command_line_args[i]);
3607 }
3608 fprintf(stderr, "],\n");
3609 fprintf(stderr, " 'unsaved_files' : [");
3610 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3611 if (i)
3612 fprintf(stderr, ", ");
3613 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3614 unsaved_files[i].Length);
3615 }
3616 fprintf(stderr, "],\n");
3617 fprintf(stderr, " 'options' : %d,\n", options);
3618 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003619
3620 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003621 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003622 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003623 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003624 }
Alp Toker5c532982014-07-07 22:42:03 +00003625
3626 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003627}
3628
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003629CXString clang_Type_getObjCEncoding(CXType CT) {
3630 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3631 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3632 std::string encoding;
3633 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3634 encoding);
3635
3636 return cxstring::createDup(encoding);
3637}
3638
3639static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3640 if (C.kind == CXCursor_MacroDefinition) {
3641 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3642 return MDR->getName();
3643 } else if (C.kind == CXCursor_MacroExpansion) {
3644 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3645 return ME.getName();
3646 }
3647 return nullptr;
3648}
3649
3650unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3651 const IdentifierInfo *II = getMacroIdentifier(C);
3652 if (!II) {
3653 return false;
3654 }
3655 ASTUnit *ASTU = getCursorASTUnit(C);
3656 Preprocessor &PP = ASTU->getPreprocessor();
3657 if (const MacroInfo *MI = PP.getMacroInfo(II))
3658 return MI->isFunctionLike();
3659 return false;
3660}
3661
3662unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3663 const IdentifierInfo *II = getMacroIdentifier(C);
3664 if (!II) {
3665 return false;
3666 }
3667 ASTUnit *ASTU = getCursorASTUnit(C);
3668 Preprocessor &PP = ASTU->getPreprocessor();
3669 if (const MacroInfo *MI = PP.getMacroInfo(II))
3670 return MI->isBuiltinMacro();
3671 return false;
3672}
3673
3674unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3675 const Decl *D = getCursorDecl(C);
3676 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3677 if (!FD) {
3678 return false;
3679 }
3680 return FD->isInlined();
3681}
3682
3683static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3684 if (callExpr->getNumArgs() != 1) {
3685 return nullptr;
3686 }
3687
3688 StringLiteral *S = nullptr;
3689 auto *arg = callExpr->getArg(0);
3690 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3691 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3692 auto *subExpr = I->getSubExprAsWritten();
3693
3694 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3695 return nullptr;
3696 }
3697
3698 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3699 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3700 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3701 } else {
3702 return nullptr;
3703 }
3704 return S;
3705}
3706
David Blaikie59272572016-04-13 18:23:33 +00003707struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003708 CXEvalResultKind EvalType;
3709 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003710 unsigned long long unsignedVal;
3711 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003712 double floatVal;
3713 char *stringVal;
3714 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003715 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003716 ~ExprEvalResult() {
3717 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3718 EvalType != CXEval_Int) {
Alex Lorenza19cb2e2019-01-08 23:28:37 +00003719 delete[] EvalData.stringVal;
David Blaikie59272572016-04-13 18:23:33 +00003720 }
3721 }
3722};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003723
3724void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003725 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003726}
3727
3728CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3729 if (!E) {
3730 return CXEval_UnExposed;
3731 }
3732 return ((ExprEvalResult *)E)->EvalType;
3733}
3734
3735int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003736 return clang_EvalResult_getAsLongLong(E);
3737}
3738
3739long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003740 if (!E) {
3741 return 0;
3742 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003743 ExprEvalResult *Result = (ExprEvalResult*)E;
3744 if (Result->IsUnsignedInt)
3745 return Result->EvalData.unsignedVal;
3746 return Result->EvalData.intVal;
3747}
3748
3749unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3750 return ((ExprEvalResult *)E)->IsUnsignedInt;
3751}
3752
3753unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3754 if (!E) {
3755 return 0;
3756 }
3757
3758 ExprEvalResult *Result = (ExprEvalResult*)E;
3759 if (Result->IsUnsignedInt)
3760 return Result->EvalData.unsignedVal;
3761 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003762}
3763
3764double clang_EvalResult_getAsDouble(CXEvalResult E) {
3765 if (!E) {
3766 return 0;
3767 }
3768 return ((ExprEvalResult *)E)->EvalData.floatVal;
3769}
3770
3771const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3772 if (!E) {
3773 return nullptr;
3774 }
3775 return ((ExprEvalResult *)E)->EvalData.stringVal;
3776}
3777
3778static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3779 Expr::EvalResult ER;
3780 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003781 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003782 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003783
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003784 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003785 if (!expr->EvaluateAsRValue(ER, ctx))
3786 return nullptr;
3787
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003788 QualType rettype;
3789 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003790 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003791 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003792 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003793
David Blaikiebbc00882016-04-13 18:36:19 +00003794 if (ER.Val.isInt()) {
3795 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003796
3797 auto& val = ER.Val.getInt();
3798 if (val.isUnsigned()) {
3799 result->IsUnsignedInt = true;
3800 result->EvalData.unsignedVal = val.getZExtValue();
3801 } else {
3802 result->EvalData.intVal = val.getExtValue();
3803 }
3804
David Blaikiebbc00882016-04-13 18:36:19 +00003805 return result.release();
3806 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003807
David Blaikiebbc00882016-04-13 18:36:19 +00003808 if (ER.Val.isFloat()) {
3809 llvm::SmallVector<char, 100> Buffer;
3810 ER.Val.getFloat().toString(Buffer);
3811 std::string floatStr(Buffer.data(), Buffer.size());
3812 result->EvalType = CXEval_Float;
3813 bool ignored;
3814 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003815 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003816 llvm::APFloat::rmNearestTiesToEven, &ignored);
3817 result->EvalData.floatVal = apFloat.convertToDouble();
3818 return result.release();
3819 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003820
David Blaikiebbc00882016-04-13 18:36:19 +00003821 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3822 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3823 auto *subExpr = I->getSubExprAsWritten();
3824 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3825 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003826 const StringLiteral *StrE = nullptr;
3827 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003828 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003829
3830 if (ObjCExpr) {
3831 StrE = ObjCExpr->getString();
3832 result->EvalType = CXEval_ObjCStrLiteral;
3833 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003834 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003835 result->EvalType = CXEval_StrLiteral;
3836 }
3837
3838 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003839 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003840 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3841 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003842 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003843 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003844 }
3845 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3846 expr->getStmtClass() == Stmt::StringLiteralClass) {
3847 const StringLiteral *StrE = nullptr;
3848 const ObjCStringLiteral *ObjCExpr;
3849 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003850
David Blaikiebbc00882016-04-13 18:36:19 +00003851 if (ObjCExpr) {
3852 StrE = ObjCExpr->getString();
3853 result->EvalType = CXEval_ObjCStrLiteral;
3854 } else {
3855 StrE = cast<StringLiteral>(expr);
3856 result->EvalType = CXEval_StrLiteral;
3857 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003858
David Blaikiebbc00882016-04-13 18:36:19 +00003859 std::string strRef(StrE->getString().str());
3860 result->EvalData.stringVal = new char[strRef.size() + 1];
3861 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3862 result->EvalData.stringVal[strRef.size()] = '\0';
3863 return result.release();
3864 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003865
David Blaikiebbc00882016-04-13 18:36:19 +00003866 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3867 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003868
David Blaikiebbc00882016-04-13 18:36:19 +00003869 rettype = CC->getType();
3870 if (rettype.getAsString() == "CFStringRef" &&
3871 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003872
David Blaikiebbc00882016-04-13 18:36:19 +00003873 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3874 StringLiteral *S = getCFSTR_value(callExpr);
3875 if (S) {
3876 std::string strLiteral(S->getString().str());
3877 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003878
David Blaikiebbc00882016-04-13 18:36:19 +00003879 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3880 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3881 strLiteral.size());
3882 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003883 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003884 }
3885 }
3886
David Blaikiebbc00882016-04-13 18:36:19 +00003887 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3888 callExpr = static_cast<CallExpr *>(expr);
3889 rettype = callExpr->getCallReturnType(ctx);
3890
3891 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3892 return nullptr;
3893
3894 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3895 if (callExpr->getNumArgs() == 1 &&
3896 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3897 return nullptr;
3898 } else if (rettype.getAsString() == "CFStringRef") {
3899
3900 StringLiteral *S = getCFSTR_value(callExpr);
3901 if (S) {
3902 std::string strLiteral(S->getString().str());
3903 result->EvalType = CXEval_CFStr;
3904 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3905 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3906 strLiteral.size());
3907 result->EvalData.stringVal[strLiteral.size()] = '\0';
3908 return result.release();
3909 }
3910 }
3911 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3912 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3913 ValueDecl *V = D->getDecl();
3914 if (V->getKind() == Decl::Function) {
3915 std::string strName = V->getNameAsString();
3916 result->EvalType = CXEval_Other;
3917 result->EvalData.stringVal = new char[strName.size() + 1];
3918 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3919 result->EvalData.stringVal[strName.size()] = '\0';
3920 return result.release();
3921 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003922 }
3923
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003924 return nullptr;
3925}
3926
Alex Lorenz65317e12019-01-08 22:32:51 +00003927static const Expr *evaluateDeclExpr(const Decl *D) {
3928 if (!D)
Evgeniy Stepanov9b871492018-07-10 19:48:53 +00003929 return nullptr;
Alex Lorenz65317e12019-01-08 22:32:51 +00003930 if (auto *Var = dyn_cast<VarDecl>(D))
3931 return Var->getInit();
3932 else if (auto *Field = dyn_cast<FieldDecl>(D))
3933 return Field->getInClassInitializer();
3934 return nullptr;
3935}
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003936
Alex Lorenz65317e12019-01-08 22:32:51 +00003937static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
3938 assert(CS && "invalid compound statement");
3939 for (auto *bodyIterator : CS->body()) {
3940 if (const auto *E = dyn_cast<Expr>(bodyIterator))
3941 return E;
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003942 }
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00003943 return nullptr;
3944}
3945
Alex Lorenz65317e12019-01-08 22:32:51 +00003946CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3947 if (const Expr *E =
3948 clang_getCursorKind(C) == CXCursor_CompoundStmt
3949 ? evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)))
3950 : evaluateDeclExpr(getCursorDecl(C)))
3951 return const_cast<CXEvalResult>(
3952 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
3953 return nullptr;
3954}
3955
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003956unsigned clang_Cursor_hasAttrs(CXCursor C) {
3957 const Decl *D = getCursorDecl(C);
3958 if (!D) {
3959 return 0;
3960 }
3961
3962 if (D->hasAttrs()) {
3963 return 1;
3964 }
3965
3966 return 0;
3967}
Guy Benyei11169dd2012-12-18 14:30:41 +00003968unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3969 return CXSaveTranslationUnit_None;
3970}
3971
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003972static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3973 const char *FileName,
3974 unsigned options) {
3975 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003976 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3977 setThreadBackgroundPriority();
3978
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003979 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3980 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003981}
3982
3983int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3984 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003985 LOG_FUNC_SECTION {
3986 *Log << TU << ' ' << FileName;
3987 }
3988
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003989 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003990 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003991 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003992 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003993
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003994 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003995 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3996 if (!CXXUnit->hasSema())
3997 return CXSaveError_InvalidTU;
3998
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003999 CXSaveError result;
4000 auto SaveTranslationUnitImpl = [=, &result]() {
4001 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
4002 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004003
Erik Verbruggen3cc39112017-11-14 09:34:39 +00004004 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004005 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00004006
4007 if (getenv("LIBCLANG_RESOURCE_USAGE"))
4008 PrintLibclangResourceUsage(TU);
4009
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004010 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004011 }
4012
4013 // We have an AST that has invalid nodes due to compiler errors.
4014 // Use a crash recovery thread for protection.
4015
4016 llvm::CrashRecoveryContext CRC;
4017
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004018 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004019 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
4020 fprintf(stderr, " 'filename' : '%s'\n", FileName);
4021 fprintf(stderr, " 'options' : %d,\n", options);
4022 fprintf(stderr, "}\n");
4023
4024 return CXSaveError_Unknown;
4025
4026 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4027 PrintLibclangResourceUsage(TU);
4028 }
4029
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004030 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004031}
4032
4033void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4034 if (CTUnit) {
4035 // If the translation unit has been marked as unsafe to free, just discard
4036 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004037 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4038 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004039 return;
4040
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004041 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004042 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004043 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4044 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004045 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004046 delete CTUnit;
4047 }
4048}
4049
Erik Verbruggen346066b2017-05-30 14:25:54 +00004050unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4051 if (CTUnit) {
4052 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4053
4054 if (Unit && Unit->isUnsafeToFree())
4055 return false;
4056
4057 Unit->ResetForParse();
4058 return true;
4059 }
4060
4061 return false;
4062}
4063
Guy Benyei11169dd2012-12-18 14:30:41 +00004064unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4065 return CXReparse_None;
4066}
4067
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004068static CXErrorCode
4069clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4070 ArrayRef<CXUnsavedFile> unsaved_files,
4071 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004072 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004073 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004074 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004075 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004076 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004077
4078 // Reset the associated diagnostics.
4079 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004080 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004081
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004082 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004083 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4084 setThreadBackgroundPriority();
4085
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004086 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004087 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004088
4089 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4090 new std::vector<ASTUnit::RemappedFile>());
4091
Guy Benyei11169dd2012-12-18 14:30:41 +00004092 // Recover resources if we crash before exiting this function.
4093 llvm::CrashRecoveryContextCleanupRegistrar<
4094 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004095
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004096 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004097 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004098 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004099 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004100 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004101
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004102 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4103 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004104 return CXError_Success;
4105 if (isASTReadError(CXXUnit))
4106 return CXError_ASTReadError;
4107 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004108}
4109
4110int clang_reparseTranslationUnit(CXTranslationUnit TU,
4111 unsigned num_unsaved_files,
4112 struct CXUnsavedFile *unsaved_files,
4113 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004114 LOG_FUNC_SECTION {
4115 *Log << TU;
4116 }
4117
Alp Toker9d85b182014-07-07 01:23:14 +00004118 if (num_unsaved_files && !unsaved_files)
4119 return CXError_InvalidArguments;
4120
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004121 CXErrorCode result;
4122 auto ReparseTranslationUnitImpl = [=, &result]() {
4123 result = clang_reparseTranslationUnit_Impl(
4124 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4125 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004126
Guy Benyei11169dd2012-12-18 14:30:41 +00004127 llvm::CrashRecoveryContext CRC;
4128
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004129 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004130 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004131 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004132 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004133 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4134 PrintLibclangResourceUsage(TU);
4135
Alp Toker5c532982014-07-07 22:42:03 +00004136 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004137}
4138
4139
4140CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004141 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004142 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004143 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004144 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004145
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004146 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004147 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004148}
4149
4150CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004151 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004152 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004153 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004154 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004155
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004156 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004157 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4158}
4159
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004160CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4161 if (isNotUsableTU(CTUnit)) {
4162 LOG_BAD_TU(CTUnit);
4163 return nullptr;
4164 }
4165
4166 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4167 impl->TranslationUnit = CTUnit;
4168 return impl;
4169}
4170
4171CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4172 if (!TargetInfo)
4173 return cxstring::createEmpty();
4174
4175 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4176 assert(!isNotUsableTU(CTUnit) &&
4177 "Unexpected unusable translation unit in TargetInfo");
4178
4179 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4180 std::string Triple =
4181 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4182 return cxstring::createDup(Triple);
4183}
4184
4185int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4186 if (!TargetInfo)
4187 return -1;
4188
4189 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4190 assert(!isNotUsableTU(CTUnit) &&
4191 "Unexpected unusable translation unit in TargetInfo");
4192
4193 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4194 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4195}
4196
4197void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4198 if (!TargetInfo)
4199 return;
4200
4201 delete TargetInfo;
4202}
4203
Guy Benyei11169dd2012-12-18 14:30:41 +00004204//===----------------------------------------------------------------------===//
4205// CXFile Operations.
4206//===----------------------------------------------------------------------===//
4207
Guy Benyei11169dd2012-12-18 14:30:41 +00004208CXString clang_getFileName(CXFile SFile) {
4209 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004210 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004211
4212 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004213 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004214}
4215
4216time_t clang_getFileTime(CXFile SFile) {
4217 if (!SFile)
4218 return 0;
4219
4220 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4221 return FEnt->getModificationTime();
4222}
4223
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004224CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004225 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004226 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004227 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004228 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004229
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004230 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004231
4232 FileManager &FMgr = CXXUnit->getFileManager();
4233 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4234}
4235
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004236const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4237 size_t *size) {
4238 if (isNotUsableTU(TU)) {
4239 LOG_BAD_TU(TU);
4240 return nullptr;
4241 }
4242
4243 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4244 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4245 bool Invalid = true;
Nico Weber04347d82019-04-04 21:06:41 +00004246 const llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004247 if (Invalid) {
4248 if (size)
4249 *size = 0;
4250 return nullptr;
4251 }
4252 if (size)
4253 *size = buf->getBufferSize();
4254 return buf->getBufferStart();
4255}
4256
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004257unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4258 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004259 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004260 LOG_BAD_TU(TU);
4261 return 0;
4262 }
4263
4264 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004265 return 0;
4266
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004267 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004268 FileEntry *FEnt = static_cast<FileEntry *>(file);
4269 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4270 .isFileMultipleIncludeGuarded(FEnt);
4271}
4272
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004273int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4274 if (!file || !outID)
4275 return 1;
4276
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004277 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004278 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4279 outID->data[0] = ID.getDevice();
4280 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004281 outID->data[2] = FEnt->getModificationTime();
4282 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004283}
4284
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004285int clang_File_isEqual(CXFile file1, CXFile file2) {
4286 if (file1 == file2)
4287 return true;
4288
4289 if (!file1 || !file2)
4290 return false;
4291
4292 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4293 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4294 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4295}
4296
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004297CXString clang_File_tryGetRealPathName(CXFile SFile) {
4298 if (!SFile)
4299 return cxstring::createNull();
4300
4301 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4302 return cxstring::createRef(FEnt->tryGetRealPathName());
4303}
4304
Guy Benyei11169dd2012-12-18 14:30:41 +00004305//===----------------------------------------------------------------------===//
4306// CXCursor Operations.
4307//===----------------------------------------------------------------------===//
4308
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004309static const Decl *getDeclFromExpr(const Stmt *E) {
4310 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004311 return getDeclFromExpr(CE->getSubExpr());
4312
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004313 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004314 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004315 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004316 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004317 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004318 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004319 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004320 if (PRE->isExplicitProperty())
4321 return PRE->getExplicitProperty();
4322 // It could be messaging both getter and setter as in:
4323 // ++myobj.myprop;
4324 // in which case prefer to associate the setter since it is less obvious
4325 // from inspecting the source that the setter is going to get called.
4326 if (PRE->isMessagingSetter())
4327 return PRE->getImplicitPropertySetter();
4328 return PRE->getImplicitPropertyGetter();
4329 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004330 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004331 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004332 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004333 if (Expr *Src = OVE->getSourceExpr())
4334 return getDeclFromExpr(Src);
4335
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004336 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004337 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004338 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004339 if (!CE->isElidable())
4340 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004341 if (const CXXInheritedCtorInitExpr *CE =
4342 dyn_cast<CXXInheritedCtorInitExpr>(E))
4343 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004344 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004345 return OME->getMethodDecl();
4346
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004347 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004348 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004349 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004350 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4351 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004352 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004353 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4354 isa<ParmVarDecl>(SizeOfPack->getPack()))
4355 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004356
4357 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004358}
4359
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004360static SourceLocation getLocationFromExpr(const Expr *E) {
4361 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004362 return getLocationFromExpr(CE->getSubExpr());
4363
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004364 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004365 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004366 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004367 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004368 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004369 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004370 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004371 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004372 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004373 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004374 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004375 return PropRef->getLocation();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004376
4377 return E->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00004378}
4379
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004380extern "C" {
4381
Guy Benyei11169dd2012-12-18 14:30:41 +00004382unsigned clang_visitChildren(CXCursor parent,
4383 CXCursorVisitor visitor,
4384 CXClientData client_data) {
4385 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4386 /*VisitPreprocessorLast=*/false);
4387 return CursorVis.VisitChildren(parent);
4388}
4389
4390#ifndef __has_feature
4391#define __has_feature(x) 0
4392#endif
4393#if __has_feature(blocks)
4394typedef enum CXChildVisitResult
4395 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4396
4397static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4398 CXClientData client_data) {
4399 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4400 return block(cursor, parent);
4401}
4402#else
4403// If we are compiled with a compiler that doesn't have native blocks support,
4404// define and call the block manually, so the
4405typedef struct _CXChildVisitResult
4406{
4407 void *isa;
4408 int flags;
4409 int reserved;
4410 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4411 CXCursor);
4412} *CXCursorVisitorBlock;
4413
4414static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4415 CXClientData client_data) {
4416 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4417 return block->invoke(block, cursor, parent);
4418}
4419#endif
4420
4421
4422unsigned clang_visitChildrenWithBlock(CXCursor parent,
4423 CXCursorVisitorBlock block) {
4424 return clang_visitChildren(parent, visitWithBlock, block);
4425}
4426
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004427static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004428 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004429 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004430
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004431 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004432 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004433 if (const ObjCPropertyImplDecl *PropImpl =
4434 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004435 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004436 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004437
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004438 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004439 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004440 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004441
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004442 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004443 }
4444
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004445 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004446 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004447
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004448 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004449 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4450 // and returns different names. NamedDecl returns the class name and
4451 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004452 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004453
4454 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004455 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004456
4457 SmallString<1024> S;
4458 llvm::raw_svector_ostream os(S);
4459 ND->printName(os);
4460
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004461 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004462}
4463
4464CXString clang_getCursorSpelling(CXCursor C) {
4465 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004466 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004467
4468 if (clang_isReference(C.kind)) {
4469 switch (C.kind) {
4470 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004471 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004472 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004473 }
4474 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004475 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004476 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004477 }
4478 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004479 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004480 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004481 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004482 }
4483 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004484 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004485 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004486 }
4487 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004488 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004489 assert(Type && "Missing type decl");
4490
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004491 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004492 getAsString());
4493 }
4494 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004495 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004496 assert(Template && "Missing template decl");
4497
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004498 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004499 }
4500
4501 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004502 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004503 assert(NS && "Missing namespace decl");
4504
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004505 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004506 }
4507
4508 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004509 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004510 assert(Field && "Missing member decl");
4511
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004512 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004513 }
4514
4515 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004516 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004517 assert(Label && "Missing label");
4518
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004519 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004520 }
4521
4522 case CXCursor_OverloadedDeclRef: {
4523 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004524 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4525 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004526 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004527 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004528 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004529 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004530 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004531 OverloadedTemplateStorage *Ovl
4532 = Storage.get<OverloadedTemplateStorage*>();
4533 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004534 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004535 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004536 }
4537
4538 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004539 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004540 assert(Var && "Missing variable decl");
4541
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004542 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004543 }
4544
4545 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004546 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004547 }
4548 }
4549
4550 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004551 const Expr *E = getCursorExpr(C);
4552
4553 if (C.kind == CXCursor_ObjCStringLiteral ||
4554 C.kind == CXCursor_StringLiteral) {
4555 const StringLiteral *SLit;
4556 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4557 SLit = OSL->getString();
4558 } else {
4559 SLit = cast<StringLiteral>(E);
4560 }
4561 SmallString<256> Buf;
4562 llvm::raw_svector_ostream OS(Buf);
4563 SLit->outputString(OS);
4564 return cxstring::createDup(OS.str());
4565 }
4566
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004567 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004568 if (D)
4569 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004570 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004571 }
4572
4573 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004574 const Stmt *S = getCursorStmt(C);
4575 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004576 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004577
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004578 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004579 }
4580
4581 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004582 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004583 ->getNameStart());
4584
4585 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004586 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004587 ->getNameStart());
4588
4589 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004590 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004591
4592 if (clang_isDeclaration(C.kind))
4593 return getDeclSpelling(getCursorDecl(C));
4594
4595 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004596 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004597 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004598 }
4599
4600 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004601 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004602 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004603 }
4604
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004605 if (C.kind == CXCursor_PackedAttr) {
4606 return cxstring::createRef("packed");
4607 }
4608
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004609 if (C.kind == CXCursor_VisibilityAttr) {
4610 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4611 switch (AA->getVisibility()) {
4612 case VisibilityAttr::VisibilityType::Default:
4613 return cxstring::createRef("default");
4614 case VisibilityAttr::VisibilityType::Hidden:
4615 return cxstring::createRef("hidden");
4616 case VisibilityAttr::VisibilityType::Protected:
4617 return cxstring::createRef("protected");
4618 }
4619 llvm_unreachable("unknown visibility type");
4620 }
4621
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004622 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004623}
4624
4625CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4626 unsigned pieceIndex,
4627 unsigned options) {
4628 if (clang_Cursor_isNull(C))
4629 return clang_getNullRange();
4630
4631 ASTContext &Ctx = getCursorContext(C);
4632
4633 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004634 const Stmt *S = getCursorStmt(C);
4635 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004636 if (pieceIndex > 0)
4637 return clang_getNullRange();
4638 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4639 }
4640
4641 return clang_getNullRange();
4642 }
4643
4644 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004645 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004646 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4647 if (pieceIndex >= ME->getNumSelectorLocs())
4648 return clang_getNullRange();
4649 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4650 }
4651 }
4652
4653 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4654 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004655 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004656 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4657 if (pieceIndex >= MD->getNumSelectorLocs())
4658 return clang_getNullRange();
4659 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4660 }
4661 }
4662
4663 if (C.kind == CXCursor_ObjCCategoryDecl ||
4664 C.kind == CXCursor_ObjCCategoryImplDecl) {
4665 if (pieceIndex > 0)
4666 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004667 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004668 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4669 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004670 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004671 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4672 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4673 }
4674
4675 if (C.kind == CXCursor_ModuleImportDecl) {
4676 if (pieceIndex > 0)
4677 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004678 if (const ImportDecl *ImportD =
4679 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004680 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4681 if (!Locs.empty())
4682 return cxloc::translateSourceRange(Ctx,
4683 SourceRange(Locs.front(), Locs.back()));
4684 }
4685 return clang_getNullRange();
4686 }
4687
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004688 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004689 C.kind == CXCursor_ConversionFunction ||
4690 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004691 if (pieceIndex > 0)
4692 return clang_getNullRange();
4693 if (const FunctionDecl *FD =
4694 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4695 DeclarationNameInfo FunctionName = FD->getNameInfo();
4696 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4697 }
4698 return clang_getNullRange();
4699 }
4700
Guy Benyei11169dd2012-12-18 14:30:41 +00004701 // FIXME: A CXCursor_InclusionDirective should give the location of the
4702 // filename, but we don't keep track of this.
4703
4704 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4705 // but we don't keep track of this.
4706
4707 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4708 // but we don't keep track of this.
4709
4710 // Default handling, give the location of the cursor.
4711
4712 if (pieceIndex > 0)
4713 return clang_getNullRange();
4714
4715 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4716 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4717 return cxloc::translateSourceRange(Ctx, Loc);
4718}
4719
Eli Bendersky44a206f2014-07-31 18:04:56 +00004720CXString clang_Cursor_getMangling(CXCursor C) {
4721 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4722 return cxstring::createEmpty();
4723
Eli Bendersky44a206f2014-07-31 18:04:56 +00004724 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004725 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004726 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4727 return cxstring::createEmpty();
4728
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004729 ASTContext &Ctx = D->getASTContext();
4730 index::CodegenNameGenerator CGNameGen(Ctx);
4731 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004732}
4733
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004734CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4735 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4736 return nullptr;
4737
4738 const Decl *D = getCursorDecl(C);
4739 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4740 return nullptr;
4741
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004742 ASTContext &Ctx = D->getASTContext();
4743 index::CodegenNameGenerator CGNameGen(Ctx);
4744 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004745 return cxstring::createSet(Manglings);
4746}
4747
Dave Lee1a532c92017-09-22 16:58:57 +00004748CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4749 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4750 return nullptr;
4751
4752 const Decl *D = getCursorDecl(C);
4753 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4754 return nullptr;
4755
4756 ASTContext &Ctx = D->getASTContext();
4757 index::CodegenNameGenerator CGNameGen(Ctx);
4758 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4759 return cxstring::createSet(Manglings);
4760}
4761
Jonathan Coe45ef5032018-01-16 10:19:56 +00004762CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4763 if (clang_Cursor_isNull(C))
4764 return 0;
4765 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4766}
4767
4768void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4769 if (Policy)
4770 delete static_cast<PrintingPolicy *>(Policy);
4771}
4772
4773unsigned
4774clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4775 enum CXPrintingPolicyProperty Property) {
4776 if (!Policy)
4777 return 0;
4778
4779 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4780 switch (Property) {
4781 case CXPrintingPolicy_Indentation:
4782 return P->Indentation;
4783 case CXPrintingPolicy_SuppressSpecifiers:
4784 return P->SuppressSpecifiers;
4785 case CXPrintingPolicy_SuppressTagKeyword:
4786 return P->SuppressTagKeyword;
4787 case CXPrintingPolicy_IncludeTagDefinition:
4788 return P->IncludeTagDefinition;
4789 case CXPrintingPolicy_SuppressScope:
4790 return P->SuppressScope;
4791 case CXPrintingPolicy_SuppressUnwrittenScope:
4792 return P->SuppressUnwrittenScope;
4793 case CXPrintingPolicy_SuppressInitializers:
4794 return P->SuppressInitializers;
4795 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4796 return P->ConstantArraySizeAsWritten;
4797 case CXPrintingPolicy_AnonymousTagLocations:
4798 return P->AnonymousTagLocations;
4799 case CXPrintingPolicy_SuppressStrongLifetime:
4800 return P->SuppressStrongLifetime;
4801 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4802 return P->SuppressLifetimeQualifiers;
4803 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4804 return P->SuppressTemplateArgsInCXXConstructors;
4805 case CXPrintingPolicy_Bool:
4806 return P->Bool;
4807 case CXPrintingPolicy_Restrict:
4808 return P->Restrict;
4809 case CXPrintingPolicy_Alignof:
4810 return P->Alignof;
4811 case CXPrintingPolicy_UnderscoreAlignof:
4812 return P->UnderscoreAlignof;
4813 case CXPrintingPolicy_UseVoidForZeroParams:
4814 return P->UseVoidForZeroParams;
4815 case CXPrintingPolicy_TerseOutput:
4816 return P->TerseOutput;
4817 case CXPrintingPolicy_PolishForDeclaration:
4818 return P->PolishForDeclaration;
4819 case CXPrintingPolicy_Half:
4820 return P->Half;
4821 case CXPrintingPolicy_MSWChar:
4822 return P->MSWChar;
4823 case CXPrintingPolicy_IncludeNewlines:
4824 return P->IncludeNewlines;
4825 case CXPrintingPolicy_MSVCFormatting:
4826 return P->MSVCFormatting;
4827 case CXPrintingPolicy_ConstantsAsWritten:
4828 return P->ConstantsAsWritten;
4829 case CXPrintingPolicy_SuppressImplicitBase:
4830 return P->SuppressImplicitBase;
4831 case CXPrintingPolicy_FullyQualifiedName:
4832 return P->FullyQualifiedName;
4833 }
4834
4835 assert(false && "Invalid CXPrintingPolicyProperty");
4836 return 0;
4837}
4838
4839void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4840 enum CXPrintingPolicyProperty Property,
4841 unsigned Value) {
4842 if (!Policy)
4843 return;
4844
4845 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4846 switch (Property) {
4847 case CXPrintingPolicy_Indentation:
4848 P->Indentation = Value;
4849 return;
4850 case CXPrintingPolicy_SuppressSpecifiers:
4851 P->SuppressSpecifiers = Value;
4852 return;
4853 case CXPrintingPolicy_SuppressTagKeyword:
4854 P->SuppressTagKeyword = Value;
4855 return;
4856 case CXPrintingPolicy_IncludeTagDefinition:
4857 P->IncludeTagDefinition = Value;
4858 return;
4859 case CXPrintingPolicy_SuppressScope:
4860 P->SuppressScope = Value;
4861 return;
4862 case CXPrintingPolicy_SuppressUnwrittenScope:
4863 P->SuppressUnwrittenScope = Value;
4864 return;
4865 case CXPrintingPolicy_SuppressInitializers:
4866 P->SuppressInitializers = Value;
4867 return;
4868 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4869 P->ConstantArraySizeAsWritten = Value;
4870 return;
4871 case CXPrintingPolicy_AnonymousTagLocations:
4872 P->AnonymousTagLocations = Value;
4873 return;
4874 case CXPrintingPolicy_SuppressStrongLifetime:
4875 P->SuppressStrongLifetime = Value;
4876 return;
4877 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4878 P->SuppressLifetimeQualifiers = Value;
4879 return;
4880 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4881 P->SuppressTemplateArgsInCXXConstructors = Value;
4882 return;
4883 case CXPrintingPolicy_Bool:
4884 P->Bool = Value;
4885 return;
4886 case CXPrintingPolicy_Restrict:
4887 P->Restrict = Value;
4888 return;
4889 case CXPrintingPolicy_Alignof:
4890 P->Alignof = Value;
4891 return;
4892 case CXPrintingPolicy_UnderscoreAlignof:
4893 P->UnderscoreAlignof = Value;
4894 return;
4895 case CXPrintingPolicy_UseVoidForZeroParams:
4896 P->UseVoidForZeroParams = Value;
4897 return;
4898 case CXPrintingPolicy_TerseOutput:
4899 P->TerseOutput = Value;
4900 return;
4901 case CXPrintingPolicy_PolishForDeclaration:
4902 P->PolishForDeclaration = Value;
4903 return;
4904 case CXPrintingPolicy_Half:
4905 P->Half = Value;
4906 return;
4907 case CXPrintingPolicy_MSWChar:
4908 P->MSWChar = Value;
4909 return;
4910 case CXPrintingPolicy_IncludeNewlines:
4911 P->IncludeNewlines = Value;
4912 return;
4913 case CXPrintingPolicy_MSVCFormatting:
4914 P->MSVCFormatting = Value;
4915 return;
4916 case CXPrintingPolicy_ConstantsAsWritten:
4917 P->ConstantsAsWritten = Value;
4918 return;
4919 case CXPrintingPolicy_SuppressImplicitBase:
4920 P->SuppressImplicitBase = Value;
4921 return;
4922 case CXPrintingPolicy_FullyQualifiedName:
4923 P->FullyQualifiedName = Value;
4924 return;
4925 }
4926
4927 assert(false && "Invalid CXPrintingPolicyProperty");
4928}
4929
4930CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4931 if (clang_Cursor_isNull(C))
4932 return cxstring::createEmpty();
4933
4934 if (clang_isDeclaration(C.kind)) {
4935 const Decl *D = getCursorDecl(C);
4936 if (!D)
4937 return cxstring::createEmpty();
4938
4939 SmallString<128> Str;
4940 llvm::raw_svector_ostream OS(Str);
4941 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4942 D->print(OS, UserPolicy ? *UserPolicy
4943 : getCursorContext(C).getPrintingPolicy());
4944
4945 return cxstring::createDup(OS.str());
4946 }
4947
4948 return cxstring::createEmpty();
4949}
4950
Guy Benyei11169dd2012-12-18 14:30:41 +00004951CXString clang_getCursorDisplayName(CXCursor C) {
4952 if (!clang_isDeclaration(C.kind))
4953 return clang_getCursorSpelling(C);
4954
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004955 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004956 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004957 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004958
4959 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004960 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004961 D = FunTmpl->getTemplatedDecl();
4962
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004963 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004964 SmallString<64> Str;
4965 llvm::raw_svector_ostream OS(Str);
4966 OS << *Function;
4967 if (Function->getPrimaryTemplate())
4968 OS << "<>";
4969 OS << "(";
4970 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4971 if (I)
4972 OS << ", ";
4973 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4974 }
4975
4976 if (Function->isVariadic()) {
4977 if (Function->getNumParams())
4978 OS << ", ";
4979 OS << "...";
4980 }
4981 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004982 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004983 }
4984
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004985 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004986 SmallString<64> Str;
4987 llvm::raw_svector_ostream OS(Str);
4988 OS << *ClassTemplate;
4989 OS << "<";
4990 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4991 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4992 if (I)
4993 OS << ", ";
4994
4995 NamedDecl *Param = Params->getParam(I);
4996 if (Param->getIdentifier()) {
4997 OS << Param->getIdentifier()->getName();
4998 continue;
4999 }
5000
5001 // There is no parameter name, which makes this tricky. Try to come up
5002 // with something useful that isn't too long.
5003 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5004 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
5005 else if (NonTypeTemplateParmDecl *NTTP
5006 = dyn_cast<NonTypeTemplateParmDecl>(Param))
5007 OS << NTTP->getType().getAsString(Policy);
5008 else
5009 OS << "template<...> class";
5010 }
5011
5012 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005013 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005014 }
5015
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005016 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00005017 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
5018 // If the type was explicitly written, use that.
5019 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005020 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00005021
Benjamin Kramer9170e912013-02-22 15:46:01 +00005022 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00005023 llvm::raw_svector_ostream OS(Str);
5024 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00005025 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5026 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005027 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005028 }
5029
5030 return clang_getCursorSpelling(C);
5031}
5032
5033CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5034 switch (Kind) {
5035 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005036 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005037 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005038 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005039 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005040 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005041 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005042 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005043 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005044 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005045 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005046 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005047 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005048 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005049 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005050 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005051 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005052 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005053 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005054 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005055 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005056 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005057 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005058 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005059 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005060 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005061 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005062 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005063 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005064 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005065 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005066 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005067 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005068 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005069 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005070 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005071 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005072 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005074 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005075 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005076 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005077 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005078 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005079 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005080 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005081 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005082 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005083 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005084 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005085 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005086 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005087 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005088 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005089 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005090 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005091 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005092 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005093 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005094 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005095 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005096 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005097 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005098 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005099 case CXCursor_FixedPointLiteral:
5100 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005101 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005102 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005103 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005104 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005105 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005106 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005107 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005108 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005109 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005110 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005111 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005112 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005113 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005114 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005115 case CXCursor_OMPArraySectionExpr:
5116 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005117 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005118 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005119 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005120 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005121 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005122 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005123 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005124 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005125 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005126 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005127 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005128 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005129 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005130 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005131 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005132 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005133 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005134 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005135 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005136 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005137 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005138 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005139 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005140 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005141 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005142 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005143 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005144 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005145 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005146 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005147 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005148 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005149 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005150 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005151 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005152 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005153 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005154 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005155 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005156 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005157 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005158 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005159 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005160 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005161 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005162 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005163 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005164 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005165 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005166 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005167 case CXCursor_ObjCAvailabilityCheckExpr:
5168 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005169 case CXCursor_ObjCSelfExpr:
5170 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005171 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005172 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005173 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005174 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005175 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005176 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005177 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005178 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005179 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005180 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005181 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005182 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005183 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005184 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005185 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005186 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005187 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005188 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005189 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005190 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005191 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005192 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005193 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005194 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005195 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005196 return cxstring::createRef("ObjCMessageExpr");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005197 case CXCursor_BuiltinBitCastExpr:
5198 return cxstring::createRef("BuiltinBitCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005199 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005200 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005201 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005202 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005203 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005204 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005205 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005206 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005207 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005208 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005209 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005210 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005211 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005212 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005213 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005214 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005215 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005216 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005217 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005218 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005219 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005220 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005221 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005222 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005223 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005224 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005225 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005226 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005227 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005228 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005229 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005230 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005231 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005232 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005233 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005234 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005235 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005236 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005237 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005238 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005239 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005240 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005241 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005242 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005243 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005244 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005245 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005246 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005247 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005248 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005249 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005250 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005251 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005252 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005253 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005254 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005255 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005256 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005257 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005258 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005259 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005260 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005261 case CXCursor_SEHLeaveStmt:
5262 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005263 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005264 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005265 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005266 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005267 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005268 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005269 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005270 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005271 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005272 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005273 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005274 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005275 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005276 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005277 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005278 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005279 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005280 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005281 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005282 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005283 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005284 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005285 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005286 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005287 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005288 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005289 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005290 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005291 case CXCursor_PackedAttr:
5292 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005293 case CXCursor_PureAttr:
5294 return cxstring::createRef("attribute(pure)");
5295 case CXCursor_ConstAttr:
5296 return cxstring::createRef("attribute(const)");
5297 case CXCursor_NoDuplicateAttr:
5298 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005299 case CXCursor_CUDAConstantAttr:
5300 return cxstring::createRef("attribute(constant)");
5301 case CXCursor_CUDADeviceAttr:
5302 return cxstring::createRef("attribute(device)");
5303 case CXCursor_CUDAGlobalAttr:
5304 return cxstring::createRef("attribute(global)");
5305 case CXCursor_CUDAHostAttr:
5306 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005307 case CXCursor_CUDASharedAttr:
5308 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005309 case CXCursor_VisibilityAttr:
5310 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005311 case CXCursor_DLLExport:
5312 return cxstring::createRef("attribute(dllexport)");
5313 case CXCursor_DLLImport:
5314 return cxstring::createRef("attribute(dllimport)");
Michael Wud092d0b2018-08-03 05:03:22 +00005315 case CXCursor_NSReturnsRetained:
5316 return cxstring::createRef("attribute(ns_returns_retained)");
5317 case CXCursor_NSReturnsNotRetained:
5318 return cxstring::createRef("attribute(ns_returns_not_retained)");
5319 case CXCursor_NSReturnsAutoreleased:
5320 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5321 case CXCursor_NSConsumesSelf:
5322 return cxstring::createRef("attribute(ns_consumes_self)");
5323 case CXCursor_NSConsumed:
5324 return cxstring::createRef("attribute(ns_consumed)");
5325 case CXCursor_ObjCException:
5326 return cxstring::createRef("attribute(objc_exception)");
5327 case CXCursor_ObjCNSObject:
5328 return cxstring::createRef("attribute(NSObject)");
5329 case CXCursor_ObjCIndependentClass:
5330 return cxstring::createRef("attribute(objc_independent_class)");
5331 case CXCursor_ObjCPreciseLifetime:
5332 return cxstring::createRef("attribute(objc_precise_lifetime)");
5333 case CXCursor_ObjCReturnsInnerPointer:
5334 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5335 case CXCursor_ObjCRequiresSuper:
5336 return cxstring::createRef("attribute(objc_requires_super)");
5337 case CXCursor_ObjCRootClass:
5338 return cxstring::createRef("attribute(objc_root_class)");
5339 case CXCursor_ObjCSubclassingRestricted:
5340 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5341 case CXCursor_ObjCExplicitProtocolImpl:
5342 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5343 case CXCursor_ObjCDesignatedInitializer:
5344 return cxstring::createRef("attribute(objc_designated_initializer)");
5345 case CXCursor_ObjCRuntimeVisible:
5346 return cxstring::createRef("attribute(objc_runtime_visible)");
5347 case CXCursor_ObjCBoxable:
5348 return cxstring::createRef("attribute(objc_boxable)");
Michael Wu58d837d2018-08-03 05:55:40 +00005349 case CXCursor_FlagEnum:
5350 return cxstring::createRef("attribute(flag_enum)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005351 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005352 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005353 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005354 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005355 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005356 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005357 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005358 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005359 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005360 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005361 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005362 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005363 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005364 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005365 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005366 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005367 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005368 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005369 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005370 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005371 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005372 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005373 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005374 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005375 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005376 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005377 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005378 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005379 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005380 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005381 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005382 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005383 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005384 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005385 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005386 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005387 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005388 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005389 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005390 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005391 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005392 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005393 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005394 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005395 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005396 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005397 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005398 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005399 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005400 return cxstring::createRef("OMPParallelDirective");
5401 case CXCursor_OMPSimdDirective:
5402 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005403 case CXCursor_OMPForDirective:
5404 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005405 case CXCursor_OMPForSimdDirective:
5406 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005407 case CXCursor_OMPSectionsDirective:
5408 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005409 case CXCursor_OMPSectionDirective:
5410 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005411 case CXCursor_OMPSingleDirective:
5412 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005413 case CXCursor_OMPMasterDirective:
5414 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005415 case CXCursor_OMPCriticalDirective:
5416 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005417 case CXCursor_OMPParallelForDirective:
5418 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005419 case CXCursor_OMPParallelForSimdDirective:
5420 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005421 case CXCursor_OMPParallelSectionsDirective:
5422 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005423 case CXCursor_OMPTaskDirective:
5424 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005425 case CXCursor_OMPTaskyieldDirective:
5426 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005427 case CXCursor_OMPBarrierDirective:
5428 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005429 case CXCursor_OMPTaskwaitDirective:
5430 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005431 case CXCursor_OMPTaskgroupDirective:
5432 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005433 case CXCursor_OMPFlushDirective:
5434 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005435 case CXCursor_OMPOrderedDirective:
5436 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005437 case CXCursor_OMPAtomicDirective:
5438 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005439 case CXCursor_OMPTargetDirective:
5440 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005441 case CXCursor_OMPTargetDataDirective:
5442 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005443 case CXCursor_OMPTargetEnterDataDirective:
5444 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005445 case CXCursor_OMPTargetExitDataDirective:
5446 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005447 case CXCursor_OMPTargetParallelDirective:
5448 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005449 case CXCursor_OMPTargetParallelForDirective:
5450 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005451 case CXCursor_OMPTargetUpdateDirective:
5452 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005453 case CXCursor_OMPTeamsDirective:
5454 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005455 case CXCursor_OMPCancellationPointDirective:
5456 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005457 case CXCursor_OMPCancelDirective:
5458 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005459 case CXCursor_OMPTaskLoopDirective:
5460 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005461 case CXCursor_OMPTaskLoopSimdDirective:
5462 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005463 case CXCursor_OMPDistributeDirective:
5464 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005465 case CXCursor_OMPDistributeParallelForDirective:
5466 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005467 case CXCursor_OMPDistributeParallelForSimdDirective:
5468 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005469 case CXCursor_OMPDistributeSimdDirective:
5470 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005471 case CXCursor_OMPTargetParallelForSimdDirective:
5472 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005473 case CXCursor_OMPTargetSimdDirective:
5474 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005475 case CXCursor_OMPTeamsDistributeDirective:
5476 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005477 case CXCursor_OMPTeamsDistributeSimdDirective:
5478 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005479 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5480 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005481 case CXCursor_OMPTeamsDistributeParallelForDirective:
5482 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005483 case CXCursor_OMPTargetTeamsDirective:
5484 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005485 case CXCursor_OMPTargetTeamsDistributeDirective:
5486 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005487 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5488 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005489 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5490 return cxstring::createRef(
5491 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005492 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5493 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005494 case CXCursor_OverloadCandidate:
5495 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005496 case CXCursor_TypeAliasTemplateDecl:
5497 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005498 case CXCursor_StaticAssert:
5499 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005500 case CXCursor_FriendDecl:
Sven van Haastregtdc2c9302019-02-11 11:00:56 +00005501 return cxstring::createRef("FriendDecl");
5502 case CXCursor_ConvergentAttr:
5503 return cxstring::createRef("attribute(convergent)");
Emilio Cobos Alvarez0a3fe502019-02-25 21:24:52 +00005504 case CXCursor_WarnUnusedAttr:
5505 return cxstring::createRef("attribute(warn_unused)");
5506 case CXCursor_WarnUnusedResultAttr:
5507 return cxstring::createRef("attribute(warn_unused_result)");
Emilio Cobos Alvarezcd741272019-03-13 16:16:54 +00005508 case CXCursor_AlignedAttr:
5509 return cxstring::createRef("attribute(aligned)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005510 }
5511
5512 llvm_unreachable("Unhandled CXCursorKind");
5513}
5514
5515struct GetCursorData {
5516 SourceLocation TokenBeginLoc;
5517 bool PointsAtMacroArgExpansion;
5518 bool VisitedObjCPropertyImplDecl;
5519 SourceLocation VisitedDeclaratorDeclStartLoc;
5520 CXCursor &BestCursor;
5521
5522 GetCursorData(SourceManager &SM,
5523 SourceLocation tokenBegin, CXCursor &outputCursor)
5524 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5525 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5526 VisitedObjCPropertyImplDecl = false;
5527 }
5528};
5529
5530static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5531 CXCursor parent,
5532 CXClientData client_data) {
5533 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5534 CXCursor *BestCursor = &Data->BestCursor;
5535
5536 // If we point inside a macro argument we should provide info of what the
5537 // token is so use the actual cursor, don't replace it with a macro expansion
5538 // cursor.
5539 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5540 return CXChildVisit_Recurse;
5541
5542 if (clang_isDeclaration(cursor.kind)) {
5543 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005544 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005545 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5546 if (MD->isImplicit())
5547 return CXChildVisit_Break;
5548
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005549 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005550 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5551 // Check that when we have multiple @class references in the same line,
5552 // that later ones do not override the previous ones.
5553 // If we have:
5554 // @class Foo, Bar;
5555 // source ranges for both start at '@', so 'Bar' will end up overriding
5556 // 'Foo' even though the cursor location was at 'Foo'.
5557 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5558 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005559 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005560 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5561 if (PrevID != ID &&
5562 !PrevID->isThisDeclarationADefinition() &&
5563 !ID->isThisDeclarationADefinition())
5564 return CXChildVisit_Break;
5565 }
5566
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005567 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005568 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5569 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5570 // Check that when we have multiple declarators in the same line,
5571 // that later ones do not override the previous ones.
5572 // If we have:
5573 // int Foo, Bar;
5574 // source ranges for both start at 'int', so 'Bar' will end up overriding
5575 // 'Foo' even though the cursor location was at 'Foo'.
5576 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5577 return CXChildVisit_Break;
5578 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5579
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005580 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005581 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5582 (void)PropImp;
5583 // Check that when we have multiple @synthesize in the same line,
5584 // that later ones do not override the previous ones.
5585 // If we have:
5586 // @synthesize Foo, Bar;
5587 // source ranges for both start at '@', so 'Bar' will end up overriding
5588 // 'Foo' even though the cursor location was at 'Foo'.
5589 if (Data->VisitedObjCPropertyImplDecl)
5590 return CXChildVisit_Break;
5591 Data->VisitedObjCPropertyImplDecl = true;
5592 }
5593 }
5594
5595 if (clang_isExpression(cursor.kind) &&
5596 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005597 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005598 // Avoid having the cursor of an expression replace the declaration cursor
5599 // when the expression source range overlaps the declaration range.
5600 // This can happen for C++ constructor expressions whose range generally
5601 // include the variable declaration, e.g.:
5602 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5603 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5604 D->getLocation() == Data->TokenBeginLoc)
5605 return CXChildVisit_Break;
5606 }
5607 }
5608
5609 // If our current best cursor is the construction of a temporary object,
5610 // don't replace that cursor with a type reference, because we want
5611 // clang_getCursor() to point at the constructor.
5612 if (clang_isExpression(BestCursor->kind) &&
5613 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5614 cursor.kind == CXCursor_TypeRef) {
5615 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5616 // as having the actual point on the type reference.
5617 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5618 return CXChildVisit_Recurse;
5619 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005620
5621 // If we already have an Objective-C superclass reference, don't
5622 // update it further.
5623 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5624 return CXChildVisit_Break;
5625
Guy Benyei11169dd2012-12-18 14:30:41 +00005626 *BestCursor = cursor;
5627 return CXChildVisit_Recurse;
5628}
5629
5630CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005631 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005632 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005633 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005634 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005635
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005636 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005637 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5638
5639 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5640 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5641
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005642 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005643 CXFile SearchFile;
5644 unsigned SearchLine, SearchColumn;
5645 CXFile ResultFile;
5646 unsigned ResultLine, ResultColumn;
5647 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5648 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5649 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005650
5651 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5652 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005653 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005654 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005655 SearchFileName = clang_getFileName(SearchFile);
5656 ResultFileName = clang_getFileName(ResultFile);
5657 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5658 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005659 *Log << llvm::format("(%s:%d:%d) = %s",
5660 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5661 clang_getCString(KindSpelling))
5662 << llvm::format("(%s:%d:%d):%s%s",
5663 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5664 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005665 clang_disposeString(SearchFileName);
5666 clang_disposeString(ResultFileName);
5667 clang_disposeString(KindSpelling);
5668 clang_disposeString(USR);
5669
5670 CXCursor Definition = clang_getCursorDefinition(Result);
5671 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5672 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5673 CXString DefinitionKindSpelling
5674 = clang_getCursorKindSpelling(Definition.kind);
5675 CXFile DefinitionFile;
5676 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005677 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005678 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005679 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005680 *Log << llvm::format(" -> %s(%s:%d:%d)",
5681 clang_getCString(DefinitionKindSpelling),
5682 clang_getCString(DefinitionFileName),
5683 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005684 clang_disposeString(DefinitionFileName);
5685 clang_disposeString(DefinitionKindSpelling);
5686 }
5687 }
5688
5689 return Result;
5690}
5691
5692CXCursor clang_getNullCursor(void) {
5693 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5694}
5695
5696unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005697 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5698 // can't set consistently. For example, when visiting a DeclStmt we will set
5699 // it but we don't set it on the result of clang_getCursorDefinition for
5700 // a reference of the same declaration.
5701 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5702 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5703 // to provide that kind of info.
5704 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005705 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005706 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005707 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005708
Guy Benyei11169dd2012-12-18 14:30:41 +00005709 return X == Y;
5710}
5711
5712unsigned clang_hashCursor(CXCursor C) {
5713 unsigned Index = 0;
5714 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5715 Index = 1;
5716
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005717 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005718 std::make_pair(C.kind, C.data[Index]));
5719}
5720
5721unsigned clang_isInvalid(enum CXCursorKind K) {
5722 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5723}
5724
5725unsigned clang_isDeclaration(enum CXCursorKind K) {
5726 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005727 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5728}
5729
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005730unsigned clang_isInvalidDeclaration(CXCursor C) {
5731 if (clang_isDeclaration(C.kind)) {
5732 if (const Decl *D = getCursorDecl(C))
5733 return D->isInvalidDecl();
5734 }
5735
5736 return 0;
5737}
5738
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005739unsigned clang_isReference(enum CXCursorKind K) {
5740 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5741}
Guy Benyei11169dd2012-12-18 14:30:41 +00005742
5743unsigned clang_isExpression(enum CXCursorKind K) {
5744 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5745}
5746
5747unsigned clang_isStatement(enum CXCursorKind K) {
5748 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5749}
5750
5751unsigned clang_isAttribute(enum CXCursorKind K) {
5752 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5753}
5754
5755unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5756 return K == CXCursor_TranslationUnit;
5757}
5758
5759unsigned clang_isPreprocessing(enum CXCursorKind K) {
5760 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5761}
5762
5763unsigned clang_isUnexposed(enum CXCursorKind K) {
5764 switch (K) {
5765 case CXCursor_UnexposedDecl:
5766 case CXCursor_UnexposedExpr:
5767 case CXCursor_UnexposedStmt:
5768 case CXCursor_UnexposedAttr:
5769 return true;
5770 default:
5771 return false;
5772 }
5773}
5774
5775CXCursorKind clang_getCursorKind(CXCursor C) {
5776 return C.kind;
5777}
5778
5779CXSourceLocation clang_getCursorLocation(CXCursor C) {
5780 if (clang_isReference(C.kind)) {
5781 switch (C.kind) {
5782 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005783 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005784 = getCursorObjCSuperClassRef(C);
5785 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5786 }
5787
5788 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005789 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005790 = getCursorObjCProtocolRef(C);
5791 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5792 }
5793
5794 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005795 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005796 = getCursorObjCClassRef(C);
5797 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5798 }
5799
5800 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005801 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005802 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5803 }
5804
5805 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005806 std::pair<const TemplateDecl *, SourceLocation> P =
5807 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005808 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5809 }
5810
5811 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005812 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005813 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5814 }
5815
5816 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005817 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005818 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5819 }
5820
5821 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005822 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005823 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5824 }
5825
5826 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005827 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005828 if (!BaseSpec)
5829 return clang_getNullLocation();
5830
5831 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5832 return cxloc::translateSourceLocation(getCursorContext(C),
5833 TSInfo->getTypeLoc().getBeginLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005834
Guy Benyei11169dd2012-12-18 14:30:41 +00005835 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005836 BaseSpec->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005837 }
5838
5839 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005840 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005841 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5842 }
5843
5844 case CXCursor_OverloadedDeclRef:
5845 return cxloc::translateSourceLocation(getCursorContext(C),
5846 getCursorOverloadedDeclRef(C).second);
5847
5848 default:
5849 // FIXME: Need a way to enumerate all non-reference cases.
5850 llvm_unreachable("Missed a reference kind");
5851 }
5852 }
5853
5854 if (clang_isExpression(C.kind))
5855 return cxloc::translateSourceLocation(getCursorContext(C),
5856 getLocationFromExpr(getCursorExpr(C)));
5857
5858 if (clang_isStatement(C.kind))
5859 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005860 getCursorStmt(C)->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005861
5862 if (C.kind == CXCursor_PreprocessingDirective) {
5863 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5864 return cxloc::translateSourceLocation(getCursorContext(C), L);
5865 }
5866
5867 if (C.kind == CXCursor_MacroExpansion) {
5868 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005869 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005870 return cxloc::translateSourceLocation(getCursorContext(C), L);
5871 }
5872
5873 if (C.kind == CXCursor_MacroDefinition) {
5874 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5875 return cxloc::translateSourceLocation(getCursorContext(C), L);
5876 }
5877
5878 if (C.kind == CXCursor_InclusionDirective) {
5879 SourceLocation L
5880 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5881 return cxloc::translateSourceLocation(getCursorContext(C), L);
5882 }
5883
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005884 if (clang_isAttribute(C.kind)) {
5885 SourceLocation L
5886 = cxcursor::getCursorAttr(C)->getLocation();
5887 return cxloc::translateSourceLocation(getCursorContext(C), L);
5888 }
5889
Guy Benyei11169dd2012-12-18 14:30:41 +00005890 if (!clang_isDeclaration(C.kind))
5891 return clang_getNullLocation();
5892
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005893 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005894 if (!D)
5895 return clang_getNullLocation();
5896
5897 SourceLocation Loc = D->getLocation();
5898 // FIXME: Multiple variables declared in a single declaration
5899 // currently lack the information needed to correctly determine their
5900 // ranges when accounting for the type-specifier. We use context
5901 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5902 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005903 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005904 if (!cxcursor::isFirstInDeclGroup(C))
5905 Loc = VD->getLocation();
5906 }
5907
5908 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005909 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005910 Loc = MD->getSelectorStartLoc();
5911
5912 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5913}
5914
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005915} // end extern "C"
5916
Guy Benyei11169dd2012-12-18 14:30:41 +00005917CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5918 assert(TU);
5919
5920 // Guard against an invalid SourceLocation, or we may assert in one
5921 // of the following calls.
5922 if (SLoc.isInvalid())
5923 return clang_getNullCursor();
5924
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005925 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005926
5927 // Translate the given source location to make it point at the beginning of
5928 // the token under the cursor.
5929 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5930 CXXUnit->getASTContext().getLangOpts());
5931
5932 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5933 if (SLoc.isValid()) {
5934 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5935 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5936 /*VisitPreprocessorLast=*/true,
5937 /*VisitIncludedEntities=*/false,
5938 SourceLocation(SLoc));
5939 CursorVis.visitFileRegion();
5940 }
5941
5942 return Result;
5943}
5944
5945static SourceRange getRawCursorExtent(CXCursor C) {
5946 if (clang_isReference(C.kind)) {
5947 switch (C.kind) {
5948 case CXCursor_ObjCSuperClassRef:
5949 return getCursorObjCSuperClassRef(C).second;
5950
5951 case CXCursor_ObjCProtocolRef:
5952 return getCursorObjCProtocolRef(C).second;
5953
5954 case CXCursor_ObjCClassRef:
5955 return getCursorObjCClassRef(C).second;
5956
5957 case CXCursor_TypeRef:
5958 return getCursorTypeRef(C).second;
5959
5960 case CXCursor_TemplateRef:
5961 return getCursorTemplateRef(C).second;
5962
5963 case CXCursor_NamespaceRef:
5964 return getCursorNamespaceRef(C).second;
5965
5966 case CXCursor_MemberRef:
5967 return getCursorMemberRef(C).second;
5968
5969 case CXCursor_CXXBaseSpecifier:
5970 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5971
5972 case CXCursor_LabelRef:
5973 return getCursorLabelRef(C).second;
5974
5975 case CXCursor_OverloadedDeclRef:
5976 return getCursorOverloadedDeclRef(C).second;
5977
5978 case CXCursor_VariableRef:
5979 return getCursorVariableRef(C).second;
5980
5981 default:
5982 // FIXME: Need a way to enumerate all non-reference cases.
5983 llvm_unreachable("Missed a reference kind");
5984 }
5985 }
5986
5987 if (clang_isExpression(C.kind))
5988 return getCursorExpr(C)->getSourceRange();
5989
5990 if (clang_isStatement(C.kind))
5991 return getCursorStmt(C)->getSourceRange();
5992
5993 if (clang_isAttribute(C.kind))
5994 return getCursorAttr(C)->getRange();
5995
5996 if (C.kind == CXCursor_PreprocessingDirective)
5997 return cxcursor::getCursorPreprocessingDirective(C);
5998
5999 if (C.kind == CXCursor_MacroExpansion) {
6000 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00006001 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00006002 return TU->mapRangeFromPreamble(Range);
6003 }
6004
6005 if (C.kind == CXCursor_MacroDefinition) {
6006 ASTUnit *TU = getCursorASTUnit(C);
6007 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
6008 return TU->mapRangeFromPreamble(Range);
6009 }
6010
6011 if (C.kind == CXCursor_InclusionDirective) {
6012 ASTUnit *TU = getCursorASTUnit(C);
6013 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
6014 return TU->mapRangeFromPreamble(Range);
6015 }
6016
6017 if (C.kind == CXCursor_TranslationUnit) {
6018 ASTUnit *TU = getCursorASTUnit(C);
6019 FileID MainID = TU->getSourceManager().getMainFileID();
6020 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
6021 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
6022 return SourceRange(Start, End);
6023 }
6024
6025 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006026 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006027 if (!D)
6028 return SourceRange();
6029
6030 SourceRange R = D->getSourceRange();
6031 // FIXME: Multiple variables declared in a single declaration
6032 // currently lack the information needed to correctly determine their
6033 // ranges when accounting for the type-specifier. We use context
6034 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6035 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006036 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006037 if (!cxcursor::isFirstInDeclGroup(C))
6038 R.setBegin(VD->getLocation());
6039 }
6040 return R;
6041 }
6042 return SourceRange();
6043}
6044
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006045/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00006046/// the decl-specifier-seq for declarations.
6047static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6048 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006049 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006050 if (!D)
6051 return SourceRange();
6052
6053 SourceRange R = D->getSourceRange();
6054
6055 // Adjust the start of the location for declarations preceded by
6056 // declaration specifiers.
6057 SourceLocation StartLoc;
6058 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6059 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006060 StartLoc = TI->getTypeLoc().getBeginLoc();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006061 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006062 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006063 StartLoc = TI->getTypeLoc().getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006064 }
6065
6066 if (StartLoc.isValid() && R.getBegin().isValid() &&
6067 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6068 R.setBegin(StartLoc);
6069
6070 // FIXME: Multiple variables declared in a single declaration
6071 // currently lack the information needed to correctly determine their
6072 // ranges when accounting for the type-specifier. We use context
6073 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6074 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006075 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006076 if (!cxcursor::isFirstInDeclGroup(C))
6077 R.setBegin(VD->getLocation());
6078 }
6079
6080 return R;
6081 }
6082
6083 return getRawCursorExtent(C);
6084}
6085
Guy Benyei11169dd2012-12-18 14:30:41 +00006086CXSourceRange clang_getCursorExtent(CXCursor C) {
6087 SourceRange R = getRawCursorExtent(C);
6088 if (R.isInvalid())
6089 return clang_getNullRange();
6090
6091 return cxloc::translateSourceRange(getCursorContext(C), R);
6092}
6093
6094CXCursor clang_getCursorReferenced(CXCursor C) {
6095 if (clang_isInvalid(C.kind))
6096 return clang_getNullCursor();
6097
6098 CXTranslationUnit tu = getCursorTU(C);
6099 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006100 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006101 if (!D)
6102 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006103 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006104 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006105 if (const ObjCPropertyImplDecl *PropImpl =
6106 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006107 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6108 return MakeCXCursor(Property, tu);
6109
6110 return C;
6111 }
6112
6113 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006114 const Expr *E = getCursorExpr(C);
6115 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006116 if (D) {
6117 CXCursor declCursor = MakeCXCursor(D, tu);
6118 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6119 declCursor);
6120 return declCursor;
6121 }
6122
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006123 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006124 return MakeCursorOverloadedDeclRef(Ovl, tu);
6125
6126 return clang_getNullCursor();
6127 }
6128
6129 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006130 const Stmt *S = getCursorStmt(C);
6131 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006132 if (LabelDecl *label = Goto->getLabel())
6133 if (LabelStmt *labelS = label->getStmt())
6134 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6135
6136 return clang_getNullCursor();
6137 }
Richard Smith66a81862015-05-04 02:25:31 +00006138
Guy Benyei11169dd2012-12-18 14:30:41 +00006139 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006140 if (const MacroDefinitionRecord *Def =
6141 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006142 return MakeMacroDefinitionCursor(Def, tu);
6143 }
6144
6145 if (!clang_isReference(C.kind))
6146 return clang_getNullCursor();
6147
6148 switch (C.kind) {
6149 case CXCursor_ObjCSuperClassRef:
6150 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6151
6152 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006153 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6154 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006155 return MakeCXCursor(Def, tu);
6156
6157 return MakeCXCursor(Prot, tu);
6158 }
6159
6160 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006161 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6162 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006163 return MakeCXCursor(Def, tu);
6164
6165 return MakeCXCursor(Class, tu);
6166 }
6167
6168 case CXCursor_TypeRef:
6169 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6170
6171 case CXCursor_TemplateRef:
6172 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6173
6174 case CXCursor_NamespaceRef:
6175 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6176
6177 case CXCursor_MemberRef:
6178 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6179
6180 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006181 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006182 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6183 tu ));
6184 }
6185
6186 case CXCursor_LabelRef:
6187 // FIXME: We end up faking the "parent" declaration here because we
6188 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006189 return MakeCXCursor(getCursorLabelRef(C).first,
6190 cxtu::getASTUnit(tu)->getASTContext()
6191 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006192 tu);
6193
6194 case CXCursor_OverloadedDeclRef:
6195 return C;
6196
6197 case CXCursor_VariableRef:
6198 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6199
6200 default:
6201 // We would prefer to enumerate all non-reference cursor kinds here.
6202 llvm_unreachable("Unhandled reference cursor kind");
6203 }
6204}
6205
6206CXCursor clang_getCursorDefinition(CXCursor C) {
6207 if (clang_isInvalid(C.kind))
6208 return clang_getNullCursor();
6209
6210 CXTranslationUnit TU = getCursorTU(C);
6211
6212 bool WasReference = false;
6213 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6214 C = clang_getCursorReferenced(C);
6215 WasReference = true;
6216 }
6217
6218 if (C.kind == CXCursor_MacroExpansion)
6219 return clang_getCursorReferenced(C);
6220
6221 if (!clang_isDeclaration(C.kind))
6222 return clang_getNullCursor();
6223
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006224 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006225 if (!D)
6226 return clang_getNullCursor();
6227
6228 switch (D->getKind()) {
6229 // Declaration kinds that don't really separate the notions of
6230 // declaration and definition.
6231 case Decl::Namespace:
6232 case Decl::Typedef:
6233 case Decl::TypeAlias:
6234 case Decl::TypeAliasTemplate:
6235 case Decl::TemplateTypeParm:
6236 case Decl::EnumConstant:
6237 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006238 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006239 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006240 case Decl::IndirectField:
6241 case Decl::ObjCIvar:
6242 case Decl::ObjCAtDefsField:
6243 case Decl::ImplicitParam:
6244 case Decl::ParmVar:
6245 case Decl::NonTypeTemplateParm:
6246 case Decl::TemplateTemplateParm:
6247 case Decl::ObjCCategoryImpl:
6248 case Decl::ObjCImplementation:
6249 case Decl::AccessSpec:
6250 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006251 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006252 case Decl::ObjCPropertyImpl:
6253 case Decl::FileScopeAsm:
6254 case Decl::StaticAssert:
6255 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006256 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006257 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006258 case Decl::Label: // FIXME: Is this right??
6259 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006260 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006261 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006262 case Decl::OMPThreadPrivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00006263 case Decl::OMPAllocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006264 case Decl::OMPDeclareReduction:
Michael Kruse251e1482019-02-01 20:25:04 +00006265 case Decl::OMPDeclareMapper:
Kelvin Li1408f912018-09-26 04:28:39 +00006266 case Decl::OMPRequires:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006267 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006268 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006269 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006270 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006271 case Decl::UsingPack:
Guy Benyei11169dd2012-12-18 14:30:41 +00006272 return C;
6273
6274 // Declaration kinds that don't make any sense here, but are
6275 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006276 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006277 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006278 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006279 break;
6280
6281 // Declaration kinds for which the definition is not resolvable.
6282 case Decl::UnresolvedUsingTypename:
6283 case Decl::UnresolvedUsingValue:
6284 break;
6285
6286 case Decl::UsingDirective:
6287 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6288 TU);
6289
6290 case Decl::NamespaceAlias:
6291 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6292
6293 case Decl::Enum:
6294 case Decl::Record:
6295 case Decl::CXXRecord:
6296 case Decl::ClassTemplateSpecialization:
6297 case Decl::ClassTemplatePartialSpecialization:
6298 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6299 return MakeCXCursor(Def, TU);
6300 return clang_getNullCursor();
6301
6302 case Decl::Function:
6303 case Decl::CXXMethod:
6304 case Decl::CXXConstructor:
6305 case Decl::CXXDestructor:
6306 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006307 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006308 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006309 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006310 return clang_getNullCursor();
6311 }
6312
Larisse Voufo39a1e502013-08-06 01:03:05 +00006313 case Decl::Var:
6314 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006315 case Decl::VarTemplatePartialSpecialization:
6316 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006317 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006318 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006319 return MakeCXCursor(Def, TU);
6320 return clang_getNullCursor();
6321 }
6322
6323 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006324 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006325 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6326 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6327 return clang_getNullCursor();
6328 }
6329
6330 case Decl::ClassTemplate: {
6331 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6332 ->getDefinition())
6333 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6334 TU);
6335 return clang_getNullCursor();
6336 }
6337
Larisse Voufo39a1e502013-08-06 01:03:05 +00006338 case Decl::VarTemplate: {
6339 if (VarDecl *Def =
6340 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6341 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6342 return clang_getNullCursor();
6343 }
6344
Guy Benyei11169dd2012-12-18 14:30:41 +00006345 case Decl::Using:
6346 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6347 D->getLocation(), TU);
6348
6349 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006350 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006351 return clang_getCursorDefinition(
6352 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6353 TU));
6354
6355 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006356 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006357 if (Method->isThisDeclarationADefinition())
6358 return C;
6359
6360 // Dig out the method definition in the associated
6361 // @implementation, if we have it.
6362 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006363 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006364 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6365 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6366 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6367 Method->isInstanceMethod()))
6368 if (Def->isThisDeclarationADefinition())
6369 return MakeCXCursor(Def, TU);
6370
6371 return clang_getNullCursor();
6372 }
6373
6374 case Decl::ObjCCategory:
6375 if (ObjCCategoryImplDecl *Impl
6376 = cast<ObjCCategoryDecl>(D)->getImplementation())
6377 return MakeCXCursor(Impl, TU);
6378 return clang_getNullCursor();
6379
6380 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006381 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006382 return MakeCXCursor(Def, TU);
6383 return clang_getNullCursor();
6384
6385 case Decl::ObjCInterface: {
6386 // There are two notions of a "definition" for an Objective-C
6387 // class: the interface and its implementation. When we resolved a
6388 // reference to an Objective-C class, produce the @interface as
6389 // the definition; when we were provided with the interface,
6390 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006391 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006392 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006393 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006394 return MakeCXCursor(Def, TU);
6395 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6396 return MakeCXCursor(Impl, TU);
6397 return clang_getNullCursor();
6398 }
6399
6400 case Decl::ObjCProperty:
6401 // FIXME: We don't really know where to find the
6402 // ObjCPropertyImplDecls that implement this property.
6403 return clang_getNullCursor();
6404
6405 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006406 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006407 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006408 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006409 return MakeCXCursor(Def, TU);
6410
6411 return clang_getNullCursor();
6412
6413 case Decl::Friend:
6414 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6415 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6416 return clang_getNullCursor();
6417
6418 case Decl::FriendTemplate:
6419 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6420 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6421 return clang_getNullCursor();
6422 }
6423
6424 return clang_getNullCursor();
6425}
6426
6427unsigned clang_isCursorDefinition(CXCursor C) {
6428 if (!clang_isDeclaration(C.kind))
6429 return 0;
6430
6431 return clang_getCursorDefinition(C) == C;
6432}
6433
6434CXCursor clang_getCanonicalCursor(CXCursor C) {
6435 if (!clang_isDeclaration(C.kind))
6436 return C;
6437
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006438 if (const Decl *D = getCursorDecl(C)) {
6439 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006440 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6441 return MakeCXCursor(CatD, getCursorTU(C));
6442
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006443 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6444 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006445 return MakeCXCursor(IFD, getCursorTU(C));
6446
6447 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6448 }
6449
6450 return C;
6451}
6452
6453int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6454 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6455}
6456
6457unsigned clang_getNumOverloadedDecls(CXCursor C) {
6458 if (C.kind != CXCursor_OverloadedDeclRef)
6459 return 0;
6460
6461 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006462 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006463 return E->getNumDecls();
6464
6465 if (OverloadedTemplateStorage *S
6466 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6467 return S->size();
6468
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006469 const Decl *D = Storage.get<const Decl *>();
6470 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006471 return Using->shadow_size();
6472
6473 return 0;
6474}
6475
6476CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6477 if (cursor.kind != CXCursor_OverloadedDeclRef)
6478 return clang_getNullCursor();
6479
6480 if (index >= clang_getNumOverloadedDecls(cursor))
6481 return clang_getNullCursor();
6482
6483 CXTranslationUnit TU = getCursorTU(cursor);
6484 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006485 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006486 return MakeCXCursor(E->decls_begin()[index], TU);
6487
6488 if (OverloadedTemplateStorage *S
6489 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6490 return MakeCXCursor(S->begin()[index], TU);
6491
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006492 const Decl *D = Storage.get<const Decl *>();
6493 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006494 // FIXME: This is, unfortunately, linear time.
6495 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6496 std::advance(Pos, index);
6497 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6498 }
6499
6500 return clang_getNullCursor();
6501}
6502
6503void clang_getDefinitionSpellingAndExtent(CXCursor C,
6504 const char **startBuf,
6505 const char **endBuf,
6506 unsigned *startLine,
6507 unsigned *startColumn,
6508 unsigned *endLine,
6509 unsigned *endColumn) {
6510 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006511 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006512 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6513
6514 SourceManager &SM = FD->getASTContext().getSourceManager();
6515 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6516 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6517 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6518 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6519 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6520 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6521}
6522
6523
6524CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6525 unsigned PieceIndex) {
6526 RefNamePieces Pieces;
6527
6528 switch (C.kind) {
6529 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006530 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006531 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6532 E->getQualifierLoc().getSourceRange());
6533 break;
6534
6535 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006536 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6537 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6538 Pieces =
6539 buildPieces(NameFlags, false, E->getNameInfo(),
6540 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6541 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006542 break;
6543
6544 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006545 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006546 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006547 const Expr *Callee = OCE->getCallee();
6548 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006549 Callee = ICE->getSubExpr();
6550
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006551 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006552 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6553 DRE->getQualifierLoc().getSourceRange());
6554 }
6555 break;
6556
6557 default:
6558 break;
6559 }
6560
6561 if (Pieces.empty()) {
6562 if (PieceIndex == 0)
6563 return clang_getCursorExtent(C);
6564 } else if (PieceIndex < Pieces.size()) {
6565 SourceRange R = Pieces[PieceIndex];
6566 if (R.isValid())
6567 return cxloc::translateSourceRange(getCursorContext(C), R);
6568 }
6569
6570 return clang_getNullRange();
6571}
6572
6573void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006574 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6575 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006576}
6577
6578void clang_executeOnThread(void (*fn)(void*), void *user_data,
6579 unsigned stack_size) {
6580 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6581}
6582
Guy Benyei11169dd2012-12-18 14:30:41 +00006583//===----------------------------------------------------------------------===//
6584// Token-based Operations.
6585//===----------------------------------------------------------------------===//
6586
6587/* CXToken layout:
6588 * int_data[0]: a CXTokenKind
6589 * int_data[1]: starting token location
6590 * int_data[2]: token length
6591 * int_data[3]: reserved
6592 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6593 * otherwise unused.
6594 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006595CXTokenKind clang_getTokenKind(CXToken CXTok) {
6596 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6597}
6598
6599CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6600 switch (clang_getTokenKind(CXTok)) {
6601 case CXToken_Identifier:
6602 case CXToken_Keyword:
6603 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006604 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006605 ->getNameStart());
6606
6607 case CXToken_Literal: {
6608 // We have stashed the starting pointer in the ptr_data field. Use it.
6609 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006610 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006611 }
6612
6613 case CXToken_Punctuation:
6614 case CXToken_Comment:
6615 break;
6616 }
6617
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006618 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006619 LOG_BAD_TU(TU);
6620 return cxstring::createEmpty();
6621 }
6622
Guy Benyei11169dd2012-12-18 14:30:41 +00006623 // We have to find the starting buffer pointer the hard way, by
6624 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006625 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006626 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006627 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006628
6629 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6630 std::pair<FileID, unsigned> LocInfo
6631 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6632 bool Invalid = false;
6633 StringRef Buffer
6634 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6635 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006636 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006637
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006638 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006639}
6640
6641CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006642 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006643 LOG_BAD_TU(TU);
6644 return clang_getNullLocation();
6645 }
6646
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006647 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006648 if (!CXXUnit)
6649 return clang_getNullLocation();
6650
6651 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6652 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6653}
6654
6655CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006656 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006657 LOG_BAD_TU(TU);
6658 return clang_getNullRange();
6659 }
6660
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006661 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006662 if (!CXXUnit)
6663 return clang_getNullRange();
6664
6665 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6666 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6667}
6668
6669static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6670 SmallVectorImpl<CXToken> &CXTokens) {
6671 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6672 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006673 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006674 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006675 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006676
6677 // Cannot tokenize across files.
6678 if (BeginLocInfo.first != EndLocInfo.first)
6679 return;
6680
6681 // Create a lexer
6682 bool Invalid = false;
6683 StringRef Buffer
6684 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6685 if (Invalid)
6686 return;
6687
6688 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6689 CXXUnit->getASTContext().getLangOpts(),
6690 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6691 Lex.SetCommentRetentionState(true);
6692
6693 // Lex tokens until we hit the end of the range.
6694 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6695 Token Tok;
6696 bool previousWasAt = false;
6697 do {
6698 // Lex the next token
6699 Lex.LexFromRawLexer(Tok);
6700 if (Tok.is(tok::eof))
6701 break;
6702
6703 // Initialize the CXToken.
6704 CXToken CXTok;
6705
6706 // - Common fields
6707 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6708 CXTok.int_data[2] = Tok.getLength();
6709 CXTok.int_data[3] = 0;
6710
6711 // - Kind-specific fields
6712 if (Tok.isLiteral()) {
6713 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006714 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006715 } else if (Tok.is(tok::raw_identifier)) {
6716 // Lookup the identifier to determine whether we have a keyword.
6717 IdentifierInfo *II
6718 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6719
6720 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6721 CXTok.int_data[0] = CXToken_Keyword;
6722 }
6723 else {
6724 CXTok.int_data[0] = Tok.is(tok::identifier)
6725 ? CXToken_Identifier
6726 : CXToken_Keyword;
6727 }
6728 CXTok.ptr_data = II;
6729 } else if (Tok.is(tok::comment)) {
6730 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006731 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006732 } else {
6733 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006734 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006735 }
6736 CXTokens.push_back(CXTok);
6737 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006738 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006739}
6740
Ivan Donchevskii3957e482018-06-13 12:37:08 +00006741CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6742 LOG_FUNC_SECTION {
6743 *Log << TU << ' ' << Location;
6744 }
6745
6746 if (isNotUsableTU(TU)) {
6747 LOG_BAD_TU(TU);
6748 return NULL;
6749 }
6750
6751 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6752 if (!CXXUnit)
6753 return NULL;
6754
6755 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6756 if (Begin.isInvalid())
6757 return NULL;
6758 SourceManager &SM = CXXUnit->getSourceManager();
6759 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6760 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6761
6762 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6763
6764 SmallVector<CXToken, 32> CXTokens;
6765 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6766
6767 if (CXTokens.empty())
6768 return NULL;
6769
6770 CXTokens.resize(1);
6771 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6772
6773 memmove(Token, CXTokens.data(), sizeof(CXToken));
6774 return Token;
6775}
6776
Guy Benyei11169dd2012-12-18 14:30:41 +00006777void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6778 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006779 LOG_FUNC_SECTION {
6780 *Log << TU << ' ' << Range;
6781 }
6782
Guy Benyei11169dd2012-12-18 14:30:41 +00006783 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006784 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006785 if (NumTokens)
6786 *NumTokens = 0;
6787
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006788 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006789 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006790 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006791 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006792
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006793 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006794 if (!CXXUnit || !Tokens || !NumTokens)
6795 return;
6796
6797 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6798
6799 SourceRange R = cxloc::translateCXSourceRange(Range);
6800 if (R.isInvalid())
6801 return;
6802
6803 SmallVector<CXToken, 32> CXTokens;
6804 getTokens(CXXUnit, R, CXTokens);
6805
6806 if (CXTokens.empty())
6807 return;
6808
Serge Pavlov52525732018-02-21 02:02:39 +00006809 *Tokens = static_cast<CXToken *>(
6810 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006811 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6812 *NumTokens = CXTokens.size();
6813}
6814
6815void clang_disposeTokens(CXTranslationUnit TU,
6816 CXToken *Tokens, unsigned NumTokens) {
6817 free(Tokens);
6818}
6819
Guy Benyei11169dd2012-12-18 14:30:41 +00006820//===----------------------------------------------------------------------===//
6821// Token annotation APIs.
6822//===----------------------------------------------------------------------===//
6823
Guy Benyei11169dd2012-12-18 14:30:41 +00006824static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6825 CXCursor parent,
6826 CXClientData client_data);
6827static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6828 CXClientData client_data);
6829
6830namespace {
6831class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006832 CXToken *Tokens;
6833 CXCursor *Cursors;
6834 unsigned NumTokens;
6835 unsigned TokIdx;
6836 unsigned PreprocessingTokIdx;
6837 CursorVisitor AnnotateVis;
6838 SourceManager &SrcMgr;
6839 bool HasContextSensitiveKeywords;
6840
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006841 struct PostChildrenAction {
6842 CXCursor cursor;
6843 enum Action { Invalid, Ignore, Postpone } action;
6844 };
6845 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
6846
Guy Benyei11169dd2012-12-18 14:30:41 +00006847 struct PostChildrenInfo {
6848 CXCursor Cursor;
6849 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006850 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006851 unsigned BeforeChildrenTokenIdx;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006852 PostChildrenActions ChildActions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006853 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006854 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006855
6856 CXToken &getTok(unsigned Idx) {
6857 assert(Idx < NumTokens);
6858 return Tokens[Idx];
6859 }
6860 const CXToken &getTok(unsigned Idx) const {
6861 assert(Idx < NumTokens);
6862 return Tokens[Idx];
6863 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006864 bool MoreTokens() const { return TokIdx < NumTokens; }
6865 unsigned NextToken() const { return TokIdx; }
6866 void AdvanceToken() { ++TokIdx; }
6867 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006868 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006869 }
6870 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006871 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006872 }
6873 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006874 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006875 }
6876
6877 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006878 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006879 SourceRange);
6880
6881public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006882 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006883 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006884 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006885 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006886 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006887 AnnotateTokensVisitor, this,
6888 /*VisitPreprocessorLast=*/true,
6889 /*VisitIncludedEntities=*/false,
6890 RegionOfInterest,
6891 /*VisitDeclsOnly=*/false,
6892 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006893 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006894 HasContextSensitiveKeywords(false) { }
6895
6896 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6897 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006898 bool IsIgnoredChildCursor(CXCursor cursor) const;
6899 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
6900
Guy Benyei11169dd2012-12-18 14:30:41 +00006901 bool postVisitChildren(CXCursor cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006902 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
6903 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
6904
Guy Benyei11169dd2012-12-18 14:30:41 +00006905 void AnnotateTokens();
6906
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006907 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00006908 /// context-sensitive keywords.
6909 bool hasContextSensitiveKeywords() const {
6910 return HasContextSensitiveKeywords;
6911 }
6912
6913 ~AnnotateTokensWorker() {
6914 assert(PostChildrenInfos.empty());
6915 }
6916};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006917}
Guy Benyei11169dd2012-12-18 14:30:41 +00006918
6919void AnnotateTokensWorker::AnnotateTokens() {
6920 // Walk the AST within the region of interest, annotating tokens
6921 // along the way.
6922 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006923}
Guy Benyei11169dd2012-12-18 14:30:41 +00006924
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006925bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
6926 if (PostChildrenInfos.empty())
6927 return false;
6928
6929 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
6930 if (ChildAction.cursor == cursor &&
6931 ChildAction.action == PostChildrenAction::Ignore) {
6932 return true;
6933 }
6934 }
6935
6936 return false;
6937}
6938
6939const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
6940 if (!clang_isExpression(Cursor.kind))
6941 return nullptr;
6942
6943 const Expr *E = getCursorExpr(Cursor);
6944 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
6945 const OverloadedOperatorKind Kind = OCE->getOperator();
6946 if (Kind == OO_Call || Kind == OO_Subscript)
6947 return OCE;
6948 }
6949
6950 return nullptr;
6951}
6952
6953AnnotateTokensWorker::PostChildrenActions
6954AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
6955 PostChildrenActions actions;
6956
6957 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
6958 // visited before the arguments to the operator call. For the Call and
6959 // Subscript operator the range of this DeclRefExpr includes the whole call
6960 // expression, so that all tokens in that range would be mapped to the
6961 // operator function, including the tokens of the arguments. To avoid that,
6962 // ensure to visit this DeclRefExpr as last node.
6963 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
6964 const Expr *Callee = OCE->getCallee();
6965 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
6966 const Expr *SubExpr = ICE->getSubExpr();
6967 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
Fangrui Songcabb36d2018-11-20 08:00:00 +00006968 const Decl *parentDecl = getCursorDecl(Cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006969 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
6970
6971 // Visit the DeclRefExpr as last.
6972 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
6973 actions.push_back({cxChild, PostChildrenAction::Postpone});
6974
6975 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
6976 // wide range as the DeclRefExpr. We can skip visiting this entirely.
6977 cxChild = MakeCXCursor(ICE, parentDecl, TU);
6978 actions.push_back({cxChild, PostChildrenAction::Ignore});
6979 }
6980 }
6981 }
6982
6983 return actions;
6984}
6985
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006986static inline void updateCursorAnnotation(CXCursor &Cursor,
6987 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006988 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006989 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006990 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006991}
6992
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006993/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00006994//// between the cursor location and the source range is the same as
6995/// \arg compResult.
6996///
6997/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6998/// Pass RangeOverlap to annotate tokens inside a range.
6999void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
7000 RangeComparisonResult compResult,
7001 SourceRange range) {
7002 while (MoreTokens()) {
7003 const unsigned I = NextToken();
7004 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007005 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
7006 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00007007
7008 SourceLocation TokLoc = GetTokenLoc(I);
7009 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007010 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007011 AdvanceToken();
7012 continue;
7013 }
7014 break;
7015 }
7016}
7017
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007018/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007019/// \returns true if it advanced beyond all macro tokens, false otherwise.
7020bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00007021 CXCursor updateC,
7022 RangeComparisonResult compResult,
7023 SourceRange range) {
7024 assert(MoreTokens());
7025 assert(isFunctionMacroToken(NextToken()) &&
7026 "Should be called only for macro arg tokens");
7027
7028 // This works differently than annotateAndAdvanceTokens; because expanded
7029 // macro arguments can have arbitrary translation-unit source order, we do not
7030 // advance the token index one by one until a token fails the range test.
7031 // We only advance once past all of the macro arg tokens if all of them
7032 // pass the range test. If one of them fails we keep the token index pointing
7033 // at the start of the macro arg tokens so that the failing token will be
7034 // annotated by a subsequent annotation try.
7035
7036 bool atLeastOneCompFail = false;
7037
7038 unsigned I = NextToken();
7039 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7040 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7041 if (TokLoc.isFileID())
7042 continue; // not macro arg token, it's parens or comma.
7043 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7044 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7045 Cursors[I] = updateC;
7046 } else
7047 atLeastOneCompFail = true;
7048 }
7049
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007050 if (atLeastOneCompFail)
7051 return false;
7052
7053 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7054 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00007055}
7056
7057enum CXChildVisitResult
7058AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007059 SourceRange cursorRange = getRawCursorExtent(cursor);
7060 if (cursorRange.isInvalid())
7061 return CXChildVisit_Recurse;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007062
7063 if (IsIgnoredChildCursor(cursor))
7064 return CXChildVisit_Continue;
7065
Guy Benyei11169dd2012-12-18 14:30:41 +00007066 if (!HasContextSensitiveKeywords) {
7067 // Objective-C properties can have context-sensitive keywords.
7068 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007069 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007070 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7071 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7072 }
7073 // Objective-C methods can have context-sensitive keywords.
7074 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7075 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007076 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007077 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7078 if (Method->getObjCDeclQualifier())
7079 HasContextSensitiveKeywords = true;
7080 else {
David Majnemer59f77922016-06-24 04:05:48 +00007081 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00007082 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007083 HasContextSensitiveKeywords = true;
7084 break;
7085 }
7086 }
7087 }
7088 }
7089 }
7090 // C++ methods can have context-sensitive keywords.
7091 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007092 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007093 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7094 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7095 HasContextSensitiveKeywords = true;
7096 }
7097 }
7098 // C++ classes can have context-sensitive keywords.
7099 else if (cursor.kind == CXCursor_StructDecl ||
7100 cursor.kind == CXCursor_ClassDecl ||
7101 cursor.kind == CXCursor_ClassTemplate ||
7102 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007103 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007104 if (D->hasAttr<FinalAttr>())
7105 HasContextSensitiveKeywords = true;
7106 }
7107 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00007108
7109 // Don't override a property annotation with its getter/setter method.
7110 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7111 parent.kind == CXCursor_ObjCPropertyDecl)
7112 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007113
7114 if (clang_isPreprocessing(cursor.kind)) {
7115 // Items in the preprocessing record are kept separate from items in
7116 // declarations, so we keep a separate token index.
7117 unsigned SavedTokIdx = TokIdx;
7118 TokIdx = PreprocessingTokIdx;
7119
7120 // Skip tokens up until we catch up to the beginning of the preprocessing
7121 // entry.
7122 while (MoreTokens()) {
7123 const unsigned I = NextToken();
7124 SourceLocation TokLoc = GetTokenLoc(I);
7125 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7126 case RangeBefore:
7127 AdvanceToken();
7128 continue;
7129 case RangeAfter:
7130 case RangeOverlap:
7131 break;
7132 }
7133 break;
7134 }
7135
7136 // Look at all of the tokens within this range.
7137 while (MoreTokens()) {
7138 const unsigned I = NextToken();
7139 SourceLocation TokLoc = GetTokenLoc(I);
7140 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7141 case RangeBefore:
7142 llvm_unreachable("Infeasible");
7143 case RangeAfter:
7144 break;
7145 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007146 // For macro expansions, just note where the beginning of the macro
7147 // expansion occurs.
7148 if (cursor.kind == CXCursor_MacroExpansion) {
7149 if (TokLoc == cursorRange.getBegin())
7150 Cursors[I] = cursor;
7151 AdvanceToken();
7152 break;
7153 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007154 // We may have already annotated macro names inside macro definitions.
7155 if (Cursors[I].kind != CXCursor_MacroExpansion)
7156 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007157 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007158 continue;
7159 }
7160 break;
7161 }
7162
7163 // Save the preprocessing token index; restore the non-preprocessing
7164 // token index.
7165 PreprocessingTokIdx = TokIdx;
7166 TokIdx = SavedTokIdx;
7167 return CXChildVisit_Recurse;
7168 }
7169
7170 if (cursorRange.isInvalid())
7171 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007172
7173 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007174 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007175 const enum CXCursorKind K = clang_getCursorKind(parent);
7176 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007177 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7178 // Attributes are annotated out-of-order, skip tokens until we reach it.
7179 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007180 ? clang_getNullCursor() : parent;
7181
7182 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7183
7184 // Avoid having the cursor of an expression "overwrite" the annotation of the
7185 // variable declaration that it belongs to.
7186 // This can happen for C++ constructor expressions whose range generally
7187 // include the variable declaration, e.g.:
7188 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007189 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00007190 const Expr *E = getCursorExpr(cursor);
Fangrui Songcabb36d2018-11-20 08:00:00 +00007191 if (const Decl *D = getCursorDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007192 const unsigned I = NextToken();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007193 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7194 E->getBeginLoc() == D->getLocation() &&
7195 E->getBeginLoc() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007196 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007197 AdvanceToken();
7198 }
7199 }
7200 }
7201
7202 // Before recursing into the children keep some state that we are going
7203 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7204 // extra work after the child nodes are visited.
7205 // Note that we don't call VisitChildren here to avoid traversing statements
7206 // code-recursively which can blow the stack.
7207
7208 PostChildrenInfo Info;
7209 Info.Cursor = cursor;
7210 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007211 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007212 Info.BeforeChildrenTokenIdx = NextToken();
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007213 Info.ChildActions = DetermineChildActions(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007214 PostChildrenInfos.push_back(Info);
7215
7216 return CXChildVisit_Recurse;
7217}
7218
7219bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7220 if (PostChildrenInfos.empty())
7221 return false;
7222 const PostChildrenInfo &Info = PostChildrenInfos.back();
7223 if (!clang_equalCursors(Info.Cursor, cursor))
7224 return false;
7225
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007226 HandlePostPonedChildCursors(Info);
7227
Guy Benyei11169dd2012-12-18 14:30:41 +00007228 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7229 const unsigned AfterChildren = NextToken();
7230 SourceRange cursorRange = Info.CursorRange;
7231
7232 // Scan the tokens that are at the end of the cursor, but are not captured
7233 // but the child cursors.
7234 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7235
7236 // Scan the tokens that are at the beginning of the cursor, but are not
7237 // capture by the child cursors.
7238 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7239 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7240 break;
7241
7242 Cursors[I] = cursor;
7243 }
7244
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007245 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7246 // encountered the attribute cursor.
7247 if (clang_isAttribute(cursor.kind))
7248 TokIdx = Info.BeforeReachingCursorIdx;
7249
Guy Benyei11169dd2012-12-18 14:30:41 +00007250 PostChildrenInfos.pop_back();
7251 return false;
7252}
7253
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007254void AnnotateTokensWorker::HandlePostPonedChildCursors(
7255 const PostChildrenInfo &Info) {
7256 for (const auto &ChildAction : Info.ChildActions) {
7257 if (ChildAction.action == PostChildrenAction::Postpone) {
7258 HandlePostPonedChildCursor(ChildAction.cursor,
7259 Info.BeforeChildrenTokenIdx);
7260 }
7261 }
7262}
7263
7264void AnnotateTokensWorker::HandlePostPonedChildCursor(
7265 CXCursor Cursor, unsigned StartTokenIndex) {
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007266 unsigned I = StartTokenIndex;
7267
7268 // The bracket tokens of a Call or Subscript operator are mapped to
7269 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7270 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7271 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
Nikolai Kosjar2a647e72019-05-08 13:19:29 +00007272 const CXSourceRange CXRefNameRange = clang_getCursorReferenceNameRange(
7273 Cursor, CXNameRange_WantQualifier, RefNameRangeNr);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007274 if (clang_Range_isNull(CXRefNameRange))
7275 break; // All ranges handled.
7276
7277 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7278 while (I < NumTokens) {
7279 const SourceLocation TokenLocation = GetTokenLoc(I);
7280 if (!TokenLocation.isValid())
7281 break;
7282
7283 // Adapt the end range, because LocationCompare() reports
7284 // RangeOverlap even for the not-inclusive end location.
7285 const SourceLocation fixedEnd =
7286 RefNameRange.getEnd().getLocWithOffset(-1);
7287 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7288
7289 const RangeComparisonResult ComparisonResult =
7290 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7291
7292 if (ComparisonResult == RangeOverlap) {
7293 Cursors[I++] = Cursor;
7294 } else if (ComparisonResult == RangeBefore) {
7295 ++I; // Not relevant token, check next one.
7296 } else if (ComparisonResult == RangeAfter) {
7297 break; // All tokens updated for current range, check next.
7298 }
7299 }
7300 }
7301}
7302
Guy Benyei11169dd2012-12-18 14:30:41 +00007303static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7304 CXCursor parent,
7305 CXClientData client_data) {
7306 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7307}
7308
7309static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7310 CXClientData client_data) {
7311 return static_cast<AnnotateTokensWorker*>(client_data)->
7312 postVisitChildren(cursor);
7313}
7314
7315namespace {
7316
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007317/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007318/// and mark tokens that are macro arguments. This info is used by the
7319/// AnnotateTokensWorker.
7320class MarkMacroArgTokensVisitor {
7321 SourceManager &SM;
7322 CXToken *Tokens;
7323 unsigned NumTokens;
7324 unsigned CurIdx;
7325
7326public:
7327 MarkMacroArgTokensVisitor(SourceManager &SM,
7328 CXToken *tokens, unsigned numTokens)
7329 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7330
7331 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7332 if (cursor.kind != CXCursor_MacroExpansion)
7333 return CXChildVisit_Continue;
7334
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007335 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007336 if (macroRange.getBegin() == macroRange.getEnd())
7337 return CXChildVisit_Continue; // it's not a function macro.
7338
7339 for (; CurIdx < NumTokens; ++CurIdx) {
7340 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7341 macroRange.getBegin()))
7342 break;
7343 }
7344
7345 if (CurIdx == NumTokens)
7346 return CXChildVisit_Break;
7347
7348 for (; CurIdx < NumTokens; ++CurIdx) {
7349 SourceLocation tokLoc = getTokenLoc(CurIdx);
7350 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7351 break;
7352
7353 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7354 }
7355
7356 if (CurIdx == NumTokens)
7357 return CXChildVisit_Break;
7358
7359 return CXChildVisit_Continue;
7360 }
7361
7362private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007363 CXToken &getTok(unsigned Idx) {
7364 assert(Idx < NumTokens);
7365 return Tokens[Idx];
7366 }
7367 const CXToken &getTok(unsigned Idx) const {
7368 assert(Idx < NumTokens);
7369 return Tokens[Idx];
7370 }
7371
Guy Benyei11169dd2012-12-18 14:30:41 +00007372 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007373 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007374 }
7375
7376 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7377 // The third field is reserved and currently not used. Use it here
7378 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007379 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007380 }
7381};
7382
7383} // end anonymous namespace
7384
7385static CXChildVisitResult
7386MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7387 CXClientData client_data) {
7388 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7389 parent);
7390}
7391
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007392/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007393/// \returns true if lexing was finished, false otherwise.
7394static bool lexNext(Lexer &Lex, Token &Tok,
7395 unsigned &NextIdx, unsigned NumTokens) {
7396 if (NextIdx >= NumTokens)
7397 return true;
7398
7399 ++NextIdx;
7400 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007401 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007402}
7403
Guy Benyei11169dd2012-12-18 14:30:41 +00007404static void annotatePreprocessorTokens(CXTranslationUnit TU,
7405 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007406 CXCursor *Cursors,
7407 CXToken *Tokens,
7408 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007409 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007410
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007411 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007412 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7413 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007414 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007415 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007416 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007417
7418 if (BeginLocInfo.first != EndLocInfo.first)
7419 return;
7420
7421 StringRef Buffer;
7422 bool Invalid = false;
7423 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7424 if (Buffer.empty() || Invalid)
7425 return;
7426
7427 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7428 CXXUnit->getASTContext().getLangOpts(),
7429 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7430 Buffer.end());
7431 Lex.SetCommentRetentionState(true);
7432
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007433 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007434 // Lex tokens in raw mode until we hit the end of the range, to avoid
7435 // entering #includes or expanding macros.
7436 while (true) {
7437 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007438 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7439 break;
7440 unsigned TokIdx = NextIdx-1;
7441 assert(Tok.getLocation() ==
7442 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007443
7444 reprocess:
7445 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007446 // We have found a preprocessing directive. Annotate the tokens
7447 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007448 //
7449 // FIXME: Some simple tests here could identify macro definitions and
7450 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007451
7452 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007453 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7454 break;
7455
Craig Topper69186e72014-06-08 08:38:04 +00007456 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007457 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007458 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7459 break;
7460
7461 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007462 IdentifierInfo &II =
7463 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007464 SourceLocation MappedTokLoc =
7465 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7466 MI = getMacroInfo(II, MappedTokLoc, TU);
7467 }
7468 }
7469
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007470 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007471 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007472 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7473 finished = true;
7474 break;
7475 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007476 // If we are in a macro definition, check if the token was ever a
7477 // macro name and annotate it if that's the case.
7478 if (MI) {
7479 SourceLocation SaveLoc = Tok.getLocation();
7480 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007481 MacroDefinitionRecord *MacroDef =
7482 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007483 Tok.setLocation(SaveLoc);
7484 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007485 Cursors[NextIdx - 1] =
7486 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007487 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007488 } while (!Tok.isAtStartOfLine());
7489
7490 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7491 assert(TokIdx <= LastIdx);
7492 SourceLocation EndLoc =
7493 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7494 CXCursor Cursor =
7495 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7496
7497 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007498 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007499
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007500 if (finished)
7501 break;
7502 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007503 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007504 }
7505}
7506
7507// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007508static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7509 CXToken *Tokens, unsigned NumTokens,
7510 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007511 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007512 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7513 setThreadBackgroundPriority();
7514
7515 // Determine the region of interest, which contains all of the tokens.
7516 SourceRange RegionOfInterest;
7517 RegionOfInterest.setBegin(
7518 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7519 RegionOfInterest.setEnd(
7520 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7521 Tokens[NumTokens-1])));
7522
Guy Benyei11169dd2012-12-18 14:30:41 +00007523 // Relex the tokens within the source range to look for preprocessing
7524 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007525 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007526
7527 // If begin location points inside a macro argument, set it to the expansion
7528 // location so we can have the full context when annotating semantically.
7529 {
7530 SourceManager &SM = CXXUnit->getSourceManager();
7531 SourceLocation Loc =
7532 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7533 if (Loc.isMacroID())
7534 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7535 }
7536
Guy Benyei11169dd2012-12-18 14:30:41 +00007537 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7538 // Search and mark tokens that are macro argument expansions.
7539 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7540 Tokens, NumTokens);
7541 CursorVisitor MacroArgMarker(TU,
7542 MarkMacroArgTokensVisitorDelegate, &Visitor,
7543 /*VisitPreprocessorLast=*/true,
7544 /*VisitIncludedEntities=*/false,
7545 RegionOfInterest);
7546 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7547 }
7548
7549 // Annotate all of the source locations in the region of interest that map to
7550 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007551 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007552
7553 // FIXME: We use a ridiculous stack size here because the data-recursion
7554 // algorithm uses a large stack frame than the non-data recursive version,
7555 // and AnnotationTokensWorker currently transforms the data-recursion
7556 // algorithm back into a traditional recursion by explicitly calling
7557 // VisitChildren(). We will need to remove this explicit recursive call.
7558 W.AnnotateTokens();
7559
7560 // If we ran into any entities that involve context-sensitive keywords,
7561 // take another pass through the tokens to mark them as such.
7562 if (W.hasContextSensitiveKeywords()) {
7563 for (unsigned I = 0; I != NumTokens; ++I) {
7564 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7565 continue;
7566
7567 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7568 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007569 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007570 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7571 if (Property->getPropertyAttributesAsWritten() != 0 &&
7572 llvm::StringSwitch<bool>(II->getName())
7573 .Case("readonly", true)
7574 .Case("assign", true)
7575 .Case("unsafe_unretained", true)
7576 .Case("readwrite", true)
7577 .Case("retain", true)
7578 .Case("copy", true)
7579 .Case("nonatomic", true)
7580 .Case("atomic", true)
7581 .Case("getter", true)
7582 .Case("setter", true)
7583 .Case("strong", true)
7584 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007585 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007586 .Default(false))
7587 Tokens[I].int_data[0] = CXToken_Keyword;
7588 }
7589 continue;
7590 }
7591
7592 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7593 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7594 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7595 if (llvm::StringSwitch<bool>(II->getName())
7596 .Case("in", true)
7597 .Case("out", true)
7598 .Case("inout", true)
7599 .Case("oneway", true)
7600 .Case("bycopy", true)
7601 .Case("byref", true)
7602 .Default(false))
7603 Tokens[I].int_data[0] = CXToken_Keyword;
7604 continue;
7605 }
7606
7607 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7608 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7609 Tokens[I].int_data[0] = CXToken_Keyword;
7610 continue;
7611 }
7612 }
7613 }
7614}
7615
Guy Benyei11169dd2012-12-18 14:30:41 +00007616void clang_annotateTokens(CXTranslationUnit TU,
7617 CXToken *Tokens, unsigned NumTokens,
7618 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007619 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007620 LOG_BAD_TU(TU);
7621 return;
7622 }
7623 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007624 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007625 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007626 }
7627
7628 LOG_FUNC_SECTION {
7629 *Log << TU << ' ';
7630 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7631 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7632 *Log << clang_getRange(bloc, eloc);
7633 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007634
7635 // Any token we don't specifically annotate will have a NULL cursor.
7636 CXCursor C = clang_getNullCursor();
7637 for (unsigned I = 0; I != NumTokens; ++I)
7638 Cursors[I] = C;
7639
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007640 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007641 if (!CXXUnit)
7642 return;
7643
7644 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007645
7646 auto AnnotateTokensImpl = [=]() {
7647 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7648 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007649 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007650 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007651 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7652 }
7653}
7654
Guy Benyei11169dd2012-12-18 14:30:41 +00007655//===----------------------------------------------------------------------===//
7656// Operations for querying linkage of a cursor.
7657//===----------------------------------------------------------------------===//
7658
Guy Benyei11169dd2012-12-18 14:30:41 +00007659CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7660 if (!clang_isDeclaration(cursor.kind))
7661 return CXLinkage_Invalid;
7662
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007663 const Decl *D = cxcursor::getCursorDecl(cursor);
7664 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007665 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007666 case NoLinkage:
7667 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007668 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007669 case InternalLinkage: return CXLinkage_Internal;
7670 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007671 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007672 case ExternalLinkage: return CXLinkage_External;
7673 };
7674
7675 return CXLinkage_Invalid;
7676}
Guy Benyei11169dd2012-12-18 14:30:41 +00007677
7678//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007679// Operations for querying visibility of a cursor.
7680//===----------------------------------------------------------------------===//
7681
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007682CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7683 if (!clang_isDeclaration(cursor.kind))
7684 return CXVisibility_Invalid;
7685
7686 const Decl *D = cxcursor::getCursorDecl(cursor);
7687 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7688 switch (ND->getVisibility()) {
7689 case HiddenVisibility: return CXVisibility_Hidden;
7690 case ProtectedVisibility: return CXVisibility_Protected;
7691 case DefaultVisibility: return CXVisibility_Default;
7692 };
7693
7694 return CXVisibility_Invalid;
7695}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007696
7697//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007698// Operations for querying language of a cursor.
7699//===----------------------------------------------------------------------===//
7700
7701static CXLanguageKind getDeclLanguage(const Decl *D) {
7702 if (!D)
7703 return CXLanguage_C;
7704
7705 switch (D->getKind()) {
7706 default:
7707 break;
7708 case Decl::ImplicitParam:
7709 case Decl::ObjCAtDefsField:
7710 case Decl::ObjCCategory:
7711 case Decl::ObjCCategoryImpl:
7712 case Decl::ObjCCompatibleAlias:
7713 case Decl::ObjCImplementation:
7714 case Decl::ObjCInterface:
7715 case Decl::ObjCIvar:
7716 case Decl::ObjCMethod:
7717 case Decl::ObjCProperty:
7718 case Decl::ObjCPropertyImpl:
7719 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007720 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007721 return CXLanguage_ObjC;
7722 case Decl::CXXConstructor:
7723 case Decl::CXXConversion:
7724 case Decl::CXXDestructor:
7725 case Decl::CXXMethod:
7726 case Decl::CXXRecord:
7727 case Decl::ClassTemplate:
7728 case Decl::ClassTemplatePartialSpecialization:
7729 case Decl::ClassTemplateSpecialization:
7730 case Decl::Friend:
7731 case Decl::FriendTemplate:
7732 case Decl::FunctionTemplate:
7733 case Decl::LinkageSpec:
7734 case Decl::Namespace:
7735 case Decl::NamespaceAlias:
7736 case Decl::NonTypeTemplateParm:
7737 case Decl::StaticAssert:
7738 case Decl::TemplateTemplateParm:
7739 case Decl::TemplateTypeParm:
7740 case Decl::UnresolvedUsingTypename:
7741 case Decl::UnresolvedUsingValue:
7742 case Decl::Using:
7743 case Decl::UsingDirective:
7744 case Decl::UsingShadow:
7745 return CXLanguage_CPlusPlus;
7746 }
7747
7748 return CXLanguage_C;
7749}
7750
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007751static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7752 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007753 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007754
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007755 switch (D->getAvailability()) {
7756 case AR_Available:
7757 case AR_NotYetIntroduced:
7758 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007759 return getCursorAvailabilityForDecl(
7760 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007761 return CXAvailability_Available;
7762
7763 case AR_Deprecated:
7764 return CXAvailability_Deprecated;
7765
7766 case AR_Unavailable:
7767 return CXAvailability_NotAvailable;
7768 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007769
7770 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007771}
7772
Guy Benyei11169dd2012-12-18 14:30:41 +00007773enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7774 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007775 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7776 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007777
7778 return CXAvailability_Available;
7779}
7780
7781static CXVersion convertVersion(VersionTuple In) {
7782 CXVersion Out = { -1, -1, -1 };
7783 if (In.empty())
7784 return Out;
7785
7786 Out.Major = In.getMajor();
7787
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007788 Optional<unsigned> Minor = In.getMinor();
7789 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007790 Out.Minor = *Minor;
7791 else
7792 return Out;
7793
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007794 Optional<unsigned> Subminor = In.getSubminor();
7795 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007796 Out.Subminor = *Subminor;
7797
7798 return Out;
7799}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007800
Alex Lorenz1345ea22017-06-12 19:06:30 +00007801static void getCursorPlatformAvailabilityForDecl(
7802 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7803 int *always_unavailable, CXString *unavailable_message,
7804 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007805 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007806 for (auto A : D->attrs()) {
7807 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007808 HadAvailAttr = true;
7809 if (always_deprecated)
7810 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007811 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007812 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007813 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007814 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007815 continue;
7816 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007817
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007818 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007819 HadAvailAttr = true;
7820 if (always_unavailable)
7821 *always_unavailable = 1;
7822 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007823 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007824 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7825 }
7826 continue;
7827 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007828
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007829 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007830 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007831 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007832 }
7833 }
7834
7835 if (!HadAvailAttr)
7836 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7837 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007838 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7839 deprecated_message, always_unavailable, unavailable_message,
7840 AvailabilityAttrs);
7841
7842 if (AvailabilityAttrs.empty())
7843 return;
7844
Fangrui Song55fab262018-09-26 22:16:28 +00007845 llvm::sort(AvailabilityAttrs,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007846 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7847 return LHS->getPlatform()->getName() <
7848 RHS->getPlatform()->getName();
Fangrui Song55fab262018-09-26 22:16:28 +00007849 });
Alex Lorenz1345ea22017-06-12 19:06:30 +00007850 ASTContext &Ctx = D->getASTContext();
7851 auto It = std::unique(
7852 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7853 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7854 if (LHS->getPlatform() != RHS->getPlatform())
7855 return false;
7856
7857 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7858 LHS->getDeprecated() == RHS->getDeprecated() &&
7859 LHS->getObsoleted() == RHS->getObsoleted() &&
7860 LHS->getMessage() == RHS->getMessage() &&
7861 LHS->getReplacement() == RHS->getReplacement())
7862 return true;
7863
7864 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7865 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7866 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7867 return false;
7868
7869 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7870 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7871
7872 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7873 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7874 if (LHS->getMessage().empty())
7875 LHS->setMessage(Ctx, RHS->getMessage());
7876 if (LHS->getReplacement().empty())
7877 LHS->setReplacement(Ctx, RHS->getReplacement());
7878 }
7879
7880 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7881 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7882 if (LHS->getMessage().empty())
7883 LHS->setMessage(Ctx, RHS->getMessage());
7884 if (LHS->getReplacement().empty())
7885 LHS->setReplacement(Ctx, RHS->getReplacement());
7886 }
7887
7888 return true;
7889 });
7890 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007891}
7892
Alex Lorenz1345ea22017-06-12 19:06:30 +00007893int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007894 CXString *deprecated_message,
7895 int *always_unavailable,
7896 CXString *unavailable_message,
7897 CXPlatformAvailability *availability,
7898 int availability_size) {
7899 if (always_deprecated)
7900 *always_deprecated = 0;
7901 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007902 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007903 if (always_unavailable)
7904 *always_unavailable = 0;
7905 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007906 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007907
Guy Benyei11169dd2012-12-18 14:30:41 +00007908 if (!clang_isDeclaration(cursor.kind))
7909 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007910
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007911 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007912 if (!D)
7913 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007914
Alex Lorenz1345ea22017-06-12 19:06:30 +00007915 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7916 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7917 always_unavailable, unavailable_message,
7918 AvailabilityAttrs);
7919 for (const auto &Avail :
7920 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7921 .take_front(availability_size))) {
7922 availability[Avail.index()].Platform =
7923 cxstring::createDup(Avail.value()->getPlatform()->getName());
7924 availability[Avail.index()].Introduced =
7925 convertVersion(Avail.value()->getIntroduced());
7926 availability[Avail.index()].Deprecated =
7927 convertVersion(Avail.value()->getDeprecated());
7928 availability[Avail.index()].Obsoleted =
7929 convertVersion(Avail.value()->getObsoleted());
7930 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7931 availability[Avail.index()].Message =
7932 cxstring::createDup(Avail.value()->getMessage());
7933 }
7934
7935 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007936}
Alex Lorenz1345ea22017-06-12 19:06:30 +00007937
Guy Benyei11169dd2012-12-18 14:30:41 +00007938void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7939 clang_disposeString(availability->Platform);
7940 clang_disposeString(availability->Message);
7941}
7942
7943CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7944 if (clang_isDeclaration(cursor.kind))
7945 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7946
7947 return CXLanguage_Invalid;
7948}
7949
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00007950CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7951 const Decl *D = cxcursor::getCursorDecl(cursor);
7952 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7953 switch (VD->getTLSKind()) {
7954 case VarDecl::TLS_None:
7955 return CXTLS_None;
7956 case VarDecl::TLS_Dynamic:
7957 return CXTLS_Dynamic;
7958 case VarDecl::TLS_Static:
7959 return CXTLS_Static;
7960 }
7961 }
7962
7963 return CXTLS_None;
7964}
7965
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007966 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007967 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00007968 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007969static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007970 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007971 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007972
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007973 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007974 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7975 return FunTmpl;
7976
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007977 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007978 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7979 return ClassTmpl;
7980
7981 return D;
7982}
7983
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007984
7985enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7986 StorageClass sc = SC_None;
7987 const Decl *D = getCursorDecl(C);
7988 if (D) {
7989 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7990 sc = FD->getStorageClass();
7991 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7992 sc = VD->getStorageClass();
7993 } else {
7994 return CX_SC_Invalid;
7995 }
7996 } else {
7997 return CX_SC_Invalid;
7998 }
7999 switch (sc) {
8000 case SC_None:
8001 return CX_SC_None;
8002 case SC_Extern:
8003 return CX_SC_Extern;
8004 case SC_Static:
8005 return CX_SC_Static;
8006 case SC_PrivateExtern:
8007 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008008 case SC_Auto:
8009 return CX_SC_Auto;
8010 case SC_Register:
8011 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008012 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00008013 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00008014}
8015
Guy Benyei11169dd2012-12-18 14:30:41 +00008016CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
8017 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008018 if (const Decl *D = getCursorDecl(cursor)) {
8019 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008020 if (!DC)
8021 return clang_getNullCursor();
8022
8023 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8024 getCursorTU(cursor));
8025 }
8026 }
8027
8028 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008029 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00008030 return MakeCXCursor(D, getCursorTU(cursor));
8031 }
8032
8033 return clang_getNullCursor();
8034}
8035
8036CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8037 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008038 if (const Decl *D = getCursorDecl(cursor)) {
8039 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008040 if (!DC)
8041 return clang_getNullCursor();
8042
8043 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8044 getCursorTU(cursor));
8045 }
8046 }
8047
8048 // FIXME: Note that we can't easily compute the lexical context of a
8049 // statement or expression, so we return nothing.
8050 return clang_getNullCursor();
8051}
8052
8053CXFile clang_getIncludedFile(CXCursor cursor) {
8054 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00008055 return nullptr;
8056
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008057 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00008058 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00008059}
8060
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008061unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8062 if (C.kind != CXCursor_ObjCPropertyDecl)
8063 return CXObjCPropertyAttr_noattr;
8064
8065 unsigned Result = CXObjCPropertyAttr_noattr;
8066 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8067 ObjCPropertyDecl::PropertyAttributeKind Attr =
8068 PD->getPropertyAttributesAsWritten();
8069
8070#define SET_CXOBJCPROP_ATTR(A) \
8071 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8072 Result |= CXObjCPropertyAttr_##A
8073 SET_CXOBJCPROP_ATTR(readonly);
8074 SET_CXOBJCPROP_ATTR(getter);
8075 SET_CXOBJCPROP_ATTR(assign);
8076 SET_CXOBJCPROP_ATTR(readwrite);
8077 SET_CXOBJCPROP_ATTR(retain);
8078 SET_CXOBJCPROP_ATTR(copy);
8079 SET_CXOBJCPROP_ATTR(nonatomic);
8080 SET_CXOBJCPROP_ATTR(setter);
8081 SET_CXOBJCPROP_ATTR(atomic);
8082 SET_CXOBJCPROP_ATTR(weak);
8083 SET_CXOBJCPROP_ATTR(strong);
8084 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00008085 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008086#undef SET_CXOBJCPROP_ATTR
8087
8088 return Result;
8089}
8090
Michael Wu6e88f532018-08-03 05:38:29 +00008091CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8092 if (C.kind != CXCursor_ObjCPropertyDecl)
8093 return cxstring::createNull();
8094
8095 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8096 Selector sel = PD->getGetterName();
8097 if (sel.isNull())
8098 return cxstring::createNull();
8099
8100 return cxstring::createDup(sel.getAsString());
8101}
8102
8103CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8104 if (C.kind != CXCursor_ObjCPropertyDecl)
8105 return cxstring::createNull();
8106
8107 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8108 Selector sel = PD->getSetterName();
8109 if (sel.isNull())
8110 return cxstring::createNull();
8111
8112 return cxstring::createDup(sel.getAsString());
8113}
8114
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00008115unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8116 if (!clang_isDeclaration(C.kind))
8117 return CXObjCDeclQualifier_None;
8118
8119 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8120 const Decl *D = getCursorDecl(C);
8121 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8122 QT = MD->getObjCDeclQualifier();
8123 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8124 QT = PD->getObjCDeclQualifier();
8125 if (QT == Decl::OBJC_TQ_None)
8126 return CXObjCDeclQualifier_None;
8127
8128 unsigned Result = CXObjCDeclQualifier_None;
8129 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
8130 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
8131 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
8132 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
8133 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
8134 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
8135
8136 return Result;
8137}
8138
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00008139unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8140 if (!clang_isDeclaration(C.kind))
8141 return 0;
8142
8143 const Decl *D = getCursorDecl(C);
8144 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8145 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8146 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8147 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8148
8149 return 0;
8150}
8151
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00008152unsigned clang_Cursor_isVariadic(CXCursor C) {
8153 if (!clang_isDeclaration(C.kind))
8154 return 0;
8155
8156 const Decl *D = getCursorDecl(C);
8157 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8158 return FD->isVariadic();
8159 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8160 return MD->isVariadic();
8161
8162 return 0;
8163}
8164
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008165unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8166 CXString *language, CXString *definedIn,
8167 unsigned *isGenerated) {
8168 if (!clang_isDeclaration(C.kind))
8169 return 0;
8170
8171 const Decl *D = getCursorDecl(C);
8172
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00008173 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008174 if (language)
8175 *language = cxstring::createDup(attr->getLanguage());
8176 if (definedIn)
8177 *definedIn = cxstring::createDup(attr->getDefinedIn());
8178 if (isGenerated)
8179 *isGenerated = attr->getGeneratedDeclaration();
8180 return 1;
8181 }
8182 return 0;
8183}
8184
Guy Benyei11169dd2012-12-18 14:30:41 +00008185CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8186 if (!clang_isDeclaration(C.kind))
8187 return clang_getNullRange();
8188
8189 const Decl *D = getCursorDecl(C);
8190 ASTContext &Context = getCursorContext(C);
8191 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8192 if (!RC)
8193 return clang_getNullRange();
8194
8195 return cxloc::translateSourceRange(Context, RC->getSourceRange());
8196}
8197
8198CXString clang_Cursor_getRawCommentText(CXCursor C) {
8199 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008200 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008201
8202 const Decl *D = getCursorDecl(C);
8203 ASTContext &Context = getCursorContext(C);
8204 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8205 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8206 StringRef();
8207
8208 // Don't duplicate the string because RawText points directly into source
8209 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008210 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008211}
8212
8213CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8214 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008215 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008216
8217 const Decl *D = getCursorDecl(C);
8218 const ASTContext &Context = getCursorContext(C);
8219 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8220
8221 if (RC) {
8222 StringRef BriefText = RC->getBriefText(Context);
8223
8224 // Don't duplicate the string because RawComment ensures that this memory
8225 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008226 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008227 }
8228
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008229 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008230}
8231
Guy Benyei11169dd2012-12-18 14:30:41 +00008232CXModule clang_Cursor_getModule(CXCursor C) {
8233 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008234 if (const ImportDecl *ImportD =
8235 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00008236 return ImportD->getImportedModule();
8237 }
8238
Craig Topper69186e72014-06-08 08:38:04 +00008239 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008240}
8241
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008242CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8243 if (isNotUsableTU(TU)) {
8244 LOG_BAD_TU(TU);
8245 return nullptr;
8246 }
8247 if (!File)
8248 return nullptr;
8249 FileEntry *FE = static_cast<FileEntry *>(File);
8250
8251 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8252 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8253 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8254
Richard Smithfeb54b62014-10-23 02:01:19 +00008255 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008256}
8257
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008258CXFile clang_Module_getASTFile(CXModule CXMod) {
8259 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008260 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008261 Module *Mod = static_cast<Module*>(CXMod);
8262 return const_cast<FileEntry *>(Mod->getASTFile());
8263}
8264
Guy Benyei11169dd2012-12-18 14:30:41 +00008265CXModule clang_Module_getParent(CXModule CXMod) {
8266 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008267 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008268 Module *Mod = static_cast<Module*>(CXMod);
8269 return Mod->Parent;
8270}
8271
8272CXString clang_Module_getName(CXModule CXMod) {
8273 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008274 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008275 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008276 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00008277}
8278
8279CXString clang_Module_getFullName(CXModule CXMod) {
8280 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008281 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008282 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008283 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008284}
8285
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008286int clang_Module_isSystem(CXModule CXMod) {
8287 if (!CXMod)
8288 return 0;
8289 Module *Mod = static_cast<Module*>(CXMod);
8290 return Mod->IsSystem;
8291}
8292
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008293unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8294 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008295 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008296 LOG_BAD_TU(TU);
8297 return 0;
8298 }
8299 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008300 return 0;
8301 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008302 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8303 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8304 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008305}
8306
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008307CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8308 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008309 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008310 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008311 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008312 }
8313 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008314 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008315 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008316 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008317
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008318 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8319 if (Index < TopHeaders.size())
8320 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008321
Craig Topper69186e72014-06-08 08:38:04 +00008322 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008323}
8324
Guy Benyei11169dd2012-12-18 14:30:41 +00008325//===----------------------------------------------------------------------===//
8326// C++ AST instrospection.
8327//===----------------------------------------------------------------------===//
8328
Jonathan Coe29565352016-04-27 12:48:25 +00008329unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8330 if (!clang_isDeclaration(C.kind))
8331 return 0;
8332
8333 const Decl *D = cxcursor::getCursorDecl(C);
8334 const CXXConstructorDecl *Constructor =
8335 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8336 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8337}
8338
8339unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8340 if (!clang_isDeclaration(C.kind))
8341 return 0;
8342
8343 const Decl *D = cxcursor::getCursorDecl(C);
8344 const CXXConstructorDecl *Constructor =
8345 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8346 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8347}
8348
8349unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8350 if (!clang_isDeclaration(C.kind))
8351 return 0;
8352
8353 const Decl *D = cxcursor::getCursorDecl(C);
8354 const CXXConstructorDecl *Constructor =
8355 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8356 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8357}
8358
8359unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8360 if (!clang_isDeclaration(C.kind))
8361 return 0;
8362
8363 const Decl *D = cxcursor::getCursorDecl(C);
8364 const CXXConstructorDecl *Constructor =
8365 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8366 // Passing 'false' excludes constructors marked 'explicit'.
8367 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8368}
8369
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008370unsigned clang_CXXField_isMutable(CXCursor C) {
8371 if (!clang_isDeclaration(C.kind))
8372 return 0;
8373
8374 if (const auto D = cxcursor::getCursorDecl(C))
8375 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8376 return FD->isMutable() ? 1 : 0;
8377 return 0;
8378}
8379
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008380unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8381 if (!clang_isDeclaration(C.kind))
8382 return 0;
8383
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008384 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008385 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008386 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008387 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8388}
8389
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008390unsigned clang_CXXMethod_isConst(CXCursor C) {
8391 if (!clang_isDeclaration(C.kind))
8392 return 0;
8393
8394 const Decl *D = cxcursor::getCursorDecl(C);
8395 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008396 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008397 return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008398}
8399
Jonathan Coe29565352016-04-27 12:48:25 +00008400unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8401 if (!clang_isDeclaration(C.kind))
8402 return 0;
8403
8404 const Decl *D = cxcursor::getCursorDecl(C);
8405 const CXXMethodDecl *Method =
8406 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8407 return (Method && Method->isDefaulted()) ? 1 : 0;
8408}
8409
Guy Benyei11169dd2012-12-18 14:30:41 +00008410unsigned clang_CXXMethod_isStatic(CXCursor C) {
8411 if (!clang_isDeclaration(C.kind))
8412 return 0;
8413
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008414 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008415 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008416 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008417 return (Method && Method->isStatic()) ? 1 : 0;
8418}
8419
8420unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8421 if (!clang_isDeclaration(C.kind))
8422 return 0;
8423
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008424 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008425 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008426 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008427 return (Method && Method->isVirtual()) ? 1 : 0;
8428}
Guy Benyei11169dd2012-12-18 14:30:41 +00008429
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008430unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8431 if (!clang_isDeclaration(C.kind))
8432 return 0;
8433
8434 const auto *D = cxcursor::getCursorDecl(C);
8435 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8436 if (RD)
8437 RD = RD->getDefinition();
8438 return (RD && RD->isAbstract()) ? 1 : 0;
8439}
8440
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008441unsigned clang_EnumDecl_isScoped(CXCursor C) {
8442 if (!clang_isDeclaration(C.kind))
8443 return 0;
8444
8445 const Decl *D = cxcursor::getCursorDecl(C);
8446 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8447 return (Enum && Enum->isScoped()) ? 1 : 0;
8448}
8449
Guy Benyei11169dd2012-12-18 14:30:41 +00008450//===----------------------------------------------------------------------===//
8451// Attribute introspection.
8452//===----------------------------------------------------------------------===//
8453
Guy Benyei11169dd2012-12-18 14:30:41 +00008454CXType clang_getIBOutletCollectionType(CXCursor C) {
8455 if (C.kind != CXCursor_IBOutletCollectionAttr)
8456 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8457
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008458 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008459 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8460
8461 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8462}
Guy Benyei11169dd2012-12-18 14:30:41 +00008463
8464//===----------------------------------------------------------------------===//
8465// Inspecting memory usage.
8466//===----------------------------------------------------------------------===//
8467
8468typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8469
8470static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8471 enum CXTUResourceUsageKind k,
8472 unsigned long amount) {
8473 CXTUResourceUsageEntry entry = { k, amount };
8474 entries.push_back(entry);
8475}
8476
Guy Benyei11169dd2012-12-18 14:30:41 +00008477const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8478 const char *str = "";
8479 switch (kind) {
8480 case CXTUResourceUsage_AST:
8481 str = "ASTContext: expressions, declarations, and types";
8482 break;
8483 case CXTUResourceUsage_Identifiers:
8484 str = "ASTContext: identifiers";
8485 break;
8486 case CXTUResourceUsage_Selectors:
8487 str = "ASTContext: selectors";
8488 break;
8489 case CXTUResourceUsage_GlobalCompletionResults:
8490 str = "Code completion: cached global results";
8491 break;
8492 case CXTUResourceUsage_SourceManagerContentCache:
8493 str = "SourceManager: content cache allocator";
8494 break;
8495 case CXTUResourceUsage_AST_SideTables:
8496 str = "ASTContext: side tables";
8497 break;
8498 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8499 str = "SourceManager: malloc'ed memory buffers";
8500 break;
8501 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8502 str = "SourceManager: mmap'ed memory buffers";
8503 break;
8504 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8505 str = "ExternalASTSource: malloc'ed memory buffers";
8506 break;
8507 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8508 str = "ExternalASTSource: mmap'ed memory buffers";
8509 break;
8510 case CXTUResourceUsage_Preprocessor:
8511 str = "Preprocessor: malloc'ed memory";
8512 break;
8513 case CXTUResourceUsage_PreprocessingRecord:
8514 str = "Preprocessor: PreprocessingRecord";
8515 break;
8516 case CXTUResourceUsage_SourceManager_DataStructures:
8517 str = "SourceManager: data structures and tables";
8518 break;
8519 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8520 str = "Preprocessor: header search tables";
8521 break;
8522 }
8523 return str;
8524}
8525
8526CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008527 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008528 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008529 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008530 return usage;
8531 }
8532
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008533 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008534 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008535 ASTContext &astContext = astUnit->getASTContext();
8536
8537 // How much memory is used by AST nodes and types?
8538 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8539 (unsigned long) astContext.getASTAllocatedMemory());
8540
8541 // How much memory is used by identifiers?
8542 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8543 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8544
8545 // How much memory is used for selectors?
8546 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8547 (unsigned long) astContext.Selectors.getTotalMemory());
8548
8549 // How much memory is used by ASTContext's side tables?
8550 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8551 (unsigned long) astContext.getSideTableAllocatedMemory());
8552
8553 // How much memory is used for caching global code completion results?
8554 unsigned long completionBytes = 0;
8555 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008556 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008557 completionBytes = completionAllocator->getTotalMemory();
8558 }
8559 createCXTUResourceUsageEntry(*entries,
8560 CXTUResourceUsage_GlobalCompletionResults,
8561 completionBytes);
8562
8563 // How much memory is being used by SourceManager's content cache?
8564 createCXTUResourceUsageEntry(*entries,
8565 CXTUResourceUsage_SourceManagerContentCache,
8566 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8567
8568 // How much memory is being used by the MemoryBuffer's in SourceManager?
8569 const SourceManager::MemoryBufferSizes &srcBufs =
8570 astUnit->getSourceManager().getMemoryBufferSizes();
8571
8572 createCXTUResourceUsageEntry(*entries,
8573 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8574 (unsigned long) srcBufs.malloc_bytes);
8575 createCXTUResourceUsageEntry(*entries,
8576 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8577 (unsigned long) srcBufs.mmap_bytes);
8578 createCXTUResourceUsageEntry(*entries,
8579 CXTUResourceUsage_SourceManager_DataStructures,
8580 (unsigned long) astContext.getSourceManager()
8581 .getDataStructureSizes());
8582
8583 // How much memory is being used by the ExternalASTSource?
8584 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8585 const ExternalASTSource::MemoryBufferSizes &sizes =
8586 esrc->getMemoryBufferSizes();
8587
8588 createCXTUResourceUsageEntry(*entries,
8589 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8590 (unsigned long) sizes.malloc_bytes);
8591 createCXTUResourceUsageEntry(*entries,
8592 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8593 (unsigned long) sizes.mmap_bytes);
8594 }
8595
8596 // How much memory is being used by the Preprocessor?
8597 Preprocessor &pp = astUnit->getPreprocessor();
8598 createCXTUResourceUsageEntry(*entries,
8599 CXTUResourceUsage_Preprocessor,
8600 pp.getTotalMemory());
8601
8602 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8603 createCXTUResourceUsageEntry(*entries,
8604 CXTUResourceUsage_PreprocessingRecord,
8605 pRec->getTotalMemory());
8606 }
8607
8608 createCXTUResourceUsageEntry(*entries,
8609 CXTUResourceUsage_Preprocessor_HeaderSearch,
8610 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008611
Guy Benyei11169dd2012-12-18 14:30:41 +00008612 CXTUResourceUsage usage = { (void*) entries.get(),
8613 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008614 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008615 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008616 return usage;
8617}
8618
8619void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8620 if (usage.data)
8621 delete (MemUsageEntries*) usage.data;
8622}
8623
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008624CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8625 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008626 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008627 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008628
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008629 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008630 LOG_BAD_TU(TU);
8631 return skipped;
8632 }
8633
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008634 if (!file)
8635 return skipped;
8636
8637 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8638 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8639 if (!ppRec)
8640 return skipped;
8641
8642 ASTContext &Ctx = astUnit->getASTContext();
8643 SourceManager &sm = Ctx.getSourceManager();
8644 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8645 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008646 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008647
8648 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8649 std::vector<SourceRange> wantedRanges;
8650 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8651 i != ei; ++i) {
8652 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8653 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008654 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8655 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008656 }
8657
8658 skipped->count = wantedRanges.size();
8659 skipped->ranges = new CXSourceRange[skipped->count];
8660 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8661 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8662
8663 return skipped;
8664}
8665
Cameron Desrochersd8091282016-08-18 15:43:55 +00008666CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8667 CXSourceRangeList *skipped = new CXSourceRangeList;
8668 skipped->count = 0;
8669 skipped->ranges = nullptr;
8670
8671 if (isNotUsableTU(TU)) {
8672 LOG_BAD_TU(TU);
8673 return skipped;
8674 }
8675
8676 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8677 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8678 if (!ppRec)
8679 return skipped;
8680
8681 ASTContext &Ctx = astUnit->getASTContext();
8682
8683 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8684
8685 skipped->count = SkippedRanges.size();
8686 skipped->ranges = new CXSourceRange[skipped->count];
8687 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8688 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8689
8690 return skipped;
8691}
8692
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008693void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8694 if (ranges) {
8695 delete[] ranges->ranges;
8696 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008697 }
8698}
8699
Guy Benyei11169dd2012-12-18 14:30:41 +00008700void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8701 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8702 for (unsigned I = 0; I != Usage.numEntries; ++I)
8703 fprintf(stderr, " %s: %lu\n",
8704 clang_getTUResourceUsageName(Usage.entries[I].kind),
8705 Usage.entries[I].amount);
8706
8707 clang_disposeCXTUResourceUsage(Usage);
8708}
8709
8710//===----------------------------------------------------------------------===//
8711// Misc. utility functions.
8712//===----------------------------------------------------------------------===//
8713
Richard Smith0a7b2972018-07-03 21:34:13 +00008714/// Default to using our desired 8 MB stack size on "safety" threads.
8715static unsigned SafetyStackThreadSize = DesiredStackSize;
Guy Benyei11169dd2012-12-18 14:30:41 +00008716
8717namespace clang {
8718
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008719bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008720 unsigned Size) {
8721 if (!Size)
8722 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008723 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008724 return CRC.RunSafelyOnThread(Fn, Size);
8725 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008726}
8727
8728unsigned GetSafetyThreadStackSize() {
8729 return SafetyStackThreadSize;
8730}
8731
8732void SetSafetyThreadStackSize(unsigned Value) {
8733 SafetyStackThreadSize = Value;
8734}
8735
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008736}
Guy Benyei11169dd2012-12-18 14:30:41 +00008737
8738void clang::setThreadBackgroundPriority() {
8739 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8740 return;
8741
Nico Weber18cfd9f2019-04-21 19:18:41 +00008742#if LLVM_ENABLE_THREADS
Kadir Cetinkayab8f82ca2019-04-18 13:49:20 +00008743 llvm::set_thread_priority(llvm::ThreadPriority::Background);
Nico Weber18cfd9f2019-04-21 19:18:41 +00008744#endif
Guy Benyei11169dd2012-12-18 14:30:41 +00008745}
8746
8747void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8748 if (!Unit)
8749 return;
8750
8751 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8752 DEnd = Unit->stored_diag_end();
8753 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008754 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008755 CXString Msg = clang_formatDiagnostic(&Diag,
8756 clang_defaultDiagnosticDisplayOptions());
8757 fprintf(stderr, "%s\n", clang_getCString(Msg));
8758 clang_disposeString(Msg);
8759 }
Nico Weber1865df42018-04-27 19:11:14 +00008760#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008761 // On Windows, force a flush, since there may be multiple copies of
8762 // stderr and stdout in the file system, all with different buffers
8763 // but writing to the same device.
8764 fflush(stderr);
8765#endif
8766}
8767
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008768MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8769 SourceLocation MacroDefLoc,
8770 CXTranslationUnit TU){
8771 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008772 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008773 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008774 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008775
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008776 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008777 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008778 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008779 if (MD) {
8780 for (MacroDirective::DefInfo
8781 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8782 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8783 return Def.getMacroInfo();
8784 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008785 }
8786
Craig Topper69186e72014-06-08 08:38:04 +00008787 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008788}
8789
Richard Smith66a81862015-05-04 02:25:31 +00008790const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008791 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008792 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008793 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008794 const IdentifierInfo *II = MacroDef->getName();
8795 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008796 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008797
8798 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8799}
8800
Richard Smith66a81862015-05-04 02:25:31 +00008801MacroDefinitionRecord *
8802cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8803 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008804 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008805 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008806 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008807 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008808
8809 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008810 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008811 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8812 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008813 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008814
8815 // Check that the token is inside the definition and not its argument list.
8816 SourceManager &SM = Unit->getSourceManager();
8817 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008818 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008819 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008820 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008821
8822 Preprocessor &PP = Unit->getPreprocessor();
8823 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8824 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008825 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008826
Alp Toker2d57cea2014-05-17 04:53:25 +00008827 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008828 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008829 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008830
8831 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008832 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008833 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008834
Richard Smith20e883e2015-04-29 23:20:19 +00008835 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008836 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008837 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008838
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008839 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008840}
8841
Richard Smith66a81862015-05-04 02:25:31 +00008842MacroDefinitionRecord *
8843cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8844 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008845 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008846 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008847
8848 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008849 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008850 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008851 Preprocessor &PP = Unit->getPreprocessor();
8852 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008853 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008854 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8855 Token Tok;
8856 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008857 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008858
8859 return checkForMacroInMacroDefinition(MI, Tok, TU);
8860}
8861
Guy Benyei11169dd2012-12-18 14:30:41 +00008862CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008863 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008864}
8865
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008866Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8867 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008868 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008869 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008870 if (Unit->isMainFileAST())
8871 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008872 return *this;
8873 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008874 } else {
8875 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008876 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008877 return *this;
8878}
8879
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008880Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8881 *this << FE->getName();
8882 return *this;
8883}
8884
8885Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8886 CXString cursorName = clang_getCursorDisplayName(cursor);
8887 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8888 clang_disposeString(cursorName);
8889 return *this;
8890}
8891
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008892Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8893 CXFile File;
8894 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008895 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008896 CXString FileName = clang_getFileName(File);
8897 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8898 clang_disposeString(FileName);
8899 return *this;
8900}
8901
8902Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8903 CXSourceLocation BLoc = clang_getRangeStart(range);
8904 CXSourceLocation ELoc = clang_getRangeEnd(range);
8905
8906 CXFile BFile;
8907 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008908 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008909
8910 CXFile EFile;
8911 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008912 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008913
8914 CXString BFileName = clang_getFileName(BFile);
8915 if (BFile == EFile) {
8916 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8917 BLine, BColumn, ELine, EColumn);
8918 } else {
8919 CXString EFileName = clang_getFileName(EFile);
8920 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8921 BLine, BColumn)
8922 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8923 ELine, EColumn);
8924 clang_disposeString(EFileName);
8925 }
8926 clang_disposeString(BFileName);
8927 return *this;
8928}
8929
8930Logger &cxindex::Logger::operator<<(CXString Str) {
8931 *this << clang_getCString(Str);
8932 return *this;
8933}
8934
8935Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8936 LogOS << Fmt;
8937 return *this;
8938}
8939
Chandler Carruth37ad2582014-06-27 15:14:39 +00008940static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8941
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008942cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008943 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008944
8945 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8946
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008947 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008948 OS << "[libclang:" << Name << ':';
8949
Alp Toker1a86ad22014-07-06 06:24:00 +00008950#ifdef USE_DARWIN_THREADS
8951 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008952 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8953 OS << tid << ':';
8954#endif
8955
8956 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8957 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008958 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008959
8960 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008961 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008962 OS << "--------------------------------------------------\n";
8963 }
8964}
Ivan Donchevskiic5929132018-12-10 15:58:50 +00008965
8966#ifdef CLANG_TOOL_EXTRA_BUILD
8967// This anchor is used to force the linker to link the clang-tidy plugin.
8968extern volatile int ClangTidyPluginAnchorSource;
8969static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8970 ClangTidyPluginAnchorSource;
8971
8972// This anchor is used to force the linker to link the clang-include-fixer
8973// plugin.
8974extern volatile int ClangIncludeFixerPluginAnchorSource;
8975static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8976 ClangIncludeFixerPluginAnchorSource;
8977#endif