blob: d7eee5e684db289b15aec631ae8c97aa0d7f6e82 [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
1433 case TemplateName::DependentTemplate:
1434 // FIXME: Visit nested-name-specifier.
1435 return false;
1436
1437 case TemplateName::QualifiedTemplate:
1438 // FIXME: Visit nested-name-specifier.
1439 return Visit(MakeCursorTemplateRef(
1440 Name.getAsQualifiedTemplateName()->getDecl(),
1441 Loc, TU));
1442
1443 case TemplateName::SubstTemplateTemplateParm:
1444 return Visit(MakeCursorTemplateRef(
1445 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1446 Loc, TU));
1447
1448 case TemplateName::SubstTemplateTemplateParmPack:
1449 return Visit(MakeCursorTemplateRef(
1450 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1451 Loc, TU));
1452 }
1453
1454 llvm_unreachable("Invalid TemplateName::Kind!");
1455}
1456
1457bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1458 switch (TAL.getArgument().getKind()) {
1459 case TemplateArgument::Null:
1460 case TemplateArgument::Integral:
1461 case TemplateArgument::Pack:
1462 return false;
1463
1464 case TemplateArgument::Type:
1465 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1466 return Visit(TSInfo->getTypeLoc());
1467 return false;
1468
1469 case TemplateArgument::Declaration:
1470 if (Expr *E = TAL.getSourceDeclExpression())
1471 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1472 return false;
1473
1474 case TemplateArgument::NullPtr:
1475 if (Expr *E = TAL.getSourceNullPtrExpression())
1476 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1477 return false;
1478
1479 case TemplateArgument::Expression:
1480 if (Expr *E = TAL.getSourceExpression())
1481 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1482 return false;
1483
1484 case TemplateArgument::Template:
1485 case TemplateArgument::TemplateExpansion:
1486 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1487 return true;
1488
1489 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1490 TAL.getTemplateNameLoc());
1491 }
1492
1493 llvm_unreachable("Invalid TemplateArgument::Kind!");
1494}
1495
1496bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1497 return VisitDeclContext(D);
1498}
1499
1500bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1501 return Visit(TL.getUnqualifiedLoc());
1502}
1503
1504bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1505 ASTContext &Context = AU->getASTContext();
1506
1507 // Some builtin types (such as Objective-C's "id", "sel", and
1508 // "Class") have associated declarations. Create cursors for those.
1509 QualType VisitType;
1510 switch (TL.getTypePtr()->getKind()) {
1511
1512 case BuiltinType::Void:
1513 case BuiltinType::NullPtr:
1514 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +00001515#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1516 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001517#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001518#define EXT_OPAQUE_TYPE(ExtTYpe, Id, Ext) \
1519 case BuiltinType::Id:
1520#include "clang/Basic/OpenCLExtensionTypes.def"
NAKAMURA Takumi288c42e2013-02-07 12:47:42 +00001521 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001522 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001523 case BuiltinType::OCLClkEvent:
1524 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001525 case BuiltinType::OCLReserveID:
Guy Benyei11169dd2012-12-18 14:30:41 +00001526#define BUILTIN_TYPE(Id, SingletonId)
1527#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1528#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1529#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1530#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1531#include "clang/AST/BuiltinTypes.def"
1532 break;
1533
1534 case BuiltinType::ObjCId:
1535 VisitType = Context.getObjCIdType();
1536 break;
1537
1538 case BuiltinType::ObjCClass:
1539 VisitType = Context.getObjCClassType();
1540 break;
1541
1542 case BuiltinType::ObjCSel:
1543 VisitType = Context.getObjCSelType();
1544 break;
1545 }
1546
1547 if (!VisitType.isNull()) {
1548 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1549 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1550 TU));
1551 }
1552
1553 return false;
1554}
1555
1556bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1557 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1558}
1559
1560bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1561 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1562}
1563
1564bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1565 if (TL.isDefinition())
1566 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1567
1568 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1569}
1570
1571bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1572 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1573}
1574
1575bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001576 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
Guy Benyei11169dd2012-12-18 14:30:41 +00001577}
1578
Manman Rene6be26c2016-09-13 17:25:08 +00001579bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001580 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getBeginLoc(), TU)))
Manman Rene6be26c2016-09-13 17:25:08 +00001581 return true;
1582 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1583 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1584 TU)))
1585 return true;
1586 }
1587
1588 return false;
1589}
1590
Guy Benyei11169dd2012-12-18 14:30:41 +00001591bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1592 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1593 return true;
1594
Douglas Gregore9d95f12015-07-07 03:57:35 +00001595 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1596 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1597 return true;
1598 }
1599
Guy Benyei11169dd2012-12-18 14:30:41 +00001600 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1601 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1602 TU)))
1603 return true;
1604 }
1605
1606 return false;
1607}
1608
1609bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1610 return Visit(TL.getPointeeLoc());
1611}
1612
1613bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1614 return Visit(TL.getInnerLoc());
1615}
1616
1617bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1618 return Visit(TL.getPointeeLoc());
1619}
1620
1621bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1622 return Visit(TL.getPointeeLoc());
1623}
1624
1625bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1626 return Visit(TL.getPointeeLoc());
1627}
1628
1629bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1630 return Visit(TL.getPointeeLoc());
1631}
1632
1633bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1634 return Visit(TL.getPointeeLoc());
1635}
1636
1637bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1638 return Visit(TL.getModifiedLoc());
1639}
1640
1641bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1642 bool SkipResultType) {
Alp Toker42a16a62014-01-25 23:51:36 +00001643 if (!SkipResultType && Visit(TL.getReturnLoc()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001644 return true;
1645
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001646 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1647 if (Decl *D = TL.getParam(I))
Guy Benyei11169dd2012-12-18 14:30:41 +00001648 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1649 return true;
1650
1651 return false;
1652}
1653
1654bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1655 if (Visit(TL.getElementLoc()))
1656 return true;
1657
1658 if (Expr *Size = TL.getSizeExpr())
1659 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1660
1661 return false;
1662}
1663
Reid Kleckner8a365022013-06-24 17:51:48 +00001664bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1665 return Visit(TL.getOriginalLoc());
1666}
1667
Reid Kleckner0503a872013-12-05 01:23:43 +00001668bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1669 return Visit(TL.getOriginalLoc());
1670}
1671
Richard Smith600b5262017-01-26 20:40:47 +00001672bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1673 DeducedTemplateSpecializationTypeLoc TL) {
1674 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1675 TL.getTemplateNameLoc()))
1676 return true;
1677
1678 return false;
1679}
1680
Guy Benyei11169dd2012-12-18 14:30:41 +00001681bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1682 TemplateSpecializationTypeLoc TL) {
1683 // Visit the template name.
1684 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1685 TL.getTemplateNameLoc()))
1686 return true;
1687
1688 // Visit the template arguments.
1689 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1690 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1691 return true;
1692
1693 return false;
1694}
1695
1696bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1697 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1698}
1699
1700bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1701 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1702 return Visit(TSInfo->getTypeLoc());
1703
1704 return false;
1705}
1706
1707bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1708 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1709 return Visit(TSInfo->getTypeLoc());
1710
1711 return false;
1712}
1713
1714bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00001715 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00001716}
1717
1718bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1719 DependentTemplateSpecializationTypeLoc TL) {
1720 // Visit the nested-name-specifier, if there is one.
1721 if (TL.getQualifierLoc() &&
1722 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1723 return true;
1724
1725 // Visit the template arguments.
1726 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1727 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1728 return true;
1729
1730 return false;
1731}
1732
1733bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1734 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1735 return true;
1736
1737 return Visit(TL.getNamedTypeLoc());
1738}
1739
1740bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1741 return Visit(TL.getPatternLoc());
1742}
1743
1744bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1745 if (Expr *E = TL.getUnderlyingExpr())
1746 return Visit(MakeCXCursor(E, StmtParent, TU));
1747
1748 return false;
1749}
1750
1751bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1752 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1753}
1754
1755bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1756 return Visit(TL.getValueLoc());
1757}
1758
Xiuli Pan9c14e282016-01-09 12:53:17 +00001759bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1760 return Visit(TL.getValueLoc());
1761}
1762
Guy Benyei11169dd2012-12-18 14:30:41 +00001763#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1764bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1765 return Visit##PARENT##Loc(TL); \
1766}
1767
1768DEFAULT_TYPELOC_IMPL(Complex, Type)
1769DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1770DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1771DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1772DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001773DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
Erich Keanef702b022018-07-13 19:46:04 +00001774DEFAULT_TYPELOC_IMPL(DependentVector, Type)
Guy Benyei11169dd2012-12-18 14:30:41 +00001775DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1776DEFAULT_TYPELOC_IMPL(Vector, Type)
1777DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1778DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1779DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1780DEFAULT_TYPELOC_IMPL(Record, TagType)
1781DEFAULT_TYPELOC_IMPL(Enum, TagType)
1782DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1783DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1784DEFAULT_TYPELOC_IMPL(Auto, Type)
1785
1786bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1787 // Visit the nested-name-specifier, if present.
1788 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1789 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1790 return true;
1791
1792 if (D->isCompleteDefinition()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001793 for (const auto &I : D->bases()) {
1794 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001795 return true;
1796 }
1797 }
1798
1799 return VisitTagDecl(D);
1800}
1801
1802bool CursorVisitor::VisitAttributes(Decl *D) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001803 for (const auto *I : D->attrs())
Michael Wu40ff1052018-08-03 05:20:23 +00001804 if ((TU->ParsingOptions & CXTranslationUnit_VisitImplicitAttributes ||
1805 !I->isImplicit()) &&
1806 Visit(MakeCXCursor(I, D, TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00001807 return true;
1808
1809 return false;
1810}
1811
1812//===----------------------------------------------------------------------===//
1813// Data-recursive visitor methods.
1814//===----------------------------------------------------------------------===//
1815
1816namespace {
1817#define DEF_JOB(NAME, DATA, KIND)\
1818class NAME : public VisitorJob {\
1819public:\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001820 NAME(const DATA *d, CXCursor parent) : \
1821 VisitorJob(parent, VisitorJob::KIND, d) {} \
Guy Benyei11169dd2012-12-18 14:30:41 +00001822 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001823 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
Guy Benyei11169dd2012-12-18 14:30:41 +00001824};
1825
1826DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1827DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1828DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1829DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
Guy Benyei11169dd2012-12-18 14:30:41 +00001830DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1831DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1832DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1833#undef DEF_JOB
1834
James Y Knight04ec5bf2015-12-24 02:59:37 +00001835class ExplicitTemplateArgsVisit : public VisitorJob {
1836public:
1837 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1838 const TemplateArgumentLoc *End, CXCursor parent)
1839 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1840 End) {}
1841 static bool classof(const VisitorJob *VJ) {
1842 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1843 }
1844 const TemplateArgumentLoc *begin() const {
1845 return static_cast<const TemplateArgumentLoc *>(data[0]);
1846 }
1847 const TemplateArgumentLoc *end() {
1848 return static_cast<const TemplateArgumentLoc *>(data[1]);
1849 }
1850};
Guy Benyei11169dd2012-12-18 14:30:41 +00001851class DeclVisit : public VisitorJob {
1852public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001853 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
Guy Benyei11169dd2012-12-18 14:30:41 +00001854 VisitorJob(parent, VisitorJob::DeclVisitKind,
Craig Topper69186e72014-06-08 08:38:04 +00001855 D, isFirst ? (void*) 1 : (void*) nullptr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001856 static bool classof(const VisitorJob *VJ) {
1857 return VJ->getKind() == DeclVisitKind;
1858 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001859 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
Dmitri Gribenkoe5423a72015-03-23 19:23:50 +00001860 bool isFirst() const { return data[1] != nullptr; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001861};
1862class TypeLocVisit : public VisitorJob {
1863public:
1864 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1865 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1866 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1867
1868 static bool classof(const VisitorJob *VJ) {
1869 return VJ->getKind() == TypeLocVisitKind;
1870 }
1871
1872 TypeLoc get() const {
1873 QualType T = QualType::getFromOpaquePtr(data[0]);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001874 return TypeLoc(T, const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001875 }
1876};
1877
1878class LabelRefVisit : public VisitorJob {
1879public:
1880 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1881 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1882 labelLoc.getPtrEncoding()) {}
1883
1884 static bool classof(const VisitorJob *VJ) {
1885 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1886 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001887 const LabelDecl *get() const {
1888 return static_cast<const LabelDecl *>(data[0]);
1889 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001890 SourceLocation getLoc() const {
1891 return SourceLocation::getFromPtrEncoding(data[1]); }
1892};
1893
1894class NestedNameSpecifierLocVisit : public VisitorJob {
1895public:
1896 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1897 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1898 Qualifier.getNestedNameSpecifier(),
1899 Qualifier.getOpaqueData()) { }
1900
1901 static bool classof(const VisitorJob *VJ) {
1902 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1903 }
1904
1905 NestedNameSpecifierLoc get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001906 return NestedNameSpecifierLoc(
1907 const_cast<NestedNameSpecifier *>(
1908 static_cast<const NestedNameSpecifier *>(data[0])),
1909 const_cast<void *>(data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001910 }
1911};
1912
1913class DeclarationNameInfoVisit : public VisitorJob {
1914public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001915 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
Dmitri Gribenkodd7dacf2013-02-03 13:19:54 +00001916 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00001917 static bool classof(const VisitorJob *VJ) {
1918 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1919 }
1920 DeclarationNameInfo get() const {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001921 const Stmt *S = static_cast<const Stmt *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001922 switch (S->getStmtClass()) {
1923 default:
1924 llvm_unreachable("Unhandled Stmt");
1925 case clang::Stmt::MSDependentExistsStmtClass:
1926 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1927 case Stmt::CXXDependentScopeMemberExprClass:
1928 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1929 case Stmt::DependentScopeDeclRefExprClass:
1930 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001931 case Stmt::OMPCriticalDirectiveClass:
1932 return cast<OMPCriticalDirective>(S)->getDirectiveName();
Guy Benyei11169dd2012-12-18 14:30:41 +00001933 }
1934 }
1935};
1936class MemberRefVisit : public VisitorJob {
1937public:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001938 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00001939 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1940 L.getPtrEncoding()) {}
1941 static bool classof(const VisitorJob *VJ) {
1942 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1943 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001944 const FieldDecl *get() const {
1945 return static_cast<const FieldDecl *>(data[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001946 }
1947 SourceLocation getLoc() const {
1948 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1949 }
1950};
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001951class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001952 friend class OMPClauseEnqueue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001953 VisitorWorkList &WL;
1954 CXCursor Parent;
1955public:
1956 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1957 : WL(wl), Parent(parent) {}
1958
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001959 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1960 void VisitBlockExpr(const BlockExpr *B);
1961 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1962 void VisitCompoundStmt(const CompoundStmt *S);
1963 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1964 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1965 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1966 void VisitCXXNewExpr(const CXXNewExpr *E);
1967 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1968 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1969 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1970 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1971 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1972 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1973 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1974 void VisitCXXCatchStmt(const CXXCatchStmt *S);
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00001975 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001976 void VisitDeclRefExpr(const DeclRefExpr *D);
1977 void VisitDeclStmt(const DeclStmt *S);
1978 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1979 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1980 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1981 void VisitForStmt(const ForStmt *FS);
1982 void VisitGotoStmt(const GotoStmt *GS);
1983 void VisitIfStmt(const IfStmt *If);
1984 void VisitInitListExpr(const InitListExpr *IE);
1985 void VisitMemberExpr(const MemberExpr *M);
1986 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1987 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1988 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1989 void VisitOverloadExpr(const OverloadExpr *E);
1990 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1991 void VisitStmt(const Stmt *S);
1992 void VisitSwitchStmt(const SwitchStmt *S);
1993 void VisitWhileStmt(const WhileStmt *W);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00001994 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1995 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1996 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1997 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1998 void VisitVAArgExpr(const VAArgExpr *E);
1999 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
2000 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
2001 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
2002 void VisitLambdaExpr(const LambdaExpr *E);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002003 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
Alexander Musman3aaab662014-08-19 11:27:13 +00002004 void VisitOMPLoopDirective(const OMPLoopDirective *D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002005 void VisitOMPParallelDirective(const OMPParallelDirective *D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002006 void VisitOMPSimdDirective(const OMPSimdDirective *D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002007 void VisitOMPForDirective(const OMPForDirective *D);
Alexander Musmanf82886e2014-09-18 05:12:34 +00002008 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002009 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002010 void VisitOMPSectionDirective(const OMPSectionDirective *D);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002011 void VisitOMPSingleDirective(const OMPSingleDirective *D);
Alexander Musman80c22892014-07-17 08:54:58 +00002012 void VisitOMPMasterDirective(const OMPMasterDirective *D);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002013 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002014 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002015 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002016 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002017 void VisitOMPTaskDirective(const OMPTaskDirective *D);
Alexey Bataev68446b72014-07-18 07:47:19 +00002018 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002019 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
Alexey Bataev2df347a2014-07-18 10:17:07 +00002020 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002021 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002022 void
2023 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
Alexey Bataev80909872015-07-02 11:25:17 +00002024 void VisitOMPCancelDirective(const OMPCancelDirective *D);
Alexey Bataev6125da92014-07-21 11:26:11 +00002025 void VisitOMPFlushDirective(const OMPFlushDirective *D);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002026 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
Alexey Bataev0162e452014-07-22 10:10:35 +00002027 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002028 void VisitOMPTargetDirective(const OMPTargetDirective *D);
Michael Wong65f367f2015-07-21 13:44:28 +00002029 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
Samuel Antaodf67fc42016-01-19 19:15:56 +00002030 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
Samuel Antao72590762016-01-19 20:04:50 +00002031 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002032 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002033 void
2034 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002035 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002036 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002037 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002038 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
Carlo Bertolli9925f152016-06-27 14:55:37 +00002039 void VisitOMPDistributeParallelForDirective(
2040 const OMPDistributeParallelForDirective *D);
Kelvin Li4a39add2016-07-05 05:00:15 +00002041 void VisitOMPDistributeParallelForSimdDirective(
2042 const OMPDistributeParallelForSimdDirective *D);
Kelvin Li787f3fc2016-07-06 04:45:38 +00002043 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
Kelvin Lia579b912016-07-14 02:54:56 +00002044 void VisitOMPTargetParallelForSimdDirective(
2045 const OMPTargetParallelForSimdDirective *D);
Kelvin Li986330c2016-07-20 22:57:10 +00002046 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
Kelvin Li02532872016-08-05 14:37:37 +00002047 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
Kelvin Li4e325f72016-10-25 12:50:55 +00002048 void VisitOMPTeamsDistributeSimdDirective(
2049 const OMPTeamsDistributeSimdDirective *D);
Kelvin Li579e41c2016-11-30 23:51:03 +00002050 void VisitOMPTeamsDistributeParallelForSimdDirective(
2051 const OMPTeamsDistributeParallelForSimdDirective *D);
Kelvin Li7ade93f2016-12-09 03:24:30 +00002052 void VisitOMPTeamsDistributeParallelForDirective(
2053 const OMPTeamsDistributeParallelForDirective *D);
Kelvin Libf594a52016-12-17 05:48:59 +00002054 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
Kelvin Li83c451e2016-12-25 04:52:54 +00002055 void VisitOMPTargetTeamsDistributeDirective(
2056 const OMPTargetTeamsDistributeDirective *D);
Kelvin Li80e8f562016-12-29 22:16:30 +00002057 void VisitOMPTargetTeamsDistributeParallelForDirective(
2058 const OMPTargetTeamsDistributeParallelForDirective *D);
Kelvin Li1851df52017-01-03 05:23:48 +00002059 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2060 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
Kelvin Lida681182017-01-10 18:08:18 +00002061 void VisitOMPTargetTeamsDistributeSimdDirective(
2062 const OMPTargetTeamsDistributeSimdDirective *D);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002063
Guy Benyei11169dd2012-12-18 14:30:41 +00002064private:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002065 void AddDeclarationNameInfo(const Stmt *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002066 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
James Y Knight04ec5bf2015-12-24 02:59:37 +00002067 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2068 unsigned NumTemplateArgs);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002069 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2070 void AddStmt(const Stmt *S);
2071 void AddDecl(const Decl *D, bool isFirst = true);
Guy Benyei11169dd2012-12-18 14:30:41 +00002072 void AddTypeLoc(TypeSourceInfo *TI);
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002073 void EnqueueChildren(const Stmt *S);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002074 void EnqueueChildren(const OMPClause *S);
Guy Benyei11169dd2012-12-18 14:30:41 +00002075};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002076} // end anonyous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002077
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002078void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002079 // 'S' should always be non-null, since it comes from the
2080 // statement we are visiting.
2081 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2082}
2083
2084void
2085EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2086 if (Qualifier)
2087 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2088}
2089
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002090void EnqueueVisitor::AddStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002091 if (S)
2092 WL.push_back(StmtVisit(S, Parent));
2093}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002094void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002095 if (D)
2096 WL.push_back(DeclVisit(D, Parent, isFirst));
2097}
James Y Knight04ec5bf2015-12-24 02:59:37 +00002098void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2099 unsigned NumTemplateArgs) {
2100 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
Guy Benyei11169dd2012-12-18 14:30:41 +00002101}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002102void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002103 if (D)
2104 WL.push_back(MemberRefVisit(D, L, Parent));
2105}
2106void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2107 if (TI)
2108 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2109 }
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002110void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002111 unsigned size = WL.size();
Benjamin Kramer642f1732015-07-02 21:03:14 +00002112 for (const Stmt *SubStmt : S->children()) {
2113 AddStmt(SubStmt);
Guy Benyei11169dd2012-12-18 14:30:41 +00002114 }
2115 if (size == WL.size())
2116 return;
2117 // Now reverse the entries we just added. This will match the DFS
2118 // ordering performed by the worklist.
2119 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2120 std::reverse(I, E);
2121}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002122namespace {
2123class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2124 EnqueueVisitor *Visitor;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002125 /// Process clauses with list of variables.
Alexey Bataev756c1962013-09-24 03:17:45 +00002126 template <typename T>
2127 void VisitOMPClauseList(T *Node);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002128public:
2129 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2130#define OPENMP_CLAUSE(Name, Class) \
2131 void Visit##Class(const Class *C);
2132#include "clang/Basic/OpenMPKinds.def"
Alexey Bataev3392d762016-02-16 11:18:12 +00002133 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002134 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002135};
2136
Alexey Bataev3392d762016-02-16 11:18:12 +00002137void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2138 const OMPClauseWithPreInit *C) {
2139 Visitor->AddStmt(C->getPreInitStmt());
2140}
2141
Alexey Bataev005248a2016-02-25 05:25:57 +00002142void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2143 const OMPClauseWithPostUpdate *C) {
Alexey Bataev37e594c2016-03-04 07:21:16 +00002144 VisitOMPClauseWithPreInit(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002145 Visitor->AddStmt(C->getPostUpdateExpr());
2146}
2147
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002148void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002149 VisitOMPClauseWithPreInit(C);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00002150 Visitor->AddStmt(C->getCondition());
2151}
2152
Alexey Bataev3778b602014-07-17 07:32:53 +00002153void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2154 Visitor->AddStmt(C->getCondition());
2155}
2156
Alexey Bataev568a8332014-03-06 06:15:19 +00002157void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00002158 VisitOMPClauseWithPreInit(C);
Alexey Bataev568a8332014-03-06 06:15:19 +00002159 Visitor->AddStmt(C->getNumThreads());
2160}
2161
Alexey Bataev62c87d22014-03-21 04:51:18 +00002162void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2163 Visitor->AddStmt(C->getSafelen());
2164}
2165
Alexey Bataev66b15b52015-08-21 11:14:16 +00002166void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2167 Visitor->AddStmt(C->getSimdlen());
2168}
2169
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002170void OMPClauseEnqueue::VisitOMPAllocatorClause(const OMPAllocatorClause *C) {
2171 Visitor->AddStmt(C->getAllocator());
2172}
2173
Alexander Musman8bd31e62014-05-27 15:12:19 +00002174void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2175 Visitor->AddStmt(C->getNumForLoops());
2176}
2177
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002178void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
Alexey Bataev756c1962013-09-24 03:17:45 +00002179
Alexey Bataevbcbadb62014-05-06 06:04:14 +00002180void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2181
Alexey Bataev56dafe82014-06-20 07:16:17 +00002182void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002183 VisitOMPClauseWithPreInit(C);
Alexey Bataev56dafe82014-06-20 07:16:17 +00002184 Visitor->AddStmt(C->getChunkSize());
2185}
2186
Alexey Bataev10e775f2015-07-30 11:36:16 +00002187void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2188 Visitor->AddStmt(C->getNumForLoops());
2189}
Alexey Bataev142e1fc2014-06-20 09:44:06 +00002190
Alexey Bataev236070f2014-06-20 11:19:47 +00002191void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2192
Alexey Bataev7aea99a2014-07-17 12:19:31 +00002193void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2194
Alexey Bataev74ba3a52014-07-17 12:47:03 +00002195void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2196
Alexey Bataevf98b00c2014-07-23 02:27:21 +00002197void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2198
Alexey Bataevdea47612014-07-23 07:46:59 +00002199void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2200
Alexey Bataev67a4f222014-07-23 10:25:33 +00002201void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2202
Alexey Bataev459dec02014-07-24 06:46:57 +00002203void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2204
Alexey Bataev82bad8b2014-07-24 08:55:34 +00002205void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2206
Alexey Bataev346265e2015-09-25 10:37:12 +00002207void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2208
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002209void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2210
Alexey Bataevb825de12015-12-07 10:51:44 +00002211void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2212
Kelvin Li1408f912018-09-26 04:28:39 +00002213void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2214 const OMPUnifiedAddressClause *) {}
2215
Patrick Lyster4a370b92018-10-01 13:47:43 +00002216void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2217 const OMPUnifiedSharedMemoryClause *) {}
2218
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00002219void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2220 const OMPReverseOffloadClause *) {}
2221
Patrick Lyster3fe9e392018-10-11 14:41:10 +00002222void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2223 const OMPDynamicAllocatorsClause *) {}
2224
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00002225void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2226 const OMPAtomicDefaultMemOrderClause *) {}
2227
Michael Wonge710d542015-08-07 16:16:36 +00002228void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2229 Visitor->AddStmt(C->getDevice());
2230}
2231
Kelvin Li099bb8c2015-11-24 20:50:12 +00002232void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00002233 VisitOMPClauseWithPreInit(C);
Kelvin Li099bb8c2015-11-24 20:50:12 +00002234 Visitor->AddStmt(C->getNumTeams());
2235}
2236
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002237void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00002238 VisitOMPClauseWithPreInit(C);
Kelvin Lia15fb1a2015-11-27 18:47:36 +00002239 Visitor->AddStmt(C->getThreadLimit());
2240}
2241
Alexey Bataeva0569352015-12-01 10:17:31 +00002242void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2243 Visitor->AddStmt(C->getPriority());
2244}
2245
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00002246void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2247 Visitor->AddStmt(C->getGrainsize());
2248}
2249
Alexey Bataev382967a2015-12-08 12:06:20 +00002250void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2251 Visitor->AddStmt(C->getNumTasks());
2252}
2253
Alexey Bataev28c75412015-12-15 08:19:24 +00002254void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2255 Visitor->AddStmt(C->getHint());
2256}
2257
Alexey Bataev756c1962013-09-24 03:17:45 +00002258template<typename T>
2259void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
Alexey Bataev03b340a2014-10-21 03:16:40 +00002260 for (const auto *I : Node->varlists()) {
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002261 Visitor->AddStmt(I);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002262 }
Alexey Bataev756c1962013-09-24 03:17:45 +00002263}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002264
Alexey Bataeve04483e2019-03-27 14:14:31 +00002265void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) {
2266 VisitOMPClauseList(C);
2267 Visitor->AddStmt(C->getAllocator());
2268}
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002269void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002270 VisitOMPClauseList(C);
Alexey Bataev03b340a2014-10-21 03:16:40 +00002271 for (const auto *E : C->private_copies()) {
2272 Visitor->AddStmt(E);
2273 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002274}
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002275void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2276 const OMPFirstprivateClause *C) {
2277 VisitOMPClauseList(C);
Alexey Bataev417089f2016-02-17 13:19:37 +00002278 VisitOMPClauseWithPreInit(C);
2279 for (const auto *E : C->private_copies()) {
2280 Visitor->AddStmt(E);
2281 }
2282 for (const auto *E : C->inits()) {
2283 Visitor->AddStmt(E);
2284 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002285}
Alexander Musman1bb328c2014-06-04 13:06:39 +00002286void OMPClauseEnqueue::VisitOMPLastprivateClause(
2287 const OMPLastprivateClause *C) {
2288 VisitOMPClauseList(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002289 VisitOMPClauseWithPostUpdate(C);
Alexey Bataev38e89532015-04-16 04:54:05 +00002290 for (auto *E : C->private_copies()) {
2291 Visitor->AddStmt(E);
2292 }
2293 for (auto *E : C->source_exprs()) {
2294 Visitor->AddStmt(E);
2295 }
2296 for (auto *E : C->destination_exprs()) {
2297 Visitor->AddStmt(E);
2298 }
2299 for (auto *E : C->assignment_ops()) {
2300 Visitor->AddStmt(E);
2301 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00002302}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002303void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
Alexey Bataev756c1962013-09-24 03:17:45 +00002304 VisitOMPClauseList(C);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002305}
Alexey Bataevc5e02582014-06-16 07:08:35 +00002306void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2307 VisitOMPClauseList(C);
Alexey Bataev61205072016-03-02 04:57:40 +00002308 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002309 for (auto *E : C->privates()) {
2310 Visitor->AddStmt(E);
2311 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002312 for (auto *E : C->lhs_exprs()) {
2313 Visitor->AddStmt(E);
2314 }
2315 for (auto *E : C->rhs_exprs()) {
2316 Visitor->AddStmt(E);
2317 }
2318 for (auto *E : C->reduction_ops()) {
2319 Visitor->AddStmt(E);
2320 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00002321}
Alexey Bataev169d96a2017-07-18 20:17:46 +00002322void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2323 const OMPTaskReductionClause *C) {
2324 VisitOMPClauseList(C);
2325 VisitOMPClauseWithPostUpdate(C);
2326 for (auto *E : C->privates()) {
2327 Visitor->AddStmt(E);
2328 }
2329 for (auto *E : C->lhs_exprs()) {
2330 Visitor->AddStmt(E);
2331 }
2332 for (auto *E : C->rhs_exprs()) {
2333 Visitor->AddStmt(E);
2334 }
2335 for (auto *E : C->reduction_ops()) {
2336 Visitor->AddStmt(E);
2337 }
2338}
Alexey Bataevfa312f32017-07-21 18:48:21 +00002339void OMPClauseEnqueue::VisitOMPInReductionClause(
2340 const OMPInReductionClause *C) {
2341 VisitOMPClauseList(C);
2342 VisitOMPClauseWithPostUpdate(C);
2343 for (auto *E : C->privates()) {
2344 Visitor->AddStmt(E);
2345 }
2346 for (auto *E : C->lhs_exprs()) {
2347 Visitor->AddStmt(E);
2348 }
2349 for (auto *E : C->rhs_exprs()) {
2350 Visitor->AddStmt(E);
2351 }
2352 for (auto *E : C->reduction_ops()) {
2353 Visitor->AddStmt(E);
2354 }
Alexey Bataev88202be2017-07-27 13:20:36 +00002355 for (auto *E : C->taskgroup_descriptors())
2356 Visitor->AddStmt(E);
Alexey Bataevfa312f32017-07-21 18:48:21 +00002357}
Alexander Musman8dba6642014-04-22 13:09:42 +00002358void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2359 VisitOMPClauseList(C);
Alexey Bataev78849fb2016-03-09 09:49:00 +00002360 VisitOMPClauseWithPostUpdate(C);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00002361 for (const auto *E : C->privates()) {
2362 Visitor->AddStmt(E);
2363 }
Alexander Musman3276a272015-03-21 10:12:56 +00002364 for (const auto *E : C->inits()) {
2365 Visitor->AddStmt(E);
2366 }
2367 for (const auto *E : C->updates()) {
2368 Visitor->AddStmt(E);
2369 }
2370 for (const auto *E : C->finals()) {
2371 Visitor->AddStmt(E);
2372 }
Alexander Musman8dba6642014-04-22 13:09:42 +00002373 Visitor->AddStmt(C->getStep());
Alexander Musman3276a272015-03-21 10:12:56 +00002374 Visitor->AddStmt(C->getCalcStep());
Alexander Musman8dba6642014-04-22 13:09:42 +00002375}
Alexander Musmanf0d76e72014-05-29 14:36:25 +00002376void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2377 VisitOMPClauseList(C);
2378 Visitor->AddStmt(C->getAlignment());
2379}
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002380void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2381 VisitOMPClauseList(C);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002382 for (auto *E : C->source_exprs()) {
2383 Visitor->AddStmt(E);
2384 }
2385 for (auto *E : C->destination_exprs()) {
2386 Visitor->AddStmt(E);
2387 }
2388 for (auto *E : C->assignment_ops()) {
2389 Visitor->AddStmt(E);
2390 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00002391}
Alexey Bataevbae9a792014-06-27 10:37:06 +00002392void
2393OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2394 VisitOMPClauseList(C);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002395 for (auto *E : C->source_exprs()) {
2396 Visitor->AddStmt(E);
2397 }
2398 for (auto *E : C->destination_exprs()) {
2399 Visitor->AddStmt(E);
2400 }
2401 for (auto *E : C->assignment_ops()) {
2402 Visitor->AddStmt(E);
2403 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002404}
Alexey Bataev6125da92014-07-21 11:26:11 +00002405void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2406 VisitOMPClauseList(C);
2407}
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00002408void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2409 VisitOMPClauseList(C);
2410}
Kelvin Li0bff7af2015-11-23 05:32:03 +00002411void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2412 VisitOMPClauseList(C);
2413}
Carlo Bertollib4adf552016-01-15 18:50:31 +00002414void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2415 const OMPDistScheduleClause *C) {
Alexey Bataev3392d762016-02-16 11:18:12 +00002416 VisitOMPClauseWithPreInit(C);
Carlo Bertollib4adf552016-01-15 18:50:31 +00002417 Visitor->AddStmt(C->getChunkSize());
Carlo Bertollib4adf552016-01-15 18:50:31 +00002418}
Alexey Bataev3392d762016-02-16 11:18:12 +00002419void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2420 const OMPDefaultmapClause * /*C*/) {}
Samuel Antao661c0902016-05-26 17:39:58 +00002421void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2422 VisitOMPClauseList(C);
2423}
Samuel Antaoec172c62016-05-26 17:49:04 +00002424void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2425 VisitOMPClauseList(C);
2426}
Carlo Bertolli2404b172016-07-13 15:37:16 +00002427void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2428 VisitOMPClauseList(C);
2429}
Carlo Bertolli70594e92016-07-13 17:16:49 +00002430void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2431 VisitOMPClauseList(C);
2432}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002433}
Alexey Bataev756c1962013-09-24 03:17:45 +00002434
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002435void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2436 unsigned size = WL.size();
2437 OMPClauseEnqueue Visitor(this);
2438 Visitor.Visit(S);
2439 if (size == WL.size())
2440 return;
2441 // Now reverse the entries we just added. This will match the DFS
2442 // ordering performed by the worklist.
2443 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2444 std::reverse(I, E);
2445}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002446void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002447 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2448}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002449void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002450 AddDecl(B->getBlockDecl());
2451}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002452void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002453 EnqueueChildren(E);
2454 AddTypeLoc(E->getTypeSourceInfo());
2455}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002456void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
Pete Cooper57d3f142015-07-30 17:22:52 +00002457 for (auto &I : llvm::reverse(S->body()))
2458 AddStmt(I);
Guy Benyei11169dd2012-12-18 14:30:41 +00002459}
2460void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002461VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002462 AddStmt(S->getSubStmt());
2463 AddDeclarationNameInfo(S);
2464 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2465 AddNestedNameSpecifierLoc(QualifierLoc);
2466}
2467
2468void EnqueueVisitor::
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002469VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002470 if (E->hasExplicitTemplateArgs())
2471 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 AddDeclarationNameInfo(E);
2473 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2474 AddNestedNameSpecifierLoc(QualifierLoc);
2475 if (!E->isImplicitAccess())
2476 AddStmt(E->getBase());
2477}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002478void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002479 // Enqueue the initializer , if any.
2480 AddStmt(E->getInitializer());
2481 // Enqueue the array size, if any.
Richard Smithb9fb1212019-05-06 03:47:15 +00002482 AddStmt(E->getArraySize().getValueOr(nullptr));
Guy Benyei11169dd2012-12-18 14:30:41 +00002483 // Enqueue the allocated type.
2484 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2485 // Enqueue the placement arguments.
2486 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2487 AddStmt(E->getPlacementArg(I-1));
2488}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002489void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002490 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2491 AddStmt(CE->getArg(I-1));
2492 AddStmt(CE->getCallee());
2493 AddStmt(CE->getArg(0));
2494}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002495void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2496 const CXXPseudoDestructorExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002497 // Visit the name of the type being destroyed.
2498 AddTypeLoc(E->getDestroyedTypeInfo());
2499 // Visit the scope type that looks disturbingly like the nested-name-specifier
2500 // but isn't.
2501 AddTypeLoc(E->getScopeTypeInfo());
2502 // Visit the nested-name-specifier.
2503 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2504 AddNestedNameSpecifierLoc(QualifierLoc);
2505 // Visit base expression.
2506 AddStmt(E->getBase());
2507}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002508void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2509 const CXXScalarValueInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002510 AddTypeLoc(E->getTypeSourceInfo());
2511}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002512void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2513 const CXXTemporaryObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002514 EnqueueChildren(E);
2515 AddTypeLoc(E->getTypeSourceInfo());
2516}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002517void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002518 EnqueueChildren(E);
2519 if (E->isTypeOperand())
2520 AddTypeLoc(E->getTypeOperandSourceInfo());
2521}
2522
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002523void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2524 const CXXUnresolvedConstructExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002525 EnqueueChildren(E);
2526 AddTypeLoc(E->getTypeSourceInfo());
2527}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002528void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002529 EnqueueChildren(E);
2530 if (E->isTypeOperand())
2531 AddTypeLoc(E->getTypeOperandSourceInfo());
2532}
2533
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002534void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002535 EnqueueChildren(S);
2536 AddDecl(S->getExceptionDecl());
2537}
2538
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002539void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002540 AddStmt(S->getBody());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002541 AddStmt(S->getRangeInit());
Argyrios Kyrtzidiscde70692014-11-13 09:50:19 +00002542 AddDecl(S->getLoopVariable());
Argyrios Kyrtzidis99891242014-11-13 09:03:21 +00002543}
2544
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002545void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002546 if (DR->hasExplicitTemplateArgs())
2547 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002548 WL.push_back(DeclRefExprParts(DR, Parent));
2549}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002550void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2551 const DependentScopeDeclRefExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002552 if (E->hasExplicitTemplateArgs())
2553 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002554 AddDeclarationNameInfo(E);
2555 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2556}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002557void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002558 unsigned size = WL.size();
2559 bool isFirst = true;
Aaron Ballman535bbcc2014-03-14 17:01:24 +00002560 for (const auto *D : S->decls()) {
2561 AddDecl(D, isFirst);
Guy Benyei11169dd2012-12-18 14:30:41 +00002562 isFirst = false;
2563 }
2564 if (size == WL.size())
2565 return;
2566 // Now reverse the entries we just added. This will match the DFS
2567 // ordering performed by the worklist.
2568 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2569 std::reverse(I, E);
2570}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002571void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 AddStmt(E->getInit());
David Majnemerf7e36092016-06-23 00:15:04 +00002573 for (const DesignatedInitExpr::Designator &D :
2574 llvm::reverse(E->designators())) {
2575 if (D.isFieldDesignator()) {
2576 if (FieldDecl *Field = D.getField())
2577 AddMemberRef(Field, D.getFieldLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00002578 continue;
2579 }
David Majnemerf7e36092016-06-23 00:15:04 +00002580 if (D.isArrayDesignator()) {
2581 AddStmt(E->getArrayIndex(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002582 continue;
2583 }
David Majnemerf7e36092016-06-23 00:15:04 +00002584 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2585 AddStmt(E->getArrayRangeEnd(D));
2586 AddStmt(E->getArrayRangeStart(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002587 }
2588}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002589void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002590 EnqueueChildren(E);
2591 AddTypeLoc(E->getTypeInfoAsWritten());
2592}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002593void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 AddStmt(FS->getBody());
2595 AddStmt(FS->getInc());
2596 AddStmt(FS->getCond());
2597 AddDecl(FS->getConditionVariable());
2598 AddStmt(FS->getInit());
2599}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002600void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002601 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2602}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002603void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002604 AddStmt(If->getElse());
2605 AddStmt(If->getThen());
2606 AddStmt(If->getCond());
2607 AddDecl(If->getConditionVariable());
2608}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002609void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002610 // We care about the syntactic form of the initializer list, only.
2611 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2612 IE = Syntactic;
2613 EnqueueChildren(IE);
2614}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002615void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002616 WL.push_back(MemberExprParts(M, Parent));
2617
2618 // If the base of the member access expression is an implicit 'this', don't
2619 // visit it.
2620 // FIXME: If we ever want to show these implicit accesses, this will be
2621 // unfortunate. However, clang_getCursor() relies on this behavior.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002622 if (M->isImplicitAccess())
2623 return;
2624
2625 // Ignore base anonymous struct/union fields, otherwise they will shadow the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002626 // real field that we are interested in.
Argyrios Kyrtzidis58d0e7a2015-03-13 04:40:07 +00002627 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2628 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2629 if (FD->isAnonymousStructOrUnion()) {
2630 AddStmt(SubME->getBase());
2631 return;
2632 }
2633 }
2634 }
2635
2636 AddStmt(M->getBase());
Guy Benyei11169dd2012-12-18 14:30:41 +00002637}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002638void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002639 AddTypeLoc(E->getEncodedTypeSourceInfo());
2640}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002641void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002642 EnqueueChildren(M);
2643 AddTypeLoc(M->getClassReceiverTypeInfo());
2644}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002645void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002646 // Visit the components of the offsetof expression.
2647 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002648 const OffsetOfNode &Node = E->getComponent(I-1);
2649 switch (Node.getKind()) {
2650 case OffsetOfNode::Array:
2651 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2652 break;
2653 case OffsetOfNode::Field:
2654 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2655 break;
2656 case OffsetOfNode::Identifier:
2657 case OffsetOfNode::Base:
2658 continue;
2659 }
2660 }
2661 // Visit the type into which we're computing the offset.
2662 AddTypeLoc(E->getTypeSourceInfo());
2663}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002664void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002665 if (E->hasExplicitTemplateArgs())
2666 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00002667 WL.push_back(OverloadExprParts(E, Parent));
2668}
2669void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002670 const UnaryExprOrTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002671 EnqueueChildren(E);
2672 if (E->isArgumentType())
2673 AddTypeLoc(E->getArgumentTypeInfo());
2674}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002675void EnqueueVisitor::VisitStmt(const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002676 EnqueueChildren(S);
2677}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002678void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002679 AddStmt(S->getBody());
2680 AddStmt(S->getCond());
2681 AddDecl(S->getConditionVariable());
2682}
2683
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002684void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002685 AddStmt(W->getBody());
2686 AddStmt(W->getCond());
2687 AddDecl(W->getConditionVariable());
2688}
2689
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002690void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 for (unsigned I = E->getNumArgs(); I > 0; --I)
2692 AddTypeLoc(E->getArg(I-1));
2693}
2694
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002695void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002696 AddTypeLoc(E->getQueriedTypeSourceInfo());
2697}
2698
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002699void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002700 EnqueueChildren(E);
2701}
2702
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002703void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002704 VisitOverloadExpr(U);
2705 if (!U->isImplicitAccess())
2706 AddStmt(U->getBase());
2707}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002708void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002709 AddStmt(E->getSubExpr());
2710 AddTypeLoc(E->getWrittenTypeInfo());
2711}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002712void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002713 WL.push_back(SizeOfPackExprParts(E, Parent));
2714}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002715void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002716 // If the opaque value has a source expression, just transparently
2717 // visit that. This is useful for (e.g.) pseudo-object expressions.
2718 if (Expr *SourceExpr = E->getSourceExpr())
2719 return Visit(SourceExpr);
2720}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002721void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002722 AddStmt(E->getBody());
2723 WL.push_back(LambdaExprParts(E, Parent));
2724}
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002725void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002726 // Treat the expression like its syntactic form.
2727 Visit(E->getSyntacticForm());
2728}
2729
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002730void EnqueueVisitor::VisitOMPExecutableDirective(
2731 const OMPExecutableDirective *D) {
2732 EnqueueChildren(D);
2733 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2734 E = D->clauses().end();
2735 I != E; ++I)
2736 EnqueueChildren(*I);
2737}
2738
Alexander Musman3aaab662014-08-19 11:27:13 +00002739void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2740 VisitOMPExecutableDirective(D);
2741}
2742
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002743void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2744 VisitOMPExecutableDirective(D);
2745}
2746
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002747void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002748 VisitOMPLoopDirective(D);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002749}
2750
Alexey Bataevf29276e2014-06-18 04:14:57 +00002751void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002752 VisitOMPLoopDirective(D);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002753}
2754
Alexander Musmanf82886e2014-09-18 05:12:34 +00002755void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2756 VisitOMPLoopDirective(D);
2757}
2758
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002759void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2760 VisitOMPExecutableDirective(D);
2761}
2762
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002763void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2764 VisitOMPExecutableDirective(D);
2765}
2766
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002767void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2768 VisitOMPExecutableDirective(D);
2769}
2770
Alexander Musman80c22892014-07-17 08:54:58 +00002771void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2772 VisitOMPExecutableDirective(D);
2773}
2774
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002775void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2776 VisitOMPExecutableDirective(D);
2777 AddDeclarationNameInfo(D);
2778}
2779
Alexey Bataev4acb8592014-07-07 13:01:15 +00002780void
2781EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
Alexander Musman3aaab662014-08-19 11:27:13 +00002782 VisitOMPLoopDirective(D);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002783}
2784
Alexander Musmane4e893b2014-09-23 09:33:00 +00002785void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2786 const OMPParallelForSimdDirective *D) {
2787 VisitOMPLoopDirective(D);
2788}
2789
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002790void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2791 const OMPParallelSectionsDirective *D) {
2792 VisitOMPExecutableDirective(D);
2793}
2794
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002795void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2796 VisitOMPExecutableDirective(D);
2797}
2798
Alexey Bataev68446b72014-07-18 07:47:19 +00002799void
2800EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2801 VisitOMPExecutableDirective(D);
2802}
2803
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002804void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2805 VisitOMPExecutableDirective(D);
2806}
2807
Alexey Bataev2df347a2014-07-18 10:17:07 +00002808void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2809 VisitOMPExecutableDirective(D);
2810}
2811
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002812void EnqueueVisitor::VisitOMPTaskgroupDirective(
2813 const OMPTaskgroupDirective *D) {
2814 VisitOMPExecutableDirective(D);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00002815 if (const Expr *E = D->getReductionRef())
2816 VisitStmt(E);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002817}
2818
Alexey Bataev6125da92014-07-21 11:26:11 +00002819void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2820 VisitOMPExecutableDirective(D);
2821}
2822
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002823void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2824 VisitOMPExecutableDirective(D);
2825}
2826
Alexey Bataev0162e452014-07-22 10:10:35 +00002827void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2828 VisitOMPExecutableDirective(D);
2829}
2830
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002831void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2832 VisitOMPExecutableDirective(D);
2833}
2834
Michael Wong65f367f2015-07-21 13:44:28 +00002835void EnqueueVisitor::VisitOMPTargetDataDirective(const
2836 OMPTargetDataDirective *D) {
2837 VisitOMPExecutableDirective(D);
2838}
2839
Samuel Antaodf67fc42016-01-19 19:15:56 +00002840void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2841 const OMPTargetEnterDataDirective *D) {
2842 VisitOMPExecutableDirective(D);
2843}
2844
Samuel Antao72590762016-01-19 20:04:50 +00002845void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2846 const OMPTargetExitDataDirective *D) {
2847 VisitOMPExecutableDirective(D);
2848}
2849
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002850void EnqueueVisitor::VisitOMPTargetParallelDirective(
2851 const OMPTargetParallelDirective *D) {
2852 VisitOMPExecutableDirective(D);
2853}
2854
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002855void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2856 const OMPTargetParallelForDirective *D) {
2857 VisitOMPLoopDirective(D);
2858}
2859
Alexey Bataev13314bf2014-10-09 04:18:56 +00002860void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2861 VisitOMPExecutableDirective(D);
2862}
2863
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002864void EnqueueVisitor::VisitOMPCancellationPointDirective(
2865 const OMPCancellationPointDirective *D) {
2866 VisitOMPExecutableDirective(D);
2867}
2868
Alexey Bataev80909872015-07-02 11:25:17 +00002869void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2870 VisitOMPExecutableDirective(D);
2871}
2872
Alexey Bataev49f6e782015-12-01 04:18:41 +00002873void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2874 VisitOMPLoopDirective(D);
2875}
2876
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002877void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2878 const OMPTaskLoopSimdDirective *D) {
2879 VisitOMPLoopDirective(D);
2880}
2881
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002882void EnqueueVisitor::VisitOMPDistributeDirective(
2883 const OMPDistributeDirective *D) {
2884 VisitOMPLoopDirective(D);
2885}
2886
Carlo Bertolli9925f152016-06-27 14:55:37 +00002887void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2888 const OMPDistributeParallelForDirective *D) {
2889 VisitOMPLoopDirective(D);
2890}
2891
Kelvin Li4a39add2016-07-05 05:00:15 +00002892void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2893 const OMPDistributeParallelForSimdDirective *D) {
2894 VisitOMPLoopDirective(D);
2895}
2896
Kelvin Li787f3fc2016-07-06 04:45:38 +00002897void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2898 const OMPDistributeSimdDirective *D) {
2899 VisitOMPLoopDirective(D);
2900}
2901
Kelvin Lia579b912016-07-14 02:54:56 +00002902void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2903 const OMPTargetParallelForSimdDirective *D) {
2904 VisitOMPLoopDirective(D);
2905}
2906
Kelvin Li986330c2016-07-20 22:57:10 +00002907void EnqueueVisitor::VisitOMPTargetSimdDirective(
2908 const OMPTargetSimdDirective *D) {
2909 VisitOMPLoopDirective(D);
2910}
2911
Kelvin Li02532872016-08-05 14:37:37 +00002912void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2913 const OMPTeamsDistributeDirective *D) {
2914 VisitOMPLoopDirective(D);
2915}
2916
Kelvin Li4e325f72016-10-25 12:50:55 +00002917void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2918 const OMPTeamsDistributeSimdDirective *D) {
2919 VisitOMPLoopDirective(D);
2920}
2921
Kelvin Li579e41c2016-11-30 23:51:03 +00002922void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2923 const OMPTeamsDistributeParallelForSimdDirective *D) {
2924 VisitOMPLoopDirective(D);
2925}
2926
Kelvin Li7ade93f2016-12-09 03:24:30 +00002927void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2928 const OMPTeamsDistributeParallelForDirective *D) {
2929 VisitOMPLoopDirective(D);
2930}
2931
Kelvin Libf594a52016-12-17 05:48:59 +00002932void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2933 const OMPTargetTeamsDirective *D) {
2934 VisitOMPExecutableDirective(D);
2935}
2936
Kelvin Li83c451e2016-12-25 04:52:54 +00002937void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2938 const OMPTargetTeamsDistributeDirective *D) {
2939 VisitOMPLoopDirective(D);
2940}
2941
Kelvin Li80e8f562016-12-29 22:16:30 +00002942void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2943 const OMPTargetTeamsDistributeParallelForDirective *D) {
2944 VisitOMPLoopDirective(D);
2945}
2946
Kelvin Li1851df52017-01-03 05:23:48 +00002947void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2948 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2949 VisitOMPLoopDirective(D);
2950}
2951
Kelvin Lida681182017-01-10 18:08:18 +00002952void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2953 const OMPTargetTeamsDistributeSimdDirective *D) {
2954 VisitOMPLoopDirective(D);
2955}
2956
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002957void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002958 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2959}
2960
2961bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2962 if (RegionOfInterest.isValid()) {
2963 SourceRange Range = getRawCursorExtent(C);
2964 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2965 return false;
2966 }
2967 return true;
2968}
2969
2970bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2971 while (!WL.empty()) {
2972 // Dequeue the worklist item.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002973 VisitorJob LI = WL.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002974
2975 // Set the Parent field, then back to its old value once we're done.
2976 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2977
2978 switch (LI.getKind()) {
2979 case VisitorJob::DeclVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00002980 const Decl *D = cast<DeclVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00002981 if (!D)
2982 continue;
2983
2984 // For now, perform default visitation for Decls.
2985 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2986 cast<DeclVisit>(&LI)->isFirst())))
2987 return true;
2988
2989 continue;
2990 }
2991 case VisitorJob::ExplicitTemplateArgsVisitKind: {
James Y Knight04ec5bf2015-12-24 02:59:37 +00002992 for (const TemplateArgumentLoc &Arg :
2993 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2994 if (VisitTemplateArgumentLoc(Arg))
Guy Benyei11169dd2012-12-18 14:30:41 +00002995 return true;
2996 }
2997 continue;
2998 }
2999 case VisitorJob::TypeLocVisitKind: {
3000 // Perform default visitation for TypeLocs.
3001 if (Visit(cast<TypeLocVisit>(&LI)->get()))
3002 return true;
3003 continue;
3004 }
3005 case VisitorJob::LabelRefVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003006 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003007 if (LabelStmt *stmt = LS->getStmt()) {
3008 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3009 TU))) {
3010 return true;
3011 }
3012 }
3013 continue;
3014 }
3015
3016 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3017 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3018 if (VisitNestedNameSpecifierLoc(V->get()))
3019 return true;
3020 continue;
3021 }
3022
3023 case VisitorJob::DeclarationNameInfoVisitKind: {
3024 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3025 ->get()))
3026 return true;
3027 continue;
3028 }
3029 case VisitorJob::MemberRefVisitKind: {
3030 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3031 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3032 return true;
3033 continue;
3034 }
3035 case VisitorJob::StmtVisitKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003036 const Stmt *S = cast<StmtVisit>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003037 if (!S)
3038 continue;
3039
3040 // Update the current cursor.
3041 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3042 if (!IsInRegionOfInterest(Cursor))
3043 continue;
3044 switch (Visitor(Cursor, Parent, ClientData)) {
3045 case CXChildVisit_Break: return true;
3046 case CXChildVisit_Continue: break;
3047 case CXChildVisit_Recurse:
3048 if (PostChildrenVisitor)
Craig Topper69186e72014-06-08 08:38:04 +00003049 WL.push_back(PostChildrenVisit(nullptr, Cursor));
Guy Benyei11169dd2012-12-18 14:30:41 +00003050 EnqueueWorkList(WL, S);
3051 break;
3052 }
3053 continue;
3054 }
3055 case VisitorJob::MemberExprPartsKind: {
3056 // Handle the other pieces in the MemberExpr besides the base.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003057 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003058
3059 // Visit the nested-name-specifier
3060 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3061 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3062 return true;
3063
3064 // Visit the declaration name.
3065 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3066 return true;
3067
3068 // Visit the explicitly-specified template arguments, if any.
3069 if (M->hasExplicitTemplateArgs()) {
3070 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3071 *ArgEnd = Arg + M->getNumTemplateArgs();
3072 Arg != ArgEnd; ++Arg) {
3073 if (VisitTemplateArgumentLoc(*Arg))
3074 return true;
3075 }
3076 }
3077 continue;
3078 }
3079 case VisitorJob::DeclRefExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003080 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003081 // Visit nested-name-specifier, if present.
3082 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3083 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3084 return true;
3085 // Visit declaration name.
3086 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3087 return true;
3088 continue;
3089 }
3090 case VisitorJob::OverloadExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003091 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003092 // Visit the nested-name-specifier.
3093 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3094 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3095 return true;
3096 // Visit the declaration name.
3097 if (VisitDeclarationNameInfo(O->getNameInfo()))
3098 return true;
3099 // Visit the overloaded declaration reference.
3100 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3101 return true;
3102 continue;
3103 }
3104 case VisitorJob::SizeOfPackExprPartsKind: {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003105 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003106 NamedDecl *Pack = E->getPack();
3107 if (isa<TemplateTypeParmDecl>(Pack)) {
3108 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3109 E->getPackLoc(), TU)))
3110 return true;
3111
3112 continue;
3113 }
3114
3115 if (isa<TemplateTemplateParmDecl>(Pack)) {
3116 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3117 E->getPackLoc(), TU)))
3118 return true;
3119
3120 continue;
3121 }
3122
3123 // Non-type template parameter packs and function parameter packs are
3124 // treated like DeclRefExpr cursors.
3125 continue;
3126 }
3127
3128 case VisitorJob::LambdaExprPartsKind: {
3129 // Visit captures.
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003130 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
Guy Benyei11169dd2012-12-18 14:30:41 +00003131 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3132 CEnd = E->explicit_capture_end();
3133 C != CEnd; ++C) {
Richard Smithba71c082013-05-16 06:20:58 +00003134 // FIXME: Lambda init-captures.
3135 if (!C->capturesVariable())
Guy Benyei11169dd2012-12-18 14:30:41 +00003136 continue;
Richard Smithba71c082013-05-16 06:20:58 +00003137
Guy Benyei11169dd2012-12-18 14:30:41 +00003138 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3139 C->getLocation(),
3140 TU)))
3141 return true;
3142 }
3143
Haojian Wuef87c262018-12-18 15:29:12 +00003144 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00003145 // Visit parameters and return type, if present.
Haojian Wuef87c262018-12-18 15:29:12 +00003146 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3147 if (E->hasExplicitParameters()) {
3148 // Visit parameters.
3149 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3150 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
Guy Benyei11169dd2012-12-18 14:30:41 +00003151 return true;
Haojian Wuef87c262018-12-18 15:29:12 +00003152 }
3153 if (E->hasExplicitResultType()) {
3154 // Visit result type.
3155 if (Visit(Proto.getReturnLoc()))
3156 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003157 }
3158 }
3159 break;
3160 }
3161
3162 case VisitorJob::PostChildrenVisitKind:
3163 if (PostChildrenVisitor(Parent, ClientData))
3164 return true;
3165 break;
3166 }
3167 }
3168 return false;
3169}
3170
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00003171bool CursorVisitor::Visit(const Stmt *S) {
Craig Topper69186e72014-06-08 08:38:04 +00003172 VisitorWorkList *WL = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003173 if (!WorkListFreeList.empty()) {
3174 WL = WorkListFreeList.back();
3175 WL->clear();
3176 WorkListFreeList.pop_back();
3177 }
3178 else {
3179 WL = new VisitorWorkList();
3180 WorkListCache.push_back(WL);
3181 }
3182 EnqueueWorkList(*WL, S);
3183 bool result = RunVisitorWorkList(*WL);
3184 WorkListFreeList.push_back(WL);
3185 return result;
3186}
3187
3188namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003189typedef SmallVector<SourceRange, 4> RefNamePieces;
James Y Knight04ec5bf2015-12-24 02:59:37 +00003190RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3191 const DeclarationNameInfo &NI, SourceRange QLoc,
3192 const SourceRange *TemplateArgsLoc = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003193 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3194 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3195 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3196
3197 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3198
3199 RefNamePieces Pieces;
3200
3201 if (WantQualifier && QLoc.isValid())
3202 Pieces.push_back(QLoc);
3203
3204 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3205 Pieces.push_back(NI.getLoc());
James Y Knight04ec5bf2015-12-24 02:59:37 +00003206
3207 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3208 Pieces.push_back(*TemplateArgsLoc);
3209
Guy Benyei11169dd2012-12-18 14:30:41 +00003210 if (Kind == DeclarationName::CXXOperatorName) {
3211 Pieces.push_back(SourceLocation::getFromRawEncoding(
3212 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3213 Pieces.push_back(SourceLocation::getFromRawEncoding(
3214 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3215 }
3216
3217 if (WantSinglePiece) {
3218 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3219 Pieces.clear();
3220 Pieces.push_back(R);
3221 }
3222
3223 return Pieces;
3224}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003225}
Guy Benyei11169dd2012-12-18 14:30:41 +00003226
3227//===----------------------------------------------------------------------===//
3228// Misc. API hooks.
3229//===----------------------------------------------------------------------===//
3230
Chad Rosier05c71aa2013-03-27 18:28:23 +00003231static void fatal_error_handler(void *user_data, const std::string& reason,
3232 bool gen_crash_diag) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003233 // Write the result out to stderr avoiding errs() because raw_ostreams can
3234 // call report_fatal_error.
3235 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3236 ::abort();
3237}
3238
Chandler Carruth66660742014-06-27 16:37:27 +00003239namespace {
3240struct RegisterFatalErrorHandler {
3241 RegisterFatalErrorHandler() {
3242 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3243 }
3244};
3245}
3246
3247static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3248
Guy Benyei11169dd2012-12-18 14:30:41 +00003249CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3250 int displayDiagnostics) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003251 // We use crash recovery to make some of our APIs more reliable, implicitly
3252 // enable it.
Argyrios Kyrtzidis3701f542013-11-27 08:58:09 +00003253 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3254 llvm::CrashRecoveryContext::Enable();
Guy Benyei11169dd2012-12-18 14:30:41 +00003255
Chandler Carruth66660742014-06-27 16:37:27 +00003256 // Look through the managed static to trigger construction of the managed
3257 // static which registers our fatal error handler. This ensures it is only
3258 // registered once.
3259 (void)*RegisterFatalErrorHandlerOnce;
Guy Benyei11169dd2012-12-18 14:30:41 +00003260
Adrian Prantlbc068582015-07-08 01:00:30 +00003261 // Initialize targets for clang module support.
3262 llvm::InitializeAllTargets();
3263 llvm::InitializeAllTargetMCs();
3264 llvm::InitializeAllAsmPrinters();
3265 llvm::InitializeAllAsmParsers();
3266
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003267 CIndexer *CIdxr = new CIndexer();
3268
Guy Benyei11169dd2012-12-18 14:30:41 +00003269 if (excludeDeclarationsFromPCH)
3270 CIdxr->setOnlyLocalDecls();
3271 if (displayDiagnostics)
3272 CIdxr->setDisplayDiagnostics();
3273
3274 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3275 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3276 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3277 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3278 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3279 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3280
3281 return CIdxr;
3282}
3283
3284void clang_disposeIndex(CXIndex CIdx) {
3285 if (CIdx)
3286 delete static_cast<CIndexer *>(CIdx);
3287}
3288
3289void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3290 if (CIdx)
3291 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3292}
3293
3294unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3295 if (CIdx)
3296 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3297 return 0;
3298}
3299
Alex Lorenz08615792017-12-04 21:56:36 +00003300void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3301 const char *Path) {
3302 if (CIdx)
3303 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3304}
3305
Guy Benyei11169dd2012-12-18 14:30:41 +00003306void clang_toggleCrashRecovery(unsigned isEnabled) {
3307 if (isEnabled)
3308 llvm::CrashRecoveryContext::Enable();
3309 else
3310 llvm::CrashRecoveryContext::Disable();
3311}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003312
Guy Benyei11169dd2012-12-18 14:30:41 +00003313CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3314 const char *ast_filename) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003315 CXTranslationUnit TU;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003316 enum CXErrorCode Result =
3317 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
Reid Klecknerfd48fc62014-02-12 23:56:20 +00003318 (void)Result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003319 assert((TU && Result == CXError_Success) ||
3320 (!TU && Result != CXError_Success));
3321 return TU;
3322}
3323
3324enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3325 const char *ast_filename,
3326 CXTranslationUnit *out_TU) {
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003327 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003328 *out_TU = nullptr;
Dmitri Gribenko8850cda2014-02-19 10:24:00 +00003329
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003330 if (!CIdx || !ast_filename || !out_TU)
3331 return CXError_InvalidArguments;
Guy Benyei11169dd2012-12-18 14:30:41 +00003332
Argyrios Kyrtzidis27021012013-05-24 22:24:07 +00003333 LOG_FUNC_SECTION {
3334 *Log << ast_filename;
3335 }
3336
Guy Benyei11169dd2012-12-18 14:30:41 +00003337 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3338 FileSystemOptions FileSystemOpts;
3339
Justin Bognerd512c1e2014-10-15 00:33:06 +00003340 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3341 CompilerInstance::createDiagnostics(new DiagnosticOptions());
David Blaikie6f7382d2014-08-10 19:08:04 +00003342 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +00003343 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3344 ASTUnit::LoadEverything, Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +00003345 FileSystemOpts, /*UseDebugInfo=*/false,
3346 CXXIdx->getOnlyLocalDecls(), None,
David Blaikie6f7382d2014-08-10 19:08:04 +00003347 /*CaptureDiagnostics=*/true,
3348 /*AllowPCHWithCompilerErrors=*/true,
3349 /*UserFilesAreVolatile=*/true);
David Blaikieea4395e2017-01-06 19:49:01 +00003350 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003351 return *out_TU ? CXError_Success : CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003352}
3353
3354unsigned clang_defaultEditingTranslationUnitOptions() {
3355 return CXTranslationUnit_PrecompiledPreamble |
3356 CXTranslationUnit_CacheCompletionResults;
3357}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003358
Guy Benyei11169dd2012-12-18 14:30:41 +00003359CXTranslationUnit
3360clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3361 const char *source_filename,
3362 int num_command_line_args,
3363 const char * const *command_line_args,
3364 unsigned num_unsaved_files,
3365 struct CXUnsavedFile *unsaved_files) {
3366 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3367 return clang_parseTranslationUnit(CIdx, source_filename,
3368 command_line_args, num_command_line_args,
3369 unsaved_files, num_unsaved_files,
3370 Options);
3371}
3372
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003373static CXErrorCode
3374clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3375 const char *const *command_line_args,
3376 int num_command_line_args,
3377 ArrayRef<CXUnsavedFile> unsaved_files,
3378 unsigned options, CXTranslationUnit *out_TU) {
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003379 // Set up the initial return values.
3380 if (out_TU)
Craig Topper69186e72014-06-08 08:38:04 +00003381 *out_TU = nullptr;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003382
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003383 // Check arguments.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003384 if (!CIdx || !out_TU)
3385 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003386
Guy Benyei11169dd2012-12-18 14:30:41 +00003387 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3388
3389 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3390 setThreadBackgroundPriority();
3391
3392 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003393 bool CreatePreambleOnFirstParse =
3394 options & CXTranslationUnit_CreatePreambleOnFirstParse;
Guy Benyei11169dd2012-12-18 14:30:41 +00003395 // FIXME: Add a flag for modules.
3396 TranslationUnitKind TUKind
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003397 = (options & (CXTranslationUnit_Incomplete |
3398 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
Alp Toker8c8a8752013-12-03 06:53:35 +00003399 bool CacheCodeCompletionResults
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003400 = options & CXTranslationUnit_CacheCompletionResults;
3401 bool IncludeBriefCommentsInCodeCompletion
3402 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003403 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3404 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00003405 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3406 if (options & CXTranslationUnit_SkipFunctionBodies) {
3407 SkipFunctionBodies =
3408 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3409 ? SkipFunctionBodiesScope::Preamble
3410 : SkipFunctionBodiesScope::PreambleAndMainFile;
3411 }
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00003412
3413 // Configure the diagnostics.
3414 IntrusiveRefCntPtr<DiagnosticsEngine>
Sean Silvaf1b49e22013-01-20 01:58:28 +00003415 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
Guy Benyei11169dd2012-12-18 14:30:41 +00003416
Manuel Klimek016c0242016-03-01 10:56:19 +00003417 if (options & CXTranslationUnit_KeepGoing)
Ivan Donchevskii878271b2019-03-07 10:13:50 +00003418 Diags->setFatalsAsError(true);
Manuel Klimek016c0242016-03-01 10:56:19 +00003419
Guy Benyei11169dd2012-12-18 14:30:41 +00003420 // Recover resources if we crash before exiting this function.
3421 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3422 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00003423 DiagCleanup(Diags.get());
Guy Benyei11169dd2012-12-18 14:30:41 +00003424
Ahmed Charlesb8984322014-03-07 20:03:18 +00003425 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3426 new std::vector<ASTUnit::RemappedFile>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003427
3428 // Recover resources if we crash before exiting this function.
3429 llvm::CrashRecoveryContextCleanupRegistrar<
3430 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3431
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003432 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003433 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00003434 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00003435 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003436 }
3437
Ahmed Charlesb8984322014-03-07 20:03:18 +00003438 std::unique_ptr<std::vector<const char *>> Args(
3439 new std::vector<const char *>());
Guy Benyei11169dd2012-12-18 14:30:41 +00003440
3441 // Recover resources if we crash before exiting this method.
3442 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3443 ArgsCleanup(Args.get());
3444
3445 // Since the Clang C library is primarily used by batch tools dealing with
3446 // (often very broken) source code, where spell-checking can have a
3447 // significant negative impact on performance (particularly when
3448 // precompiled headers are involved), we disable it by default.
3449 // Only do this if we haven't found a spell-checking-related argument.
3450 bool FoundSpellCheckingArgument = false;
3451 for (int I = 0; I != num_command_line_args; ++I) {
3452 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3453 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3454 FoundSpellCheckingArgument = true;
3455 break;
3456 }
3457 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003458 Args->insert(Args->end(), command_line_args,
3459 command_line_args + num_command_line_args);
3460
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003461 if (!FoundSpellCheckingArgument)
3462 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3463
Guy Benyei11169dd2012-12-18 14:30:41 +00003464 // The 'source_filename' argument is optional. If the caller does not
3465 // specify it then it is assumed that the source file is specified
3466 // in the actual argument list.
3467 // Put the source file after command_line_args otherwise if '-x' flag is
3468 // present it will be unused.
3469 if (source_filename)
3470 Args->push_back(source_filename);
3471
3472 // Do we need the detailed preprocessing record?
3473 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3474 Args->push_back("-Xclang");
3475 Args->push_back("-detailed-preprocessing-record");
3476 }
Alex Lorenzcb006402017-04-27 13:47:03 +00003477
3478 // Suppress any editor placeholder diagnostics.
3479 Args->push_back("-fallow-editor-placeholders");
3480
Guy Benyei11169dd2012-12-18 14:30:41 +00003481 unsigned NumErrors = Diags->getClient()->getNumErrors();
Ahmed Charlesb8984322014-03-07 20:03:18 +00003482 std::unique_ptr<ASTUnit> ErrUnit;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003483 // Unless the user specified that they want the preamble on the first parse
3484 // set it up to be created on the first reparse. This makes the first parse
3485 // faster, trading for a slower (first) reparse.
3486 unsigned PrecompilePreambleAfterNParses =
3487 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
Alex Lorenz08615792017-12-04 21:56:36 +00003488
Alex Lorenz08615792017-12-04 21:56:36 +00003489 LibclangInvocationReporter InvocationReporter(
3490 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
Alex Lorenz690f0e22017-12-07 20:37:50 +00003491 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3492 unsaved_files);
Ahmed Charlesb8984322014-03-07 20:03:18 +00003493 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003494 Args->data(), Args->data() + Args->size(),
3495 CXXIdx->getPCHContainerOperations(), Diags,
Ahmed Charlesb8984322014-03-07 20:03:18 +00003496 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3497 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00003498 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3499 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00003500 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00003501 /*UserFilesAreVolatile=*/true, ForSerialization,
3502 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3503 &ErrUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00003504
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003505 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003506 if (!Unit && !ErrUnit)
3507 return CXError_ASTReadError;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003508
Guy Benyei11169dd2012-12-18 14:30:41 +00003509 if (NumErrors != Diags->getClient()->getNumErrors()) {
3510 // Make sure to check that 'Unit' is non-NULL.
3511 if (CXXIdx->getDisplayDiagnostics())
3512 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3513 }
3514
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003515 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3516 return CXError_ASTReadError;
3517
David Blaikieea4395e2017-01-06 19:49:01 +00003518 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
Alex Lorenz690f0e22017-12-07 20:37:50 +00003519 if (CXTranslationUnitImpl *TU = *out_TU) {
3520 TU->ParsingOptions = options;
3521 TU->Arguments.reserve(Args->size());
3522 for (const char *Arg : *Args)
3523 TU->Arguments.push_back(Arg);
3524 return CXError_Success;
3525 }
3526 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003527}
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003528
3529CXTranslationUnit
3530clang_parseTranslationUnit(CXIndex CIdx,
3531 const char *source_filename,
3532 const char *const *command_line_args,
3533 int num_command_line_args,
3534 struct CXUnsavedFile *unsaved_files,
3535 unsigned num_unsaved_files,
3536 unsigned options) {
3537 CXTranslationUnit TU;
3538 enum CXErrorCode Result = clang_parseTranslationUnit2(
3539 CIdx, source_filename, command_line_args, num_command_line_args,
3540 unsaved_files, num_unsaved_files, options, &TU);
Reid Kleckner6eaf05a2014-02-13 01:19:59 +00003541 (void)Result;
Dmitri Gribenko1bf8d912014-02-18 15:20:02 +00003542 assert((TU && Result == CXError_Success) ||
3543 (!TU && Result != CXError_Success));
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003544 return TU;
3545}
3546
3547enum CXErrorCode clang_parseTranslationUnit2(
Benjamin Kramerc02670e2015-11-18 16:14:27 +00003548 CXIndex CIdx, const char *source_filename,
3549 const char *const *command_line_args, int num_command_line_args,
3550 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3551 unsigned options, CXTranslationUnit *out_TU) {
3552 SmallVector<const char *, 4> Args;
3553 Args.push_back("clang");
3554 Args.append(command_line_args, command_line_args + num_command_line_args);
3555 return clang_parseTranslationUnit2FullArgv(
3556 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3557 num_unsaved_files, options, out_TU);
3558}
3559
3560enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3561 CXIndex CIdx, const char *source_filename,
3562 const char *const *command_line_args, int num_command_line_args,
3563 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3564 unsigned options, CXTranslationUnit *out_TU) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003565 LOG_FUNC_SECTION {
3566 *Log << source_filename << ": ";
3567 for (int i = 0; i != num_command_line_args; ++i)
3568 *Log << command_line_args[i] << " ";
3569 }
3570
Alp Toker9d85b182014-07-07 01:23:14 +00003571 if (num_unsaved_files && !unsaved_files)
3572 return CXError_InvalidArguments;
3573
Alp Toker5c532982014-07-07 22:42:03 +00003574 CXErrorCode result = CXError_Failure;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003575 auto ParseTranslationUnitImpl = [=, &result] {
3576 result = clang_parseTranslationUnit_Impl(
3577 CIdx, source_filename, command_line_args, num_command_line_args,
3578 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3579 };
Erik Verbruggen284848d2017-08-29 09:08:02 +00003580
Guy Benyei11169dd2012-12-18 14:30:41 +00003581 llvm::CrashRecoveryContext CRC;
3582
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003583 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003584 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3585 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3586 fprintf(stderr, " 'command_line_args' : [");
3587 for (int i = 0; i != num_command_line_args; ++i) {
3588 if (i)
3589 fprintf(stderr, ", ");
3590 fprintf(stderr, "'%s'", command_line_args[i]);
3591 }
3592 fprintf(stderr, "],\n");
3593 fprintf(stderr, " 'unsaved_files' : [");
3594 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3595 if (i)
3596 fprintf(stderr, ", ");
3597 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3598 unsaved_files[i].Length);
3599 }
3600 fprintf(stderr, "],\n");
3601 fprintf(stderr, " 'options' : %d,\n", options);
3602 fprintf(stderr, "}\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003603
3604 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00003605 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003606 if (CXTranslationUnit *TU = out_TU)
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003607 PrintLibclangResourceUsage(*TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003608 }
Alp Toker5c532982014-07-07 22:42:03 +00003609
3610 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003611}
3612
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003613CXString clang_Type_getObjCEncoding(CXType CT) {
3614 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3615 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3616 std::string encoding;
3617 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3618 encoding);
3619
3620 return cxstring::createDup(encoding);
3621}
3622
3623static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3624 if (C.kind == CXCursor_MacroDefinition) {
3625 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3626 return MDR->getName();
3627 } else if (C.kind == CXCursor_MacroExpansion) {
3628 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3629 return ME.getName();
3630 }
3631 return nullptr;
3632}
3633
3634unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3635 const IdentifierInfo *II = getMacroIdentifier(C);
3636 if (!II) {
3637 return false;
3638 }
3639 ASTUnit *ASTU = getCursorASTUnit(C);
3640 Preprocessor &PP = ASTU->getPreprocessor();
3641 if (const MacroInfo *MI = PP.getMacroInfo(II))
3642 return MI->isFunctionLike();
3643 return false;
3644}
3645
3646unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3647 const IdentifierInfo *II = getMacroIdentifier(C);
3648 if (!II) {
3649 return false;
3650 }
3651 ASTUnit *ASTU = getCursorASTUnit(C);
3652 Preprocessor &PP = ASTU->getPreprocessor();
3653 if (const MacroInfo *MI = PP.getMacroInfo(II))
3654 return MI->isBuiltinMacro();
3655 return false;
3656}
3657
3658unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3659 const Decl *D = getCursorDecl(C);
3660 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3661 if (!FD) {
3662 return false;
3663 }
3664 return FD->isInlined();
3665}
3666
3667static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3668 if (callExpr->getNumArgs() != 1) {
3669 return nullptr;
3670 }
3671
3672 StringLiteral *S = nullptr;
3673 auto *arg = callExpr->getArg(0);
3674 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3675 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3676 auto *subExpr = I->getSubExprAsWritten();
3677
3678 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3679 return nullptr;
3680 }
3681
3682 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3683 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3684 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3685 } else {
3686 return nullptr;
3687 }
3688 return S;
3689}
3690
David Blaikie59272572016-04-13 18:23:33 +00003691struct ExprEvalResult {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003692 CXEvalResultKind EvalType;
3693 union {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003694 unsigned long long unsignedVal;
3695 long long intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003696 double floatVal;
3697 char *stringVal;
3698 } EvalData;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003699 bool IsUnsignedInt;
David Blaikie59272572016-04-13 18:23:33 +00003700 ~ExprEvalResult() {
3701 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3702 EvalType != CXEval_Int) {
Alex Lorenza19cb2e2019-01-08 23:28:37 +00003703 delete[] EvalData.stringVal;
David Blaikie59272572016-04-13 18:23:33 +00003704 }
3705 }
3706};
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003707
3708void clang_EvalResult_dispose(CXEvalResult E) {
David Blaikie59272572016-04-13 18:23:33 +00003709 delete static_cast<ExprEvalResult *>(E);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003710}
3711
3712CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3713 if (!E) {
3714 return CXEval_UnExposed;
3715 }
3716 return ((ExprEvalResult *)E)->EvalType;
3717}
3718
3719int clang_EvalResult_getAsInt(CXEvalResult E) {
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003720 return clang_EvalResult_getAsLongLong(E);
3721}
3722
3723long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003724 if (!E) {
3725 return 0;
3726 }
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003727 ExprEvalResult *Result = (ExprEvalResult*)E;
3728 if (Result->IsUnsignedInt)
3729 return Result->EvalData.unsignedVal;
3730 return Result->EvalData.intVal;
3731}
3732
3733unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3734 return ((ExprEvalResult *)E)->IsUnsignedInt;
3735}
3736
3737unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3738 if (!E) {
3739 return 0;
3740 }
3741
3742 ExprEvalResult *Result = (ExprEvalResult*)E;
3743 if (Result->IsUnsignedInt)
3744 return Result->EvalData.unsignedVal;
3745 return Result->EvalData.intVal;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003746}
3747
3748double clang_EvalResult_getAsDouble(CXEvalResult E) {
3749 if (!E) {
3750 return 0;
3751 }
3752 return ((ExprEvalResult *)E)->EvalData.floatVal;
3753}
3754
3755const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3756 if (!E) {
3757 return nullptr;
3758 }
3759 return ((ExprEvalResult *)E)->EvalData.stringVal;
3760}
3761
3762static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3763 Expr::EvalResult ER;
3764 ASTContext &ctx = getCursorContext(C);
David Blaikiebbc00882016-04-13 18:36:19 +00003765 if (!expr)
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003766 return nullptr;
David Blaikiebbc00882016-04-13 18:36:19 +00003767
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003768 expr = expr->IgnoreParens();
David Blaikiebbc00882016-04-13 18:36:19 +00003769 if (!expr->EvaluateAsRValue(ER, ctx))
3770 return nullptr;
3771
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003772 QualType rettype;
3773 CallExpr *callExpr;
David Blaikie59272572016-04-13 18:23:33 +00003774 auto result = llvm::make_unique<ExprEvalResult>();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003775 result->EvalType = CXEval_UnExposed;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003776 result->IsUnsignedInt = false;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003777
David Blaikiebbc00882016-04-13 18:36:19 +00003778 if (ER.Val.isInt()) {
3779 result->EvalType = CXEval_Int;
Argyrios Kyrtzidis5dda1122016-12-01 23:41:27 +00003780
3781 auto& val = ER.Val.getInt();
3782 if (val.isUnsigned()) {
3783 result->IsUnsignedInt = true;
3784 result->EvalData.unsignedVal = val.getZExtValue();
3785 } else {
3786 result->EvalData.intVal = val.getExtValue();
3787 }
3788
David Blaikiebbc00882016-04-13 18:36:19 +00003789 return result.release();
3790 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003791
David Blaikiebbc00882016-04-13 18:36:19 +00003792 if (ER.Val.isFloat()) {
3793 llvm::SmallVector<char, 100> Buffer;
3794 ER.Val.getFloat().toString(Buffer);
3795 std::string floatStr(Buffer.data(), Buffer.size());
3796 result->EvalType = CXEval_Float;
3797 bool ignored;
3798 llvm::APFloat apFloat = ER.Val.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003799 apFloat.convert(llvm::APFloat::IEEEdouble(),
David Blaikiebbc00882016-04-13 18:36:19 +00003800 llvm::APFloat::rmNearestTiesToEven, &ignored);
3801 result->EvalData.floatVal = apFloat.convertToDouble();
3802 return result.release();
3803 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003804
David Blaikiebbc00882016-04-13 18:36:19 +00003805 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3806 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3807 auto *subExpr = I->getSubExprAsWritten();
3808 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3809 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003810 const StringLiteral *StrE = nullptr;
3811 const ObjCStringLiteral *ObjCExpr;
David Blaikiebbc00882016-04-13 18:36:19 +00003812 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003813
3814 if (ObjCExpr) {
3815 StrE = ObjCExpr->getString();
3816 result->EvalType = CXEval_ObjCStrLiteral;
3817 } else {
David Blaikiebbc00882016-04-13 18:36:19 +00003818 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003819 result->EvalType = CXEval_StrLiteral;
3820 }
3821
3822 std::string strRef(StrE->getString().str());
David Blaikie59272572016-04-13 18:23:33 +00003823 result->EvalData.stringVal = new char[strRef.size() + 1];
David Blaikiebbc00882016-04-13 18:36:19 +00003824 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3825 strRef.size());
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003826 result->EvalData.stringVal[strRef.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003827 return result.release();
David Blaikiebbc00882016-04-13 18:36:19 +00003828 }
3829 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3830 expr->getStmtClass() == Stmt::StringLiteralClass) {
3831 const StringLiteral *StrE = nullptr;
3832 const ObjCStringLiteral *ObjCExpr;
3833 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003834
David Blaikiebbc00882016-04-13 18:36:19 +00003835 if (ObjCExpr) {
3836 StrE = ObjCExpr->getString();
3837 result->EvalType = CXEval_ObjCStrLiteral;
3838 } else {
3839 StrE = cast<StringLiteral>(expr);
3840 result->EvalType = CXEval_StrLiteral;
3841 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003842
David Blaikiebbc00882016-04-13 18:36:19 +00003843 std::string strRef(StrE->getString().str());
3844 result->EvalData.stringVal = new char[strRef.size() + 1];
3845 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3846 result->EvalData.stringVal[strRef.size()] = '\0';
3847 return result.release();
3848 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003849
David Blaikiebbc00882016-04-13 18:36:19 +00003850 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3851 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003852
David Blaikiebbc00882016-04-13 18:36:19 +00003853 rettype = CC->getType();
3854 if (rettype.getAsString() == "CFStringRef" &&
3855 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003856
David Blaikiebbc00882016-04-13 18:36:19 +00003857 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3858 StringLiteral *S = getCFSTR_value(callExpr);
3859 if (S) {
3860 std::string strLiteral(S->getString().str());
3861 result->EvalType = CXEval_CFStr;
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003862
David Blaikiebbc00882016-04-13 18:36:19 +00003863 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3864 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3865 strLiteral.size());
3866 result->EvalData.stringVal[strLiteral.size()] = '\0';
David Blaikie59272572016-04-13 18:23:33 +00003867 return result.release();
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003868 }
3869 }
3870
David Blaikiebbc00882016-04-13 18:36:19 +00003871 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3872 callExpr = static_cast<CallExpr *>(expr);
3873 rettype = callExpr->getCallReturnType(ctx);
3874
3875 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3876 return nullptr;
3877
3878 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3879 if (callExpr->getNumArgs() == 1 &&
3880 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3881 return nullptr;
3882 } else if (rettype.getAsString() == "CFStringRef") {
3883
3884 StringLiteral *S = getCFSTR_value(callExpr);
3885 if (S) {
3886 std::string strLiteral(S->getString().str());
3887 result->EvalType = CXEval_CFStr;
3888 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3889 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3890 strLiteral.size());
3891 result->EvalData.stringVal[strLiteral.size()] = '\0';
3892 return result.release();
3893 }
3894 }
3895 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3896 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3897 ValueDecl *V = D->getDecl();
3898 if (V->getKind() == Decl::Function) {
3899 std::string strName = V->getNameAsString();
3900 result->EvalType = CXEval_Other;
3901 result->EvalData.stringVal = new char[strName.size() + 1];
3902 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3903 result->EvalData.stringVal[strName.size()] = '\0';
3904 return result.release();
3905 }
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003906 }
3907
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003908 return nullptr;
3909}
3910
Alex Lorenz65317e12019-01-08 22:32:51 +00003911static const Expr *evaluateDeclExpr(const Decl *D) {
3912 if (!D)
Evgeniy Stepanov9b871492018-07-10 19:48:53 +00003913 return nullptr;
Alex Lorenz65317e12019-01-08 22:32:51 +00003914 if (auto *Var = dyn_cast<VarDecl>(D))
3915 return Var->getInit();
3916 else if (auto *Field = dyn_cast<FieldDecl>(D))
3917 return Field->getInClassInitializer();
3918 return nullptr;
3919}
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003920
Alex Lorenz65317e12019-01-08 22:32:51 +00003921static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
3922 assert(CS && "invalid compound statement");
3923 for (auto *bodyIterator : CS->body()) {
3924 if (const auto *E = dyn_cast<Expr>(bodyIterator))
3925 return E;
Evgeniy Stepanov6df47ce2018-07-10 19:49:07 +00003926 }
Alex Lorenzc4cf96e2018-07-09 19:56:45 +00003927 return nullptr;
3928}
3929
Alex Lorenz65317e12019-01-08 22:32:51 +00003930CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3931 if (const Expr *E =
3932 clang_getCursorKind(C) == CXCursor_CompoundStmt
3933 ? evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)))
3934 : evaluateDeclExpr(getCursorDecl(C)))
3935 return const_cast<CXEvalResult>(
3936 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
3937 return nullptr;
3938}
3939
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00003940unsigned clang_Cursor_hasAttrs(CXCursor C) {
3941 const Decl *D = getCursorDecl(C);
3942 if (!D) {
3943 return 0;
3944 }
3945
3946 if (D->hasAttrs()) {
3947 return 1;
3948 }
3949
3950 return 0;
3951}
Guy Benyei11169dd2012-12-18 14:30:41 +00003952unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3953 return CXSaveTranslationUnit_None;
3954}
3955
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003956static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3957 const char *FileName,
3958 unsigned options) {
3959 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00003960 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3961 setThreadBackgroundPriority();
3962
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003963 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3964 return hadError ? CXSaveError_Unknown : CXSaveError_None;
Guy Benyei11169dd2012-12-18 14:30:41 +00003965}
3966
3967int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3968 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00003969 LOG_FUNC_SECTION {
3970 *Log << TU << ' ' << FileName;
3971 }
3972
Dmitri Gribenko852d6222014-02-11 15:02:48 +00003973 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003974 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003975 return CXSaveError_InvalidTU;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00003976 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003977
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00003978 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00003979 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3980 if (!CXXUnit->hasSema())
3981 return CXSaveError_InvalidTU;
3982
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003983 CXSaveError result;
3984 auto SaveTranslationUnitImpl = [=, &result]() {
3985 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3986 };
Guy Benyei11169dd2012-12-18 14:30:41 +00003987
Erik Verbruggen3cc39112017-11-14 09:34:39 +00003988 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003989 SaveTranslationUnitImpl();
Guy Benyei11169dd2012-12-18 14:30:41 +00003990
3991 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3992 PrintLibclangResourceUsage(TU);
3993
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00003994 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003995 }
3996
3997 // We have an AST that has invalid nodes due to compiler errors.
3998 // Use a crash recovery thread for protection.
3999
4000 llvm::CrashRecoveryContext CRC;
4001
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004002 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004003 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
4004 fprintf(stderr, " 'filename' : '%s'\n", FileName);
4005 fprintf(stderr, " 'options' : %d,\n", options);
4006 fprintf(stderr, "}\n");
4007
4008 return CXSaveError_Unknown;
4009
4010 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4011 PrintLibclangResourceUsage(TU);
4012 }
4013
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004014 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004015}
4016
4017void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4018 if (CTUnit) {
4019 // If the translation unit has been marked as unsafe to free, just discard
4020 // it.
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004021 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4022 if (Unit && Unit->isUnsafeToFree())
Guy Benyei11169dd2012-12-18 14:30:41 +00004023 return;
4024
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004025 delete cxtu::getASTUnit(CTUnit);
Dmitri Gribenkob95b3f12013-01-26 22:44:19 +00004026 delete CTUnit->StringPool;
Guy Benyei11169dd2012-12-18 14:30:41 +00004027 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4028 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Dmitri Gribenko9e605112013-11-13 22:16:51 +00004029 delete CTUnit->CommentToXML;
Guy Benyei11169dd2012-12-18 14:30:41 +00004030 delete CTUnit;
4031 }
4032}
4033
Erik Verbruggen346066b2017-05-30 14:25:54 +00004034unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4035 if (CTUnit) {
4036 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4037
4038 if (Unit && Unit->isUnsafeToFree())
4039 return false;
4040
4041 Unit->ResetForParse();
4042 return true;
4043 }
4044
4045 return false;
4046}
4047
Guy Benyei11169dd2012-12-18 14:30:41 +00004048unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4049 return CXReparse_None;
4050}
4051
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004052static CXErrorCode
4053clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4054 ArrayRef<CXUnsavedFile> unsaved_files,
4055 unsigned options) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004056 // Check arguments.
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004057 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004058 LOG_BAD_TU(TU);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004059 return CXError_InvalidArguments;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004060 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004061
4062 // Reset the associated diagnostics.
4063 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
Craig Topper69186e72014-06-08 08:38:04 +00004064 TU->Diagnostics = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004065
Dmitri Gribenko183436e2013-01-26 21:49:50 +00004066 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00004067 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4068 setThreadBackgroundPriority();
4069
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004070 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004071 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ahmed Charlesb8984322014-03-07 20:03:18 +00004072
4073 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4074 new std::vector<ASTUnit::RemappedFile>());
4075
Guy Benyei11169dd2012-12-18 14:30:41 +00004076 // Recover resources if we crash before exiting this function.
4077 llvm::CrashRecoveryContextCleanupRegistrar<
4078 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
Alp Toker9d85b182014-07-07 01:23:14 +00004079
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004080 for (auto &UF : unsaved_files) {
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004081 std::unique_ptr<llvm::MemoryBuffer> MB =
Alp Toker9d85b182014-07-07 01:23:14 +00004082 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
Rafael Espindolad87f8d72014-08-27 20:03:29 +00004083 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004084 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004085
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004086 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4087 *RemappedFiles.get()))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004088 return CXError_Success;
4089 if (isASTReadError(CXXUnit))
4090 return CXError_ASTReadError;
4091 return CXError_Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004092}
4093
4094int clang_reparseTranslationUnit(CXTranslationUnit TU,
4095 unsigned num_unsaved_files,
4096 struct CXUnsavedFile *unsaved_files,
4097 unsigned options) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00004098 LOG_FUNC_SECTION {
4099 *Log << TU;
4100 }
4101
Alp Toker9d85b182014-07-07 01:23:14 +00004102 if (num_unsaved_files && !unsaved_files)
4103 return CXError_InvalidArguments;
4104
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004105 CXErrorCode result;
4106 auto ReparseTranslationUnitImpl = [=, &result]() {
4107 result = clang_reparseTranslationUnit_Impl(
4108 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4109 };
Guy Benyei11169dd2012-12-18 14:30:41 +00004110
Guy Benyei11169dd2012-12-18 14:30:41 +00004111 llvm::CrashRecoveryContext CRC;
4112
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00004113 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004114 fprintf(stderr, "libclang: crash detected during reparsing\n");
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004115 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004116 return CXError_Crashed;
Guy Benyei11169dd2012-12-18 14:30:41 +00004117 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4118 PrintLibclangResourceUsage(TU);
4119
Alp Toker5c532982014-07-07 22:42:03 +00004120 return result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004121}
4122
4123
4124CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004125 if (isNotUsableTU(CTUnit)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004126 LOG_BAD_TU(CTUnit);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004127 return cxstring::createEmpty();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004128 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004129
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004130 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004131 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004132}
4133
4134CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004135 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004136 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004137 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004138 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00004139
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004140 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004141 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4142}
4143
Emilio Cobos Alvarez485ad422017-04-28 15:56:39 +00004144CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4145 if (isNotUsableTU(CTUnit)) {
4146 LOG_BAD_TU(CTUnit);
4147 return nullptr;
4148 }
4149
4150 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4151 impl->TranslationUnit = CTUnit;
4152 return impl;
4153}
4154
4155CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4156 if (!TargetInfo)
4157 return cxstring::createEmpty();
4158
4159 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4160 assert(!isNotUsableTU(CTUnit) &&
4161 "Unexpected unusable translation unit in TargetInfo");
4162
4163 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4164 std::string Triple =
4165 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4166 return cxstring::createDup(Triple);
4167}
4168
4169int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4170 if (!TargetInfo)
4171 return -1;
4172
4173 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4174 assert(!isNotUsableTU(CTUnit) &&
4175 "Unexpected unusable translation unit in TargetInfo");
4176
4177 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4178 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4179}
4180
4181void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4182 if (!TargetInfo)
4183 return;
4184
4185 delete TargetInfo;
4186}
4187
Guy Benyei11169dd2012-12-18 14:30:41 +00004188//===----------------------------------------------------------------------===//
4189// CXFile Operations.
4190//===----------------------------------------------------------------------===//
4191
Guy Benyei11169dd2012-12-18 14:30:41 +00004192CXString clang_getFileName(CXFile SFile) {
4193 if (!SFile)
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00004194 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00004195
4196 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004197 return cxstring::createRef(FEnt->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004198}
4199
4200time_t clang_getFileTime(CXFile SFile) {
4201 if (!SFile)
4202 return 0;
4203
4204 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4205 return FEnt->getModificationTime();
4206}
4207
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004208CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004209 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004210 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00004211 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004212 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004213
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004214 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004215
4216 FileManager &FMgr = CXXUnit->getFileManager();
4217 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4218}
4219
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004220const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4221 size_t *size) {
4222 if (isNotUsableTU(TU)) {
4223 LOG_BAD_TU(TU);
4224 return nullptr;
4225 }
4226
4227 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4228 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4229 bool Invalid = true;
Nico Weber04347d82019-04-04 21:06:41 +00004230 const llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
Erik Verbruggen3afa3ce2017-12-06 09:02:52 +00004231 if (Invalid) {
4232 if (size)
4233 *size = 0;
4234 return nullptr;
4235 }
4236 if (size)
4237 *size = buf->getBufferSize();
4238 return buf->getBufferStart();
4239}
4240
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004241unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4242 CXFile file) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00004243 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00004244 LOG_BAD_TU(TU);
4245 return 0;
4246 }
4247
4248 if (!file)
Guy Benyei11169dd2012-12-18 14:30:41 +00004249 return 0;
4250
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00004251 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004252 FileEntry *FEnt = static_cast<FileEntry *>(file);
4253 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4254 .isFileMultipleIncludeGuarded(FEnt);
4255}
4256
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004257int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4258 if (!file || !outID)
4259 return 1;
4260
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004261 FileEntry *FEnt = static_cast<FileEntry *>(file);
Rafael Espindolaf8f91b82013-08-01 21:42:11 +00004262 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4263 outID->data[0] = ID.getDevice();
4264 outID->data[1] = ID.getFile();
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004265 outID->data[2] = FEnt->getModificationTime();
4266 return 0;
Argyrios Kyrtzidisac08b262013-01-26 04:52:52 +00004267}
4268
Argyrios Kyrtzidisac3997e2014-08-16 00:26:19 +00004269int clang_File_isEqual(CXFile file1, CXFile file2) {
4270 if (file1 == file2)
4271 return true;
4272
4273 if (!file1 || !file2)
4274 return false;
4275
4276 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4277 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4278 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4279}
4280
Fangrui Songe46ac5f2018-04-07 20:50:35 +00004281CXString clang_File_tryGetRealPathName(CXFile SFile) {
4282 if (!SFile)
4283 return cxstring::createNull();
4284
4285 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4286 return cxstring::createRef(FEnt->tryGetRealPathName());
4287}
4288
Guy Benyei11169dd2012-12-18 14:30:41 +00004289//===----------------------------------------------------------------------===//
4290// CXCursor Operations.
4291//===----------------------------------------------------------------------===//
4292
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004293static const Decl *getDeclFromExpr(const Stmt *E) {
4294 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004295 return getDeclFromExpr(CE->getSubExpr());
4296
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004297 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004298 return RefExpr->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004299 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004300 return ME->getMemberDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004301 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004302 return RE->getDecl();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004303 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004304 if (PRE->isExplicitProperty())
4305 return PRE->getExplicitProperty();
4306 // It could be messaging both getter and setter as in:
4307 // ++myobj.myprop;
4308 // in which case prefer to associate the setter since it is less obvious
4309 // from inspecting the source that the setter is going to get called.
4310 if (PRE->isMessagingSetter())
4311 return PRE->getImplicitPropertySetter();
4312 return PRE->getImplicitPropertyGetter();
4313 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004314 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004315 return getDeclFromExpr(POE->getSyntacticForm());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004316 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004317 if (Expr *Src = OVE->getSourceExpr())
4318 return getDeclFromExpr(Src);
4319
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004320 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004321 return getDeclFromExpr(CE->getCallee());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004322 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004323 if (!CE->isElidable())
4324 return CE->getConstructor();
Richard Smith5179eb72016-06-28 19:03:57 +00004325 if (const CXXInheritedCtorInitExpr *CE =
4326 dyn_cast<CXXInheritedCtorInitExpr>(E))
4327 return CE->getConstructor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004328 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004329 return OME->getMethodDecl();
4330
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004331 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004332 return PE->getProtocol();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004333 if (const SubstNonTypeTemplateParmPackExpr *NTTP
Guy Benyei11169dd2012-12-18 14:30:41 +00004334 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4335 return NTTP->getParameterPack();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004336 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004337 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4338 isa<ParmVarDecl>(SizeOfPack->getPack()))
4339 return SizeOfPack->getPack();
Craig Topper69186e72014-06-08 08:38:04 +00004340
4341 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004342}
4343
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004344static SourceLocation getLocationFromExpr(const Expr *E) {
4345 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004346 return getLocationFromExpr(CE->getSubExpr());
4347
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004348 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004349 return /*FIXME:*/Msg->getLeftLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004350 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004351 return DRE->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004352 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004353 return Member->getMemberLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004354 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004355 return Ivar->getLocation();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004356 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004357 return SizeOfPack->getPackLoc();
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004358 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00004359 return PropRef->getLocation();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004360
4361 return E->getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00004362}
4363
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00004364extern "C" {
4365
Guy Benyei11169dd2012-12-18 14:30:41 +00004366unsigned clang_visitChildren(CXCursor parent,
4367 CXCursorVisitor visitor,
4368 CXClientData client_data) {
4369 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4370 /*VisitPreprocessorLast=*/false);
4371 return CursorVis.VisitChildren(parent);
4372}
4373
4374#ifndef __has_feature
4375#define __has_feature(x) 0
4376#endif
4377#if __has_feature(blocks)
4378typedef enum CXChildVisitResult
4379 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4380
4381static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4382 CXClientData client_data) {
4383 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4384 return block(cursor, parent);
4385}
4386#else
4387// If we are compiled with a compiler that doesn't have native blocks support,
4388// define and call the block manually, so the
4389typedef struct _CXChildVisitResult
4390{
4391 void *isa;
4392 int flags;
4393 int reserved;
4394 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4395 CXCursor);
4396} *CXCursorVisitorBlock;
4397
4398static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4399 CXClientData client_data) {
4400 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4401 return block->invoke(block, cursor, parent);
4402}
4403#endif
4404
4405
4406unsigned clang_visitChildrenWithBlock(CXCursor parent,
4407 CXCursorVisitorBlock block) {
4408 return clang_visitChildren(parent, visitWithBlock, block);
4409}
4410
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004411static CXString getDeclSpelling(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004412 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004413 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004414
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004415 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004416 if (!ND) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004417 if (const ObjCPropertyImplDecl *PropImpl =
4418 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004419 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004420 return cxstring::createDup(Property->getIdentifier()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004421
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004422 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004423 if (Module *Mod = ImportD->getImportedModule())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004424 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004425
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004426 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004427 }
4428
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004429 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004430 return cxstring::createDup(OMD->getSelector().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004431
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004432 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +00004433 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4434 // and returns different names. NamedDecl returns the class name and
4435 // ObjCCategoryImplDecl returns the category name.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004436 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004437
4438 if (isa<UsingDirectiveDecl>(D))
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004439 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004440
4441 SmallString<1024> S;
4442 llvm::raw_svector_ostream os(S);
4443 ND->printName(os);
4444
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004445 return cxstring::createDup(os.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004446}
4447
4448CXString clang_getCursorSpelling(CXCursor C) {
4449 if (clang_isTranslationUnit(C.kind))
Dmitri Gribenko2c173b42013-01-11 19:28:44 +00004450 return clang_getTranslationUnitSpelling(getCursorTU(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004451
4452 if (clang_isReference(C.kind)) {
4453 switch (C.kind) {
4454 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004455 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004456 return cxstring::createRef(Super->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004457 }
4458 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004459 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004460 return cxstring::createRef(Class->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004461 }
4462 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004463 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004464 assert(OID && "getCursorSpelling(): Missing protocol decl");
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004465 return cxstring::createRef(OID->getIdentifier()->getNameStart());
Guy Benyei11169dd2012-12-18 14:30:41 +00004466 }
4467 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004468 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004469 return cxstring::createDup(B->getType().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004470 }
4471 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004472 const TypeDecl *Type = getCursorTypeRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004473 assert(Type && "Missing type decl");
4474
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004475 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
Guy Benyei11169dd2012-12-18 14:30:41 +00004476 getAsString());
4477 }
4478 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004479 const TemplateDecl *Template = getCursorTemplateRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004480 assert(Template && "Missing template decl");
4481
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004482 return cxstring::createDup(Template->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004483 }
4484
4485 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004486 const NamedDecl *NS = getCursorNamespaceRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004487 assert(NS && "Missing namespace decl");
4488
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004489 return cxstring::createDup(NS->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004490 }
4491
4492 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004493 const FieldDecl *Field = getCursorMemberRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004494 assert(Field && "Missing member decl");
4495
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004496 return cxstring::createDup(Field->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004497 }
4498
4499 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004500 const LabelStmt *Label = getCursorLabelRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004501 assert(Label && "Missing label");
4502
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004503 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004504 }
4505
4506 case CXCursor_OverloadedDeclRef: {
4507 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004508 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4509 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004510 return cxstring::createDup(ND->getNameAsString());
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004511 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004512 }
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004513 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004514 return cxstring::createDup(E->getName().getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004515 OverloadedTemplateStorage *Ovl
4516 = Storage.get<OverloadedTemplateStorage*>();
4517 if (Ovl->size() == 0)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004518 return cxstring::createEmpty();
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004519 return cxstring::createDup((*Ovl->begin())->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004520 }
4521
4522 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00004523 const VarDecl *Var = getCursorVariableRef(C).first;
Guy Benyei11169dd2012-12-18 14:30:41 +00004524 assert(Var && "Missing variable decl");
4525
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004526 return cxstring::createDup(Var->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00004527 }
4528
4529 default:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004530 return cxstring::createRef("<not implemented>");
Guy Benyei11169dd2012-12-18 14:30:41 +00004531 }
4532 }
4533
4534 if (clang_isExpression(C.kind)) {
Argyrios Kyrtzidis3227d862014-03-03 19:40:52 +00004535 const Expr *E = getCursorExpr(C);
4536
4537 if (C.kind == CXCursor_ObjCStringLiteral ||
4538 C.kind == CXCursor_StringLiteral) {
4539 const StringLiteral *SLit;
4540 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4541 SLit = OSL->getString();
4542 } else {
4543 SLit = cast<StringLiteral>(E);
4544 }
4545 SmallString<256> Buf;
4546 llvm::raw_svector_ostream OS(Buf);
4547 SLit->outputString(OS);
4548 return cxstring::createDup(OS.str());
4549 }
4550
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004551 const Decl *D = getDeclFromExpr(getCursorExpr(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00004552 if (D)
4553 return getDeclSpelling(D);
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004554 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004555 }
4556
4557 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004558 const Stmt *S = getCursorStmt(C);
4559 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004560 return cxstring::createRef(Label->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004561
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004562 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004563 }
4564
4565 if (C.kind == CXCursor_MacroExpansion)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004566 return cxstring::createRef(getCursorMacroExpansion(C).getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004567 ->getNameStart());
4568
4569 if (C.kind == CXCursor_MacroDefinition)
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00004570 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
Guy Benyei11169dd2012-12-18 14:30:41 +00004571 ->getNameStart());
4572
4573 if (C.kind == CXCursor_InclusionDirective)
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004574 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
Guy Benyei11169dd2012-12-18 14:30:41 +00004575
4576 if (clang_isDeclaration(C.kind))
4577 return getDeclSpelling(getCursorDecl(C));
4578
4579 if (C.kind == CXCursor_AnnotateAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004580 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004581 return cxstring::createDup(AA->getAnnotation());
Guy Benyei11169dd2012-12-18 14:30:41 +00004582 }
4583
4584 if (C.kind == CXCursor_AsmLabelAttr) {
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00004585 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004586 return cxstring::createDup(AA->getLabel());
Guy Benyei11169dd2012-12-18 14:30:41 +00004587 }
4588
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00004589 if (C.kind == CXCursor_PackedAttr) {
4590 return cxstring::createRef("packed");
4591 }
4592
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00004593 if (C.kind == CXCursor_VisibilityAttr) {
4594 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4595 switch (AA->getVisibility()) {
4596 case VisibilityAttr::VisibilityType::Default:
4597 return cxstring::createRef("default");
4598 case VisibilityAttr::VisibilityType::Hidden:
4599 return cxstring::createRef("hidden");
4600 case VisibilityAttr::VisibilityType::Protected:
4601 return cxstring::createRef("protected");
4602 }
4603 llvm_unreachable("unknown visibility type");
4604 }
4605
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004606 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004607}
4608
4609CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4610 unsigned pieceIndex,
4611 unsigned options) {
4612 if (clang_Cursor_isNull(C))
4613 return clang_getNullRange();
4614
4615 ASTContext &Ctx = getCursorContext(C);
4616
4617 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004618 const Stmt *S = getCursorStmt(C);
4619 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004620 if (pieceIndex > 0)
4621 return clang_getNullRange();
4622 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4623 }
4624
4625 return clang_getNullRange();
4626 }
4627
4628 if (C.kind == CXCursor_ObjCMessageExpr) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00004629 if (const ObjCMessageExpr *
Guy Benyei11169dd2012-12-18 14:30:41 +00004630 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4631 if (pieceIndex >= ME->getNumSelectorLocs())
4632 return clang_getNullRange();
4633 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4634 }
4635 }
4636
4637 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4638 C.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004639 if (const ObjCMethodDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004640 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4641 if (pieceIndex >= MD->getNumSelectorLocs())
4642 return clang_getNullRange();
4643 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4644 }
4645 }
4646
4647 if (C.kind == CXCursor_ObjCCategoryDecl ||
4648 C.kind == CXCursor_ObjCCategoryImplDecl) {
4649 if (pieceIndex > 0)
4650 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004651 if (const ObjCCategoryDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004652 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4653 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004654 if (const ObjCCategoryImplDecl *
Guy Benyei11169dd2012-12-18 14:30:41 +00004655 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4656 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4657 }
4658
4659 if (C.kind == CXCursor_ModuleImportDecl) {
4660 if (pieceIndex > 0)
4661 return clang_getNullRange();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004662 if (const ImportDecl *ImportD =
4663 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004664 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4665 if (!Locs.empty())
4666 return cxloc::translateSourceRange(Ctx,
4667 SourceRange(Locs.front(), Locs.back()));
4668 }
4669 return clang_getNullRange();
4670 }
4671
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004672 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
Kevin Funk4be5d672016-12-20 09:56:56 +00004673 C.kind == CXCursor_ConversionFunction ||
4674 C.kind == CXCursor_FunctionDecl) {
Argyrios Kyrtzidisa2a1e532014-08-26 20:23:26 +00004675 if (pieceIndex > 0)
4676 return clang_getNullRange();
4677 if (const FunctionDecl *FD =
4678 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4679 DeclarationNameInfo FunctionName = FD->getNameInfo();
4680 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4681 }
4682 return clang_getNullRange();
4683 }
4684
Guy Benyei11169dd2012-12-18 14:30:41 +00004685 // FIXME: A CXCursor_InclusionDirective should give the location of the
4686 // filename, but we don't keep track of this.
4687
4688 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4689 // but we don't keep track of this.
4690
4691 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4692 // but we don't keep track of this.
4693
4694 // Default handling, give the location of the cursor.
4695
4696 if (pieceIndex > 0)
4697 return clang_getNullRange();
4698
4699 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4700 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4701 return cxloc::translateSourceRange(Ctx, Loc);
4702}
4703
Eli Bendersky44a206f2014-07-31 18:04:56 +00004704CXString clang_Cursor_getMangling(CXCursor C) {
4705 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4706 return cxstring::createEmpty();
4707
Eli Bendersky44a206f2014-07-31 18:04:56 +00004708 // Mangling only works for functions and variables.
Eli Bendersky79759592014-08-01 15:01:10 +00004709 const Decl *D = getCursorDecl(C);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004710 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4711 return cxstring::createEmpty();
4712
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004713 ASTContext &Ctx = D->getASTContext();
4714 index::CodegenNameGenerator CGNameGen(Ctx);
4715 return cxstring::createDup(CGNameGen.getName(D));
Eli Bendersky44a206f2014-07-31 18:04:56 +00004716}
4717
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004718CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4719 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4720 return nullptr;
4721
4722 const Decl *D = getCursorDecl(C);
4723 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4724 return nullptr;
4725
Argyrios Kyrtzidisca741ce2016-02-14 22:30:14 +00004726 ASTContext &Ctx = D->getASTContext();
4727 index::CodegenNameGenerator CGNameGen(Ctx);
4728 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004729 return cxstring::createSet(Manglings);
4730}
4731
Dave Lee1a532c92017-09-22 16:58:57 +00004732CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4733 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4734 return nullptr;
4735
4736 const Decl *D = getCursorDecl(C);
4737 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4738 return nullptr;
4739
4740 ASTContext &Ctx = D->getASTContext();
4741 index::CodegenNameGenerator CGNameGen(Ctx);
4742 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4743 return cxstring::createSet(Manglings);
4744}
4745
Jonathan Coe45ef5032018-01-16 10:19:56 +00004746CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4747 if (clang_Cursor_isNull(C))
4748 return 0;
4749 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4750}
4751
4752void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4753 if (Policy)
4754 delete static_cast<PrintingPolicy *>(Policy);
4755}
4756
4757unsigned
4758clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4759 enum CXPrintingPolicyProperty Property) {
4760 if (!Policy)
4761 return 0;
4762
4763 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4764 switch (Property) {
4765 case CXPrintingPolicy_Indentation:
4766 return P->Indentation;
4767 case CXPrintingPolicy_SuppressSpecifiers:
4768 return P->SuppressSpecifiers;
4769 case CXPrintingPolicy_SuppressTagKeyword:
4770 return P->SuppressTagKeyword;
4771 case CXPrintingPolicy_IncludeTagDefinition:
4772 return P->IncludeTagDefinition;
4773 case CXPrintingPolicy_SuppressScope:
4774 return P->SuppressScope;
4775 case CXPrintingPolicy_SuppressUnwrittenScope:
4776 return P->SuppressUnwrittenScope;
4777 case CXPrintingPolicy_SuppressInitializers:
4778 return P->SuppressInitializers;
4779 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4780 return P->ConstantArraySizeAsWritten;
4781 case CXPrintingPolicy_AnonymousTagLocations:
4782 return P->AnonymousTagLocations;
4783 case CXPrintingPolicy_SuppressStrongLifetime:
4784 return P->SuppressStrongLifetime;
4785 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4786 return P->SuppressLifetimeQualifiers;
4787 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4788 return P->SuppressTemplateArgsInCXXConstructors;
4789 case CXPrintingPolicy_Bool:
4790 return P->Bool;
4791 case CXPrintingPolicy_Restrict:
4792 return P->Restrict;
4793 case CXPrintingPolicy_Alignof:
4794 return P->Alignof;
4795 case CXPrintingPolicy_UnderscoreAlignof:
4796 return P->UnderscoreAlignof;
4797 case CXPrintingPolicy_UseVoidForZeroParams:
4798 return P->UseVoidForZeroParams;
4799 case CXPrintingPolicy_TerseOutput:
4800 return P->TerseOutput;
4801 case CXPrintingPolicy_PolishForDeclaration:
4802 return P->PolishForDeclaration;
4803 case CXPrintingPolicy_Half:
4804 return P->Half;
4805 case CXPrintingPolicy_MSWChar:
4806 return P->MSWChar;
4807 case CXPrintingPolicy_IncludeNewlines:
4808 return P->IncludeNewlines;
4809 case CXPrintingPolicy_MSVCFormatting:
4810 return P->MSVCFormatting;
4811 case CXPrintingPolicy_ConstantsAsWritten:
4812 return P->ConstantsAsWritten;
4813 case CXPrintingPolicy_SuppressImplicitBase:
4814 return P->SuppressImplicitBase;
4815 case CXPrintingPolicy_FullyQualifiedName:
4816 return P->FullyQualifiedName;
4817 }
4818
4819 assert(false && "Invalid CXPrintingPolicyProperty");
4820 return 0;
4821}
4822
4823void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4824 enum CXPrintingPolicyProperty Property,
4825 unsigned Value) {
4826 if (!Policy)
4827 return;
4828
4829 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4830 switch (Property) {
4831 case CXPrintingPolicy_Indentation:
4832 P->Indentation = Value;
4833 return;
4834 case CXPrintingPolicy_SuppressSpecifiers:
4835 P->SuppressSpecifiers = Value;
4836 return;
4837 case CXPrintingPolicy_SuppressTagKeyword:
4838 P->SuppressTagKeyword = Value;
4839 return;
4840 case CXPrintingPolicy_IncludeTagDefinition:
4841 P->IncludeTagDefinition = Value;
4842 return;
4843 case CXPrintingPolicy_SuppressScope:
4844 P->SuppressScope = Value;
4845 return;
4846 case CXPrintingPolicy_SuppressUnwrittenScope:
4847 P->SuppressUnwrittenScope = Value;
4848 return;
4849 case CXPrintingPolicy_SuppressInitializers:
4850 P->SuppressInitializers = Value;
4851 return;
4852 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4853 P->ConstantArraySizeAsWritten = Value;
4854 return;
4855 case CXPrintingPolicy_AnonymousTagLocations:
4856 P->AnonymousTagLocations = Value;
4857 return;
4858 case CXPrintingPolicy_SuppressStrongLifetime:
4859 P->SuppressStrongLifetime = Value;
4860 return;
4861 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4862 P->SuppressLifetimeQualifiers = Value;
4863 return;
4864 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4865 P->SuppressTemplateArgsInCXXConstructors = Value;
4866 return;
4867 case CXPrintingPolicy_Bool:
4868 P->Bool = Value;
4869 return;
4870 case CXPrintingPolicy_Restrict:
4871 P->Restrict = Value;
4872 return;
4873 case CXPrintingPolicy_Alignof:
4874 P->Alignof = Value;
4875 return;
4876 case CXPrintingPolicy_UnderscoreAlignof:
4877 P->UnderscoreAlignof = Value;
4878 return;
4879 case CXPrintingPolicy_UseVoidForZeroParams:
4880 P->UseVoidForZeroParams = Value;
4881 return;
4882 case CXPrintingPolicy_TerseOutput:
4883 P->TerseOutput = Value;
4884 return;
4885 case CXPrintingPolicy_PolishForDeclaration:
4886 P->PolishForDeclaration = Value;
4887 return;
4888 case CXPrintingPolicy_Half:
4889 P->Half = Value;
4890 return;
4891 case CXPrintingPolicy_MSWChar:
4892 P->MSWChar = Value;
4893 return;
4894 case CXPrintingPolicy_IncludeNewlines:
4895 P->IncludeNewlines = Value;
4896 return;
4897 case CXPrintingPolicy_MSVCFormatting:
4898 P->MSVCFormatting = Value;
4899 return;
4900 case CXPrintingPolicy_ConstantsAsWritten:
4901 P->ConstantsAsWritten = Value;
4902 return;
4903 case CXPrintingPolicy_SuppressImplicitBase:
4904 P->SuppressImplicitBase = Value;
4905 return;
4906 case CXPrintingPolicy_FullyQualifiedName:
4907 P->FullyQualifiedName = Value;
4908 return;
4909 }
4910
4911 assert(false && "Invalid CXPrintingPolicyProperty");
4912}
4913
4914CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4915 if (clang_Cursor_isNull(C))
4916 return cxstring::createEmpty();
4917
4918 if (clang_isDeclaration(C.kind)) {
4919 const Decl *D = getCursorDecl(C);
4920 if (!D)
4921 return cxstring::createEmpty();
4922
4923 SmallString<128> Str;
4924 llvm::raw_svector_ostream OS(Str);
4925 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4926 D->print(OS, UserPolicy ? *UserPolicy
4927 : getCursorContext(C).getPrintingPolicy());
4928
4929 return cxstring::createDup(OS.str());
4930 }
4931
4932 return cxstring::createEmpty();
4933}
4934
Guy Benyei11169dd2012-12-18 14:30:41 +00004935CXString clang_getCursorDisplayName(CXCursor C) {
4936 if (!clang_isDeclaration(C.kind))
4937 return clang_getCursorSpelling(C);
4938
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004939 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00004940 if (!D)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00004941 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00004942
4943 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004944 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00004945 D = FunTmpl->getTemplatedDecl();
4946
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004947 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004948 SmallString<64> Str;
4949 llvm::raw_svector_ostream OS(Str);
4950 OS << *Function;
4951 if (Function->getPrimaryTemplate())
4952 OS << "<>";
4953 OS << "(";
4954 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4955 if (I)
4956 OS << ", ";
4957 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4958 }
4959
4960 if (Function->isVariadic()) {
4961 if (Function->getNumParams())
4962 OS << ", ";
4963 OS << "...";
4964 }
4965 OS << ")";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004966 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004967 }
4968
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00004969 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004970 SmallString<64> Str;
4971 llvm::raw_svector_ostream OS(Str);
4972 OS << *ClassTemplate;
4973 OS << "<";
4974 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4975 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4976 if (I)
4977 OS << ", ";
4978
4979 NamedDecl *Param = Params->getParam(I);
4980 if (Param->getIdentifier()) {
4981 OS << Param->getIdentifier()->getName();
4982 continue;
4983 }
4984
4985 // There is no parameter name, which makes this tricky. Try to come up
4986 // with something useful that isn't too long.
4987 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4988 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4989 else if (NonTypeTemplateParmDecl *NTTP
4990 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4991 OS << NTTP->getType().getAsString(Policy);
4992 else
4993 OS << "template<...> class";
4994 }
4995
4996 OS << ">";
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00004997 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00004998 }
4999
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005000 if (const ClassTemplateSpecializationDecl *ClassSpec
Guy Benyei11169dd2012-12-18 14:30:41 +00005001 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
5002 // If the type was explicitly written, use that.
5003 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005004 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
Serge Pavlov03e672c2017-11-28 16:14:14 +00005005
Benjamin Kramer9170e912013-02-22 15:46:01 +00005006 SmallString<128> Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00005007 llvm::raw_svector_ostream OS(Str);
5008 OS << *ClassSpec;
Serge Pavlov03e672c2017-11-28 16:14:14 +00005009 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5010 Policy);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00005011 return cxstring::createDup(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00005012 }
5013
5014 return clang_getCursorSpelling(C);
5015}
5016
5017CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5018 switch (Kind) {
5019 case CXCursor_FunctionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005020 return cxstring::createRef("FunctionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005021 case CXCursor_TypedefDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005022 return cxstring::createRef("TypedefDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005023 case CXCursor_EnumDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005024 return cxstring::createRef("EnumDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005025 case CXCursor_EnumConstantDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005026 return cxstring::createRef("EnumConstantDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005027 case CXCursor_StructDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005028 return cxstring::createRef("StructDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005029 case CXCursor_UnionDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005030 return cxstring::createRef("UnionDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005031 case CXCursor_ClassDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005032 return cxstring::createRef("ClassDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005033 case CXCursor_FieldDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005034 return cxstring::createRef("FieldDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005035 case CXCursor_VarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005036 return cxstring::createRef("VarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005037 case CXCursor_ParmDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005038 return cxstring::createRef("ParmDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005039 case CXCursor_ObjCInterfaceDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005040 return cxstring::createRef("ObjCInterfaceDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005041 case CXCursor_ObjCCategoryDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005042 return cxstring::createRef("ObjCCategoryDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005043 case CXCursor_ObjCProtocolDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005044 return cxstring::createRef("ObjCProtocolDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005045 case CXCursor_ObjCPropertyDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005046 return cxstring::createRef("ObjCPropertyDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005047 case CXCursor_ObjCIvarDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005048 return cxstring::createRef("ObjCIvarDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005049 case CXCursor_ObjCInstanceMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005050 return cxstring::createRef("ObjCInstanceMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005051 case CXCursor_ObjCClassMethodDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005052 return cxstring::createRef("ObjCClassMethodDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005053 case CXCursor_ObjCImplementationDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005054 return cxstring::createRef("ObjCImplementationDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005055 case CXCursor_ObjCCategoryImplDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005056 return cxstring::createRef("ObjCCategoryImplDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005057 case CXCursor_CXXMethod:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005058 return cxstring::createRef("CXXMethod");
Guy Benyei11169dd2012-12-18 14:30:41 +00005059 case CXCursor_UnexposedDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005060 return cxstring::createRef("UnexposedDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005061 case CXCursor_ObjCSuperClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005062 return cxstring::createRef("ObjCSuperClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005063 case CXCursor_ObjCProtocolRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005064 return cxstring::createRef("ObjCProtocolRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005065 case CXCursor_ObjCClassRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005066 return cxstring::createRef("ObjCClassRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005067 case CXCursor_TypeRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005068 return cxstring::createRef("TypeRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005069 case CXCursor_TemplateRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005070 return cxstring::createRef("TemplateRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005071 case CXCursor_NamespaceRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005072 return cxstring::createRef("NamespaceRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 case CXCursor_MemberRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005074 return cxstring::createRef("MemberRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005075 case CXCursor_LabelRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005076 return cxstring::createRef("LabelRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005077 case CXCursor_OverloadedDeclRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005078 return cxstring::createRef("OverloadedDeclRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005079 case CXCursor_VariableRef:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005080 return cxstring::createRef("VariableRef");
Guy Benyei11169dd2012-12-18 14:30:41 +00005081 case CXCursor_IntegerLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005082 return cxstring::createRef("IntegerLiteral");
Leonard Chandb01c3a2018-06-20 17:19:40 +00005083 case CXCursor_FixedPointLiteral:
5084 return cxstring::createRef("FixedPointLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005085 case CXCursor_FloatingLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005086 return cxstring::createRef("FloatingLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005087 case CXCursor_ImaginaryLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005088 return cxstring::createRef("ImaginaryLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005089 case CXCursor_StringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005090 return cxstring::createRef("StringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005091 case CXCursor_CharacterLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005092 return cxstring::createRef("CharacterLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005093 case CXCursor_ParenExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005094 return cxstring::createRef("ParenExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005095 case CXCursor_UnaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005096 return cxstring::createRef("UnaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005097 case CXCursor_ArraySubscriptExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005098 return cxstring::createRef("ArraySubscriptExpr");
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005099 case CXCursor_OMPArraySectionExpr:
5100 return cxstring::createRef("OMPArraySectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005101 case CXCursor_BinaryOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005102 return cxstring::createRef("BinaryOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005103 case CXCursor_CompoundAssignOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005104 return cxstring::createRef("CompoundAssignOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005105 case CXCursor_ConditionalOperator:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005106 return cxstring::createRef("ConditionalOperator");
Guy Benyei11169dd2012-12-18 14:30:41 +00005107 case CXCursor_CStyleCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005108 return cxstring::createRef("CStyleCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005109 case CXCursor_CompoundLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005110 return cxstring::createRef("CompoundLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005111 case CXCursor_InitListExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005112 return cxstring::createRef("InitListExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005113 case CXCursor_AddrLabelExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005114 return cxstring::createRef("AddrLabelExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005115 case CXCursor_StmtExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005116 return cxstring::createRef("StmtExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005117 case CXCursor_GenericSelectionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005118 return cxstring::createRef("GenericSelectionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005119 case CXCursor_GNUNullExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005120 return cxstring::createRef("GNUNullExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005121 case CXCursor_CXXStaticCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005122 return cxstring::createRef("CXXStaticCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005123 case CXCursor_CXXDynamicCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005124 return cxstring::createRef("CXXDynamicCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005125 case CXCursor_CXXReinterpretCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005126 return cxstring::createRef("CXXReinterpretCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005127 case CXCursor_CXXConstCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005128 return cxstring::createRef("CXXConstCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005129 case CXCursor_CXXFunctionalCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005130 return cxstring::createRef("CXXFunctionalCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005131 case CXCursor_CXXTypeidExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005132 return cxstring::createRef("CXXTypeidExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005133 case CXCursor_CXXBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005134 return cxstring::createRef("CXXBoolLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005135 case CXCursor_CXXNullPtrLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005136 return cxstring::createRef("CXXNullPtrLiteralExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005137 case CXCursor_CXXThisExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005138 return cxstring::createRef("CXXThisExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005139 case CXCursor_CXXThrowExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005140 return cxstring::createRef("CXXThrowExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005141 case CXCursor_CXXNewExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005142 return cxstring::createRef("CXXNewExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005143 case CXCursor_CXXDeleteExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005144 return cxstring::createRef("CXXDeleteExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005145 case CXCursor_UnaryExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005146 return cxstring::createRef("UnaryExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005147 case CXCursor_ObjCStringLiteral:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005148 return cxstring::createRef("ObjCStringLiteral");
Guy Benyei11169dd2012-12-18 14:30:41 +00005149 case CXCursor_ObjCBoolLiteralExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005150 return cxstring::createRef("ObjCBoolLiteralExpr");
Erik Pilkington29099de2016-07-16 00:35:23 +00005151 case CXCursor_ObjCAvailabilityCheckExpr:
5152 return cxstring::createRef("ObjCAvailabilityCheckExpr");
Argyrios Kyrtzidisc2233be2013-04-23 17:57:17 +00005153 case CXCursor_ObjCSelfExpr:
5154 return cxstring::createRef("ObjCSelfExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005155 case CXCursor_ObjCEncodeExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005156 return cxstring::createRef("ObjCEncodeExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005157 case CXCursor_ObjCSelectorExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005158 return cxstring::createRef("ObjCSelectorExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005159 case CXCursor_ObjCProtocolExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005160 return cxstring::createRef("ObjCProtocolExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005161 case CXCursor_ObjCBridgedCastExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005162 return cxstring::createRef("ObjCBridgedCastExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005163 case CXCursor_BlockExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005164 return cxstring::createRef("BlockExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005165 case CXCursor_PackExpansionExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005166 return cxstring::createRef("PackExpansionExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005167 case CXCursor_SizeOfPackExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005168 return cxstring::createRef("SizeOfPackExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005169 case CXCursor_LambdaExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005170 return cxstring::createRef("LambdaExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005171 case CXCursor_UnexposedExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005172 return cxstring::createRef("UnexposedExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005173 case CXCursor_DeclRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005174 return cxstring::createRef("DeclRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005175 case CXCursor_MemberRefExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005176 return cxstring::createRef("MemberRefExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005177 case CXCursor_CallExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005178 return cxstring::createRef("CallExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005179 case CXCursor_ObjCMessageExpr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005180 return cxstring::createRef("ObjCMessageExpr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005181 case CXCursor_UnexposedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005182 return cxstring::createRef("UnexposedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005183 case CXCursor_DeclStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005184 return cxstring::createRef("DeclStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005185 case CXCursor_LabelStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005186 return cxstring::createRef("LabelStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005187 case CXCursor_CompoundStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005188 return cxstring::createRef("CompoundStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005189 case CXCursor_CaseStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005190 return cxstring::createRef("CaseStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005191 case CXCursor_DefaultStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005192 return cxstring::createRef("DefaultStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005193 case CXCursor_IfStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005194 return cxstring::createRef("IfStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005195 case CXCursor_SwitchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005196 return cxstring::createRef("SwitchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005197 case CXCursor_WhileStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005198 return cxstring::createRef("WhileStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005199 case CXCursor_DoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005200 return cxstring::createRef("DoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005201 case CXCursor_ForStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005202 return cxstring::createRef("ForStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005203 case CXCursor_GotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005204 return cxstring::createRef("GotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005205 case CXCursor_IndirectGotoStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005206 return cxstring::createRef("IndirectGotoStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005207 case CXCursor_ContinueStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005208 return cxstring::createRef("ContinueStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005209 case CXCursor_BreakStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005210 return cxstring::createRef("BreakStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005211 case CXCursor_ReturnStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005212 return cxstring::createRef("ReturnStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005213 case CXCursor_GCCAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005214 return cxstring::createRef("GCCAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005215 case CXCursor_MSAsmStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005216 return cxstring::createRef("MSAsmStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005217 case CXCursor_ObjCAtTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005218 return cxstring::createRef("ObjCAtTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005219 case CXCursor_ObjCAtCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005220 return cxstring::createRef("ObjCAtCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005221 case CXCursor_ObjCAtFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005222 return cxstring::createRef("ObjCAtFinallyStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005223 case CXCursor_ObjCAtThrowStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005224 return cxstring::createRef("ObjCAtThrowStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005225 case CXCursor_ObjCAtSynchronizedStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005226 return cxstring::createRef("ObjCAtSynchronizedStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005227 case CXCursor_ObjCAutoreleasePoolStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005228 return cxstring::createRef("ObjCAutoreleasePoolStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005229 case CXCursor_ObjCForCollectionStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005230 return cxstring::createRef("ObjCForCollectionStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005231 case CXCursor_CXXCatchStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005232 return cxstring::createRef("CXXCatchStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005233 case CXCursor_CXXTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005234 return cxstring::createRef("CXXTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005235 case CXCursor_CXXForRangeStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005236 return cxstring::createRef("CXXForRangeStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005237 case CXCursor_SEHTryStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005238 return cxstring::createRef("SEHTryStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005239 case CXCursor_SEHExceptStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005240 return cxstring::createRef("SEHExceptStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005241 case CXCursor_SEHFinallyStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005242 return cxstring::createRef("SEHFinallyStmt");
Nico Weber9b982072014-07-07 00:12:30 +00005243 case CXCursor_SEHLeaveStmt:
5244 return cxstring::createRef("SEHLeaveStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005245 case CXCursor_NullStmt:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005246 return cxstring::createRef("NullStmt");
Guy Benyei11169dd2012-12-18 14:30:41 +00005247 case CXCursor_InvalidFile:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005248 return cxstring::createRef("InvalidFile");
Guy Benyei11169dd2012-12-18 14:30:41 +00005249 case CXCursor_InvalidCode:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005250 return cxstring::createRef("InvalidCode");
Guy Benyei11169dd2012-12-18 14:30:41 +00005251 case CXCursor_NoDeclFound:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005252 return cxstring::createRef("NoDeclFound");
Guy Benyei11169dd2012-12-18 14:30:41 +00005253 case CXCursor_NotImplemented:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005254 return cxstring::createRef("NotImplemented");
Guy Benyei11169dd2012-12-18 14:30:41 +00005255 case CXCursor_TranslationUnit:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005256 return cxstring::createRef("TranslationUnit");
Guy Benyei11169dd2012-12-18 14:30:41 +00005257 case CXCursor_UnexposedAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005258 return cxstring::createRef("UnexposedAttr");
Guy Benyei11169dd2012-12-18 14:30:41 +00005259 case CXCursor_IBActionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005260 return cxstring::createRef("attribute(ibaction)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005261 case CXCursor_IBOutletAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005262 return cxstring::createRef("attribute(iboutlet)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005263 case CXCursor_IBOutletCollectionAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005264 return cxstring::createRef("attribute(iboutletcollection)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005265 case CXCursor_CXXFinalAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005266 return cxstring::createRef("attribute(final)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005267 case CXCursor_CXXOverrideAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005268 return cxstring::createRef("attribute(override)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005269 case CXCursor_AnnotateAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005270 return cxstring::createRef("attribute(annotate)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005271 case CXCursor_AsmLabelAttr:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005272 return cxstring::createRef("asm label");
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005273 case CXCursor_PackedAttr:
5274 return cxstring::createRef("attribute(packed)");
Joey Gouly81228382014-05-01 15:41:58 +00005275 case CXCursor_PureAttr:
5276 return cxstring::createRef("attribute(pure)");
5277 case CXCursor_ConstAttr:
5278 return cxstring::createRef("attribute(const)");
5279 case CXCursor_NoDuplicateAttr:
5280 return cxstring::createRef("attribute(noduplicate)");
Eli Bendersky2581e662014-05-28 19:29:58 +00005281 case CXCursor_CUDAConstantAttr:
5282 return cxstring::createRef("attribute(constant)");
5283 case CXCursor_CUDADeviceAttr:
5284 return cxstring::createRef("attribute(device)");
5285 case CXCursor_CUDAGlobalAttr:
5286 return cxstring::createRef("attribute(global)");
5287 case CXCursor_CUDAHostAttr:
5288 return cxstring::createRef("attribute(host)");
Eli Bendersky9b071472014-08-08 14:59:00 +00005289 case CXCursor_CUDASharedAttr:
5290 return cxstring::createRef("attribute(shared)");
Saleem Abdulrasool79c69712015-09-05 18:53:43 +00005291 case CXCursor_VisibilityAttr:
5292 return cxstring::createRef("attribute(visibility)");
Saleem Abdulrasool8aa0b802015-12-10 18:45:18 +00005293 case CXCursor_DLLExport:
5294 return cxstring::createRef("attribute(dllexport)");
5295 case CXCursor_DLLImport:
5296 return cxstring::createRef("attribute(dllimport)");
Michael Wud092d0b2018-08-03 05:03:22 +00005297 case CXCursor_NSReturnsRetained:
5298 return cxstring::createRef("attribute(ns_returns_retained)");
5299 case CXCursor_NSReturnsNotRetained:
5300 return cxstring::createRef("attribute(ns_returns_not_retained)");
5301 case CXCursor_NSReturnsAutoreleased:
5302 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5303 case CXCursor_NSConsumesSelf:
5304 return cxstring::createRef("attribute(ns_consumes_self)");
5305 case CXCursor_NSConsumed:
5306 return cxstring::createRef("attribute(ns_consumed)");
5307 case CXCursor_ObjCException:
5308 return cxstring::createRef("attribute(objc_exception)");
5309 case CXCursor_ObjCNSObject:
5310 return cxstring::createRef("attribute(NSObject)");
5311 case CXCursor_ObjCIndependentClass:
5312 return cxstring::createRef("attribute(objc_independent_class)");
5313 case CXCursor_ObjCPreciseLifetime:
5314 return cxstring::createRef("attribute(objc_precise_lifetime)");
5315 case CXCursor_ObjCReturnsInnerPointer:
5316 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5317 case CXCursor_ObjCRequiresSuper:
5318 return cxstring::createRef("attribute(objc_requires_super)");
5319 case CXCursor_ObjCRootClass:
5320 return cxstring::createRef("attribute(objc_root_class)");
5321 case CXCursor_ObjCSubclassingRestricted:
5322 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5323 case CXCursor_ObjCExplicitProtocolImpl:
5324 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5325 case CXCursor_ObjCDesignatedInitializer:
5326 return cxstring::createRef("attribute(objc_designated_initializer)");
5327 case CXCursor_ObjCRuntimeVisible:
5328 return cxstring::createRef("attribute(objc_runtime_visible)");
5329 case CXCursor_ObjCBoxable:
5330 return cxstring::createRef("attribute(objc_boxable)");
Michael Wu58d837d2018-08-03 05:55:40 +00005331 case CXCursor_FlagEnum:
5332 return cxstring::createRef("attribute(flag_enum)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005333 case CXCursor_PreprocessingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005334 return cxstring::createRef("preprocessing directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005335 case CXCursor_MacroDefinition:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005336 return cxstring::createRef("macro definition");
Guy Benyei11169dd2012-12-18 14:30:41 +00005337 case CXCursor_MacroExpansion:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005338 return cxstring::createRef("macro expansion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005339 case CXCursor_InclusionDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005340 return cxstring::createRef("inclusion directive");
Guy Benyei11169dd2012-12-18 14:30:41 +00005341 case CXCursor_Namespace:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005342 return cxstring::createRef("Namespace");
Guy Benyei11169dd2012-12-18 14:30:41 +00005343 case CXCursor_LinkageSpec:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005344 return cxstring::createRef("LinkageSpec");
Guy Benyei11169dd2012-12-18 14:30:41 +00005345 case CXCursor_CXXBaseSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005346 return cxstring::createRef("C++ base class specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005347 case CXCursor_Constructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005348 return cxstring::createRef("CXXConstructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005349 case CXCursor_Destructor:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005350 return cxstring::createRef("CXXDestructor");
Guy Benyei11169dd2012-12-18 14:30:41 +00005351 case CXCursor_ConversionFunction:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005352 return cxstring::createRef("CXXConversion");
Guy Benyei11169dd2012-12-18 14:30:41 +00005353 case CXCursor_TemplateTypeParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005354 return cxstring::createRef("TemplateTypeParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005355 case CXCursor_NonTypeTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005356 return cxstring::createRef("NonTypeTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005357 case CXCursor_TemplateTemplateParameter:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005358 return cxstring::createRef("TemplateTemplateParameter");
Guy Benyei11169dd2012-12-18 14:30:41 +00005359 case CXCursor_FunctionTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005360 return cxstring::createRef("FunctionTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005361 case CXCursor_ClassTemplate:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005362 return cxstring::createRef("ClassTemplate");
Guy Benyei11169dd2012-12-18 14:30:41 +00005363 case CXCursor_ClassTemplatePartialSpecialization:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005364 return cxstring::createRef("ClassTemplatePartialSpecialization");
Guy Benyei11169dd2012-12-18 14:30:41 +00005365 case CXCursor_NamespaceAlias:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005366 return cxstring::createRef("NamespaceAlias");
Guy Benyei11169dd2012-12-18 14:30:41 +00005367 case CXCursor_UsingDirective:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005368 return cxstring::createRef("UsingDirective");
Guy Benyei11169dd2012-12-18 14:30:41 +00005369 case CXCursor_UsingDeclaration:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005370 return cxstring::createRef("UsingDeclaration");
Guy Benyei11169dd2012-12-18 14:30:41 +00005371 case CXCursor_TypeAliasDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005372 return cxstring::createRef("TypeAliasDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005373 case CXCursor_ObjCSynthesizeDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005374 return cxstring::createRef("ObjCSynthesizeDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005375 case CXCursor_ObjCDynamicDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005376 return cxstring::createRef("ObjCDynamicDecl");
Guy Benyei11169dd2012-12-18 14:30:41 +00005377 case CXCursor_CXXAccessSpecifier:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005378 return cxstring::createRef("CXXAccessSpecifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005379 case CXCursor_ModuleImportDecl:
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00005380 return cxstring::createRef("ModuleImport");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005381 case CXCursor_OMPParallelDirective:
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005382 return cxstring::createRef("OMPParallelDirective");
5383 case CXCursor_OMPSimdDirective:
5384 return cxstring::createRef("OMPSimdDirective");
Alexey Bataevf29276e2014-06-18 04:14:57 +00005385 case CXCursor_OMPForDirective:
5386 return cxstring::createRef("OMPForDirective");
Alexander Musmanf82886e2014-09-18 05:12:34 +00005387 case CXCursor_OMPForSimdDirective:
5388 return cxstring::createRef("OMPForSimdDirective");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005389 case CXCursor_OMPSectionsDirective:
5390 return cxstring::createRef("OMPSectionsDirective");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005391 case CXCursor_OMPSectionDirective:
5392 return cxstring::createRef("OMPSectionDirective");
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005393 case CXCursor_OMPSingleDirective:
5394 return cxstring::createRef("OMPSingleDirective");
Alexander Musman80c22892014-07-17 08:54:58 +00005395 case CXCursor_OMPMasterDirective:
5396 return cxstring::createRef("OMPMasterDirective");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005397 case CXCursor_OMPCriticalDirective:
5398 return cxstring::createRef("OMPCriticalDirective");
Alexey Bataev4acb8592014-07-07 13:01:15 +00005399 case CXCursor_OMPParallelForDirective:
5400 return cxstring::createRef("OMPParallelForDirective");
Alexander Musmane4e893b2014-09-23 09:33:00 +00005401 case CXCursor_OMPParallelForSimdDirective:
5402 return cxstring::createRef("OMPParallelForSimdDirective");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005403 case CXCursor_OMPParallelSectionsDirective:
5404 return cxstring::createRef("OMPParallelSectionsDirective");
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005405 case CXCursor_OMPTaskDirective:
5406 return cxstring::createRef("OMPTaskDirective");
Alexey Bataev68446b72014-07-18 07:47:19 +00005407 case CXCursor_OMPTaskyieldDirective:
5408 return cxstring::createRef("OMPTaskyieldDirective");
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005409 case CXCursor_OMPBarrierDirective:
5410 return cxstring::createRef("OMPBarrierDirective");
Alexey Bataev2df347a2014-07-18 10:17:07 +00005411 case CXCursor_OMPTaskwaitDirective:
5412 return cxstring::createRef("OMPTaskwaitDirective");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005413 case CXCursor_OMPTaskgroupDirective:
5414 return cxstring::createRef("OMPTaskgroupDirective");
Alexey Bataev6125da92014-07-21 11:26:11 +00005415 case CXCursor_OMPFlushDirective:
5416 return cxstring::createRef("OMPFlushDirective");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005417 case CXCursor_OMPOrderedDirective:
5418 return cxstring::createRef("OMPOrderedDirective");
Alexey Bataev0162e452014-07-22 10:10:35 +00005419 case CXCursor_OMPAtomicDirective:
5420 return cxstring::createRef("OMPAtomicDirective");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005421 case CXCursor_OMPTargetDirective:
5422 return cxstring::createRef("OMPTargetDirective");
Michael Wong65f367f2015-07-21 13:44:28 +00005423 case CXCursor_OMPTargetDataDirective:
5424 return cxstring::createRef("OMPTargetDataDirective");
Samuel Antaodf67fc42016-01-19 19:15:56 +00005425 case CXCursor_OMPTargetEnterDataDirective:
5426 return cxstring::createRef("OMPTargetEnterDataDirective");
Samuel Antao72590762016-01-19 20:04:50 +00005427 case CXCursor_OMPTargetExitDataDirective:
5428 return cxstring::createRef("OMPTargetExitDataDirective");
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005429 case CXCursor_OMPTargetParallelDirective:
5430 return cxstring::createRef("OMPTargetParallelDirective");
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005431 case CXCursor_OMPTargetParallelForDirective:
5432 return cxstring::createRef("OMPTargetParallelForDirective");
Samuel Antao686c70c2016-05-26 17:30:50 +00005433 case CXCursor_OMPTargetUpdateDirective:
5434 return cxstring::createRef("OMPTargetUpdateDirective");
Alexey Bataev13314bf2014-10-09 04:18:56 +00005435 case CXCursor_OMPTeamsDirective:
5436 return cxstring::createRef("OMPTeamsDirective");
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005437 case CXCursor_OMPCancellationPointDirective:
5438 return cxstring::createRef("OMPCancellationPointDirective");
Alexey Bataev80909872015-07-02 11:25:17 +00005439 case CXCursor_OMPCancelDirective:
5440 return cxstring::createRef("OMPCancelDirective");
Alexey Bataev49f6e782015-12-01 04:18:41 +00005441 case CXCursor_OMPTaskLoopDirective:
5442 return cxstring::createRef("OMPTaskLoopDirective");
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005443 case CXCursor_OMPTaskLoopSimdDirective:
5444 return cxstring::createRef("OMPTaskLoopSimdDirective");
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005445 case CXCursor_OMPDistributeDirective:
5446 return cxstring::createRef("OMPDistributeDirective");
Carlo Bertolli9925f152016-06-27 14:55:37 +00005447 case CXCursor_OMPDistributeParallelForDirective:
5448 return cxstring::createRef("OMPDistributeParallelForDirective");
Kelvin Li4a39add2016-07-05 05:00:15 +00005449 case CXCursor_OMPDistributeParallelForSimdDirective:
5450 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
Kelvin Li787f3fc2016-07-06 04:45:38 +00005451 case CXCursor_OMPDistributeSimdDirective:
5452 return cxstring::createRef("OMPDistributeSimdDirective");
Kelvin Lia579b912016-07-14 02:54:56 +00005453 case CXCursor_OMPTargetParallelForSimdDirective:
5454 return cxstring::createRef("OMPTargetParallelForSimdDirective");
Kelvin Li986330c2016-07-20 22:57:10 +00005455 case CXCursor_OMPTargetSimdDirective:
5456 return cxstring::createRef("OMPTargetSimdDirective");
Kelvin Li02532872016-08-05 14:37:37 +00005457 case CXCursor_OMPTeamsDistributeDirective:
5458 return cxstring::createRef("OMPTeamsDistributeDirective");
Kelvin Li4e325f72016-10-25 12:50:55 +00005459 case CXCursor_OMPTeamsDistributeSimdDirective:
5460 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
Kelvin Li579e41c2016-11-30 23:51:03 +00005461 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5462 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
Kelvin Li7ade93f2016-12-09 03:24:30 +00005463 case CXCursor_OMPTeamsDistributeParallelForDirective:
5464 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
Kelvin Libf594a52016-12-17 05:48:59 +00005465 case CXCursor_OMPTargetTeamsDirective:
5466 return cxstring::createRef("OMPTargetTeamsDirective");
Kelvin Li83c451e2016-12-25 04:52:54 +00005467 case CXCursor_OMPTargetTeamsDistributeDirective:
5468 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
Kelvin Li80e8f562016-12-29 22:16:30 +00005469 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5470 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
Kelvin Li1851df52017-01-03 05:23:48 +00005471 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5472 return cxstring::createRef(
5473 "OMPTargetTeamsDistributeParallelForSimdDirective");
Kelvin Lida681182017-01-10 18:08:18 +00005474 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5475 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005476 case CXCursor_OverloadCandidate:
5477 return cxstring::createRef("OverloadCandidate");
Sergey Kalinichev8f3b1872015-11-15 13:48:32 +00005478 case CXCursor_TypeAliasTemplateDecl:
5479 return cxstring::createRef("TypeAliasTemplateDecl");
Olivier Goffart81978012016-06-09 16:15:55 +00005480 case CXCursor_StaticAssert:
5481 return cxstring::createRef("StaticAssert");
Olivier Goffartd211c642016-11-04 06:29:27 +00005482 case CXCursor_FriendDecl:
Sven van Haastregtdc2c9302019-02-11 11:00:56 +00005483 return cxstring::createRef("FriendDecl");
5484 case CXCursor_ConvergentAttr:
5485 return cxstring::createRef("attribute(convergent)");
Emilio Cobos Alvarez0a3fe502019-02-25 21:24:52 +00005486 case CXCursor_WarnUnusedAttr:
5487 return cxstring::createRef("attribute(warn_unused)");
5488 case CXCursor_WarnUnusedResultAttr:
5489 return cxstring::createRef("attribute(warn_unused_result)");
Emilio Cobos Alvarezcd741272019-03-13 16:16:54 +00005490 case CXCursor_AlignedAttr:
5491 return cxstring::createRef("attribute(aligned)");
Guy Benyei11169dd2012-12-18 14:30:41 +00005492 }
5493
5494 llvm_unreachable("Unhandled CXCursorKind");
5495}
5496
5497struct GetCursorData {
5498 SourceLocation TokenBeginLoc;
5499 bool PointsAtMacroArgExpansion;
5500 bool VisitedObjCPropertyImplDecl;
5501 SourceLocation VisitedDeclaratorDeclStartLoc;
5502 CXCursor &BestCursor;
5503
5504 GetCursorData(SourceManager &SM,
5505 SourceLocation tokenBegin, CXCursor &outputCursor)
5506 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5507 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5508 VisitedObjCPropertyImplDecl = false;
5509 }
5510};
5511
5512static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5513 CXCursor parent,
5514 CXClientData client_data) {
5515 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5516 CXCursor *BestCursor = &Data->BestCursor;
5517
5518 // If we point inside a macro argument we should provide info of what the
5519 // token is so use the actual cursor, don't replace it with a macro expansion
5520 // cursor.
5521 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5522 return CXChildVisit_Recurse;
5523
5524 if (clang_isDeclaration(cursor.kind)) {
5525 // Avoid having the implicit methods override the property decls.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005526 if (const ObjCMethodDecl *MD
Guy Benyei11169dd2012-12-18 14:30:41 +00005527 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5528 if (MD->isImplicit())
5529 return CXChildVisit_Break;
5530
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005531 } else if (const ObjCInterfaceDecl *ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005532 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5533 // Check that when we have multiple @class references in the same line,
5534 // that later ones do not override the previous ones.
5535 // If we have:
5536 // @class Foo, Bar;
5537 // source ranges for both start at '@', so 'Bar' will end up overriding
5538 // 'Foo' even though the cursor location was at 'Foo'.
5539 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5540 BestCursor->kind == CXCursor_ObjCClassRef)
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005541 if (const ObjCInterfaceDecl *PrevID
Guy Benyei11169dd2012-12-18 14:30:41 +00005542 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5543 if (PrevID != ID &&
5544 !PrevID->isThisDeclarationADefinition() &&
5545 !ID->isThisDeclarationADefinition())
5546 return CXChildVisit_Break;
5547 }
5548
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005549 } else if (const DeclaratorDecl *DD
Guy Benyei11169dd2012-12-18 14:30:41 +00005550 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5551 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5552 // Check that when we have multiple declarators in the same line,
5553 // that later ones do not override the previous ones.
5554 // If we have:
5555 // int Foo, Bar;
5556 // source ranges for both start at 'int', so 'Bar' will end up overriding
5557 // 'Foo' even though the cursor location was at 'Foo'.
5558 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5559 return CXChildVisit_Break;
5560 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5561
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005562 } else if (const ObjCPropertyImplDecl *PropImp
Guy Benyei11169dd2012-12-18 14:30:41 +00005563 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5564 (void)PropImp;
5565 // Check that when we have multiple @synthesize in the same line,
5566 // that later ones do not override the previous ones.
5567 // If we have:
5568 // @synthesize Foo, Bar;
5569 // source ranges for both start at '@', so 'Bar' will end up overriding
5570 // 'Foo' even though the cursor location was at 'Foo'.
5571 if (Data->VisitedObjCPropertyImplDecl)
5572 return CXChildVisit_Break;
5573 Data->VisitedObjCPropertyImplDecl = true;
5574 }
5575 }
5576
5577 if (clang_isExpression(cursor.kind) &&
5578 clang_isDeclaration(BestCursor->kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005579 if (const Decl *D = getCursorDecl(*BestCursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005580 // Avoid having the cursor of an expression replace the declaration cursor
5581 // when the expression source range overlaps the declaration range.
5582 // This can happen for C++ constructor expressions whose range generally
5583 // include the variable declaration, e.g.:
5584 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5585 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5586 D->getLocation() == Data->TokenBeginLoc)
5587 return CXChildVisit_Break;
5588 }
5589 }
5590
5591 // If our current best cursor is the construction of a temporary object,
5592 // don't replace that cursor with a type reference, because we want
5593 // clang_getCursor() to point at the constructor.
5594 if (clang_isExpression(BestCursor->kind) &&
5595 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5596 cursor.kind == CXCursor_TypeRef) {
5597 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5598 // as having the actual point on the type reference.
5599 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5600 return CXChildVisit_Recurse;
5601 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00005602
5603 // If we already have an Objective-C superclass reference, don't
5604 // update it further.
5605 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5606 return CXChildVisit_Break;
5607
Guy Benyei11169dd2012-12-18 14:30:41 +00005608 *BestCursor = cursor;
5609 return CXChildVisit_Recurse;
5610}
5611
5612CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00005613 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005614 LOG_BAD_TU(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005615 return clang_getNullCursor();
Dmitri Gribenko256454f2014-02-11 14:34:14 +00005616 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005617
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005618 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005619 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5620
5621 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5622 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5623
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005624 LOG_FUNC_SECTION {
Guy Benyei11169dd2012-12-18 14:30:41 +00005625 CXFile SearchFile;
5626 unsigned SearchLine, SearchColumn;
5627 CXFile ResultFile;
5628 unsigned ResultLine, ResultColumn;
5629 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5630 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5631 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
Craig Topper69186e72014-06-08 08:38:04 +00005632
5633 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5634 nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005635 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
Craig Topper69186e72014-06-08 08:38:04 +00005636 &ResultColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005637 SearchFileName = clang_getFileName(SearchFile);
5638 ResultFileName = clang_getFileName(ResultFile);
5639 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5640 USR = clang_getCursorUSR(Result);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005641 *Log << llvm::format("(%s:%d:%d) = %s",
5642 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5643 clang_getCString(KindSpelling))
5644 << llvm::format("(%s:%d:%d):%s%s",
5645 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5646 clang_getCString(USR), IsDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00005647 clang_disposeString(SearchFileName);
5648 clang_disposeString(ResultFileName);
5649 clang_disposeString(KindSpelling);
5650 clang_disposeString(USR);
5651
5652 CXCursor Definition = clang_getCursorDefinition(Result);
5653 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5654 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5655 CXString DefinitionKindSpelling
5656 = clang_getCursorKindSpelling(Definition.kind);
5657 CXFile DefinitionFile;
5658 unsigned DefinitionLine, DefinitionColumn;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005659 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
Craig Topper69186e72014-06-08 08:38:04 +00005660 &DefinitionLine, &DefinitionColumn, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005661 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00005662 *Log << llvm::format(" -> %s(%s:%d:%d)",
5663 clang_getCString(DefinitionKindSpelling),
5664 clang_getCString(DefinitionFileName),
5665 DefinitionLine, DefinitionColumn);
Guy Benyei11169dd2012-12-18 14:30:41 +00005666 clang_disposeString(DefinitionFileName);
5667 clang_disposeString(DefinitionKindSpelling);
5668 }
5669 }
5670
5671 return Result;
5672}
5673
5674CXCursor clang_getNullCursor(void) {
5675 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5676}
5677
5678unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005679 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5680 // can't set consistently. For example, when visiting a DeclStmt we will set
5681 // it but we don't set it on the result of clang_getCursorDefinition for
5682 // a reference of the same declaration.
5683 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5684 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5685 // to provide that kind of info.
5686 if (clang_isDeclaration(X.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005687 X.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005688 if (clang_isDeclaration(Y.kind))
Craig Topper69186e72014-06-08 08:38:04 +00005689 Y.data[1] = nullptr;
Argyrios Kyrtzidisbf1be592013-01-08 18:23:28 +00005690
Guy Benyei11169dd2012-12-18 14:30:41 +00005691 return X == Y;
5692}
5693
5694unsigned clang_hashCursor(CXCursor C) {
5695 unsigned Index = 0;
5696 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5697 Index = 1;
5698
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005699 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
Guy Benyei11169dd2012-12-18 14:30:41 +00005700 std::make_pair(C.kind, C.data[Index]));
5701}
5702
5703unsigned clang_isInvalid(enum CXCursorKind K) {
5704 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5705}
5706
5707unsigned clang_isDeclaration(enum CXCursorKind K) {
5708 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005709 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5710}
5711
Ivan Donchevskii08ff9102018-01-04 10:59:50 +00005712unsigned clang_isInvalidDeclaration(CXCursor C) {
5713 if (clang_isDeclaration(C.kind)) {
5714 if (const Decl *D = getCursorDecl(C))
5715 return D->isInvalidDecl();
5716 }
5717
5718 return 0;
5719}
5720
Ivan Donchevskii1c27b152018-01-03 10:33:21 +00005721unsigned clang_isReference(enum CXCursorKind K) {
5722 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5723}
Guy Benyei11169dd2012-12-18 14:30:41 +00005724
5725unsigned clang_isExpression(enum CXCursorKind K) {
5726 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5727}
5728
5729unsigned clang_isStatement(enum CXCursorKind K) {
5730 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5731}
5732
5733unsigned clang_isAttribute(enum CXCursorKind K) {
5734 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5735}
5736
5737unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5738 return K == CXCursor_TranslationUnit;
5739}
5740
5741unsigned clang_isPreprocessing(enum CXCursorKind K) {
5742 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5743}
5744
5745unsigned clang_isUnexposed(enum CXCursorKind K) {
5746 switch (K) {
5747 case CXCursor_UnexposedDecl:
5748 case CXCursor_UnexposedExpr:
5749 case CXCursor_UnexposedStmt:
5750 case CXCursor_UnexposedAttr:
5751 return true;
5752 default:
5753 return false;
5754 }
5755}
5756
5757CXCursorKind clang_getCursorKind(CXCursor C) {
5758 return C.kind;
5759}
5760
5761CXSourceLocation clang_getCursorLocation(CXCursor C) {
5762 if (clang_isReference(C.kind)) {
5763 switch (C.kind) {
5764 case CXCursor_ObjCSuperClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005765 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005766 = getCursorObjCSuperClassRef(C);
5767 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5768 }
5769
5770 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005771 std::pair<const ObjCProtocolDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005772 = getCursorObjCProtocolRef(C);
5773 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5774 }
5775
5776 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005777 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
Guy Benyei11169dd2012-12-18 14:30:41 +00005778 = getCursorObjCClassRef(C);
5779 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5780 }
5781
5782 case CXCursor_TypeRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005783 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005784 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5785 }
5786
5787 case CXCursor_TemplateRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005788 std::pair<const TemplateDecl *, SourceLocation> P =
5789 getCursorTemplateRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005790 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5791 }
5792
5793 case CXCursor_NamespaceRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005794 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005795 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5796 }
5797
5798 case CXCursor_MemberRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005799 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005800 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5801 }
5802
5803 case CXCursor_VariableRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005804 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005805 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5806 }
5807
5808 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005809 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005810 if (!BaseSpec)
5811 return clang_getNullLocation();
5812
5813 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5814 return cxloc::translateSourceLocation(getCursorContext(C),
5815 TSInfo->getTypeLoc().getBeginLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005816
Guy Benyei11169dd2012-12-18 14:30:41 +00005817 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005818 BaseSpec->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005819 }
5820
5821 case CXCursor_LabelRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00005822 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005823 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5824 }
5825
5826 case CXCursor_OverloadedDeclRef:
5827 return cxloc::translateSourceLocation(getCursorContext(C),
5828 getCursorOverloadedDeclRef(C).second);
5829
5830 default:
5831 // FIXME: Need a way to enumerate all non-reference cases.
5832 llvm_unreachable("Missed a reference kind");
5833 }
5834 }
5835
5836 if (clang_isExpression(C.kind))
5837 return cxloc::translateSourceLocation(getCursorContext(C),
5838 getLocationFromExpr(getCursorExpr(C)));
5839
5840 if (clang_isStatement(C.kind))
5841 return cxloc::translateSourceLocation(getCursorContext(C),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005842 getCursorStmt(C)->getBeginLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00005843
5844 if (C.kind == CXCursor_PreprocessingDirective) {
5845 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5846 return cxloc::translateSourceLocation(getCursorContext(C), L);
5847 }
5848
5849 if (C.kind == CXCursor_MacroExpansion) {
5850 SourceLocation L
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005851 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei11169dd2012-12-18 14:30:41 +00005852 return cxloc::translateSourceLocation(getCursorContext(C), L);
5853 }
5854
5855 if (C.kind == CXCursor_MacroDefinition) {
5856 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5857 return cxloc::translateSourceLocation(getCursorContext(C), L);
5858 }
5859
5860 if (C.kind == CXCursor_InclusionDirective) {
5861 SourceLocation L
5862 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5863 return cxloc::translateSourceLocation(getCursorContext(C), L);
5864 }
5865
Argyrios Kyrtzidis16834f12013-09-25 00:14:38 +00005866 if (clang_isAttribute(C.kind)) {
5867 SourceLocation L
5868 = cxcursor::getCursorAttr(C)->getLocation();
5869 return cxloc::translateSourceLocation(getCursorContext(C), L);
5870 }
5871
Guy Benyei11169dd2012-12-18 14:30:41 +00005872 if (!clang_isDeclaration(C.kind))
5873 return clang_getNullLocation();
5874
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005875 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00005876 if (!D)
5877 return clang_getNullLocation();
5878
5879 SourceLocation Loc = D->getLocation();
5880 // FIXME: Multiple variables declared in a single declaration
5881 // currently lack the information needed to correctly determine their
5882 // ranges when accounting for the type-specifier. We use context
5883 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5884 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005885 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005886 if (!cxcursor::isFirstInDeclGroup(C))
5887 Loc = VD->getLocation();
5888 }
5889
5890 // For ObjC methods, give the start location of the method name.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00005891 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00005892 Loc = MD->getSelectorStartLoc();
5893
5894 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5895}
5896
NAKAMURA Takumia01f4c32016-12-19 16:50:43 +00005897} // end extern "C"
5898
Guy Benyei11169dd2012-12-18 14:30:41 +00005899CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5900 assert(TU);
5901
5902 // Guard against an invalid SourceLocation, or we may assert in one
5903 // of the following calls.
5904 if (SLoc.isInvalid())
5905 return clang_getNullCursor();
5906
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00005907 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00005908
5909 // Translate the given source location to make it point at the beginning of
5910 // the token under the cursor.
5911 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5912 CXXUnit->getASTContext().getLangOpts());
5913
5914 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5915 if (SLoc.isValid()) {
5916 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5917 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5918 /*VisitPreprocessorLast=*/true,
5919 /*VisitIncludedEntities=*/false,
5920 SourceLocation(SLoc));
5921 CursorVis.visitFileRegion();
5922 }
5923
5924 return Result;
5925}
5926
5927static SourceRange getRawCursorExtent(CXCursor C) {
5928 if (clang_isReference(C.kind)) {
5929 switch (C.kind) {
5930 case CXCursor_ObjCSuperClassRef:
5931 return getCursorObjCSuperClassRef(C).second;
5932
5933 case CXCursor_ObjCProtocolRef:
5934 return getCursorObjCProtocolRef(C).second;
5935
5936 case CXCursor_ObjCClassRef:
5937 return getCursorObjCClassRef(C).second;
5938
5939 case CXCursor_TypeRef:
5940 return getCursorTypeRef(C).second;
5941
5942 case CXCursor_TemplateRef:
5943 return getCursorTemplateRef(C).second;
5944
5945 case CXCursor_NamespaceRef:
5946 return getCursorNamespaceRef(C).second;
5947
5948 case CXCursor_MemberRef:
5949 return getCursorMemberRef(C).second;
5950
5951 case CXCursor_CXXBaseSpecifier:
5952 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5953
5954 case CXCursor_LabelRef:
5955 return getCursorLabelRef(C).second;
5956
5957 case CXCursor_OverloadedDeclRef:
5958 return getCursorOverloadedDeclRef(C).second;
5959
5960 case CXCursor_VariableRef:
5961 return getCursorVariableRef(C).second;
5962
5963 default:
5964 // FIXME: Need a way to enumerate all non-reference cases.
5965 llvm_unreachable("Missed a reference kind");
5966 }
5967 }
5968
5969 if (clang_isExpression(C.kind))
5970 return getCursorExpr(C)->getSourceRange();
5971
5972 if (clang_isStatement(C.kind))
5973 return getCursorStmt(C)->getSourceRange();
5974
5975 if (clang_isAttribute(C.kind))
5976 return getCursorAttr(C)->getRange();
5977
5978 if (C.kind == CXCursor_PreprocessingDirective)
5979 return cxcursor::getCursorPreprocessingDirective(C);
5980
5981 if (C.kind == CXCursor_MacroExpansion) {
5982 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00005983 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00005984 return TU->mapRangeFromPreamble(Range);
5985 }
5986
5987 if (C.kind == CXCursor_MacroDefinition) {
5988 ASTUnit *TU = getCursorASTUnit(C);
5989 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5990 return TU->mapRangeFromPreamble(Range);
5991 }
5992
5993 if (C.kind == CXCursor_InclusionDirective) {
5994 ASTUnit *TU = getCursorASTUnit(C);
5995 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5996 return TU->mapRangeFromPreamble(Range);
5997 }
5998
5999 if (C.kind == CXCursor_TranslationUnit) {
6000 ASTUnit *TU = getCursorASTUnit(C);
6001 FileID MainID = TU->getSourceManager().getMainFileID();
6002 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
6003 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
6004 return SourceRange(Start, End);
6005 }
6006
6007 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006008 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006009 if (!D)
6010 return SourceRange();
6011
6012 SourceRange R = D->getSourceRange();
6013 // FIXME: Multiple variables declared in a single declaration
6014 // currently lack the information needed to correctly determine their
6015 // ranges when accounting for the type-specifier. We use context
6016 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6017 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006018 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006019 if (!cxcursor::isFirstInDeclGroup(C))
6020 R.setBegin(VD->getLocation());
6021 }
6022 return R;
6023 }
6024 return SourceRange();
6025}
6026
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006027/// Retrieves the "raw" cursor extent, which is then extended to include
Guy Benyei11169dd2012-12-18 14:30:41 +00006028/// the decl-specifier-seq for declarations.
6029static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6030 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006031 const Decl *D = cxcursor::getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006032 if (!D)
6033 return SourceRange();
6034
6035 SourceRange R = D->getSourceRange();
6036
6037 // Adjust the start of the location for declarations preceded by
6038 // declaration specifiers.
6039 SourceLocation StartLoc;
6040 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6041 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006042 StartLoc = TI->getTypeLoc().getBeginLoc();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006043 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006044 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006045 StartLoc = TI->getTypeLoc().getBeginLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006046 }
6047
6048 if (StartLoc.isValid() && R.getBegin().isValid() &&
6049 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6050 R.setBegin(StartLoc);
6051
6052 // FIXME: Multiple variables declared in a single declaration
6053 // currently lack the information needed to correctly determine their
6054 // ranges when accounting for the type-specifier. We use context
6055 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6056 // and if so, whether it is the first decl.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006057 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006058 if (!cxcursor::isFirstInDeclGroup(C))
6059 R.setBegin(VD->getLocation());
6060 }
6061
6062 return R;
6063 }
6064
6065 return getRawCursorExtent(C);
6066}
6067
Guy Benyei11169dd2012-12-18 14:30:41 +00006068CXSourceRange clang_getCursorExtent(CXCursor C) {
6069 SourceRange R = getRawCursorExtent(C);
6070 if (R.isInvalid())
6071 return clang_getNullRange();
6072
6073 return cxloc::translateSourceRange(getCursorContext(C), R);
6074}
6075
6076CXCursor clang_getCursorReferenced(CXCursor C) {
6077 if (clang_isInvalid(C.kind))
6078 return clang_getNullCursor();
6079
6080 CXTranslationUnit tu = getCursorTU(C);
6081 if (clang_isDeclaration(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006082 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006083 if (!D)
6084 return clang_getNullCursor();
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006085 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006086 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006087 if (const ObjCPropertyImplDecl *PropImpl =
6088 dyn_cast<ObjCPropertyImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006089 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6090 return MakeCXCursor(Property, tu);
6091
6092 return C;
6093 }
6094
6095 if (clang_isExpression(C.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006096 const Expr *E = getCursorExpr(C);
6097 const Decl *D = getDeclFromExpr(E);
Guy Benyei11169dd2012-12-18 14:30:41 +00006098 if (D) {
6099 CXCursor declCursor = MakeCXCursor(D, tu);
6100 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6101 declCursor);
6102 return declCursor;
6103 }
6104
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006105 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
Guy Benyei11169dd2012-12-18 14:30:41 +00006106 return MakeCursorOverloadedDeclRef(Ovl, tu);
6107
6108 return clang_getNullCursor();
6109 }
6110
6111 if (clang_isStatement(C.kind)) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006112 const Stmt *S = getCursorStmt(C);
6113 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
Guy Benyei11169dd2012-12-18 14:30:41 +00006114 if (LabelDecl *label = Goto->getLabel())
6115 if (LabelStmt *labelS = label->getStmt())
6116 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6117
6118 return clang_getNullCursor();
6119 }
Richard Smith66a81862015-05-04 02:25:31 +00006120
Guy Benyei11169dd2012-12-18 14:30:41 +00006121 if (C.kind == CXCursor_MacroExpansion) {
Richard Smith66a81862015-05-04 02:25:31 +00006122 if (const MacroDefinitionRecord *Def =
6123 getCursorMacroExpansion(C).getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006124 return MakeMacroDefinitionCursor(Def, tu);
6125 }
6126
6127 if (!clang_isReference(C.kind))
6128 return clang_getNullCursor();
6129
6130 switch (C.kind) {
6131 case CXCursor_ObjCSuperClassRef:
6132 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6133
6134 case CXCursor_ObjCProtocolRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006135 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6136 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006137 return MakeCXCursor(Def, tu);
6138
6139 return MakeCXCursor(Prot, tu);
6140 }
6141
6142 case CXCursor_ObjCClassRef: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006143 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6144 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006145 return MakeCXCursor(Def, tu);
6146
6147 return MakeCXCursor(Class, tu);
6148 }
6149
6150 case CXCursor_TypeRef:
6151 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6152
6153 case CXCursor_TemplateRef:
6154 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6155
6156 case CXCursor_NamespaceRef:
6157 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6158
6159 case CXCursor_MemberRef:
6160 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6161
6162 case CXCursor_CXXBaseSpecifier: {
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00006163 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006164 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6165 tu ));
6166 }
6167
6168 case CXCursor_LabelRef:
6169 // FIXME: We end up faking the "parent" declaration here because we
6170 // don't want to make CXCursor larger.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006171 return MakeCXCursor(getCursorLabelRef(C).first,
6172 cxtu::getASTUnit(tu)->getASTContext()
6173 .getTranslationUnitDecl(),
Guy Benyei11169dd2012-12-18 14:30:41 +00006174 tu);
6175
6176 case CXCursor_OverloadedDeclRef:
6177 return C;
6178
6179 case CXCursor_VariableRef:
6180 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6181
6182 default:
6183 // We would prefer to enumerate all non-reference cursor kinds here.
6184 llvm_unreachable("Unhandled reference cursor kind");
6185 }
6186}
6187
6188CXCursor clang_getCursorDefinition(CXCursor C) {
6189 if (clang_isInvalid(C.kind))
6190 return clang_getNullCursor();
6191
6192 CXTranslationUnit TU = getCursorTU(C);
6193
6194 bool WasReference = false;
6195 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6196 C = clang_getCursorReferenced(C);
6197 WasReference = true;
6198 }
6199
6200 if (C.kind == CXCursor_MacroExpansion)
6201 return clang_getCursorReferenced(C);
6202
6203 if (!clang_isDeclaration(C.kind))
6204 return clang_getNullCursor();
6205
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006206 const Decl *D = getCursorDecl(C);
Guy Benyei11169dd2012-12-18 14:30:41 +00006207 if (!D)
6208 return clang_getNullCursor();
6209
6210 switch (D->getKind()) {
6211 // Declaration kinds that don't really separate the notions of
6212 // declaration and definition.
6213 case Decl::Namespace:
6214 case Decl::Typedef:
6215 case Decl::TypeAlias:
6216 case Decl::TypeAliasTemplate:
6217 case Decl::TemplateTypeParm:
6218 case Decl::EnumConstant:
6219 case Decl::Field:
Richard Smithbdb84f32016-07-22 23:36:59 +00006220 case Decl::Binding:
John McCall5e77d762013-04-16 07:28:30 +00006221 case Decl::MSProperty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006222 case Decl::IndirectField:
6223 case Decl::ObjCIvar:
6224 case Decl::ObjCAtDefsField:
6225 case Decl::ImplicitParam:
6226 case Decl::ParmVar:
6227 case Decl::NonTypeTemplateParm:
6228 case Decl::TemplateTemplateParm:
6229 case Decl::ObjCCategoryImpl:
6230 case Decl::ObjCImplementation:
6231 case Decl::AccessSpec:
6232 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00006233 case Decl::Export:
Guy Benyei11169dd2012-12-18 14:30:41 +00006234 case Decl::ObjCPropertyImpl:
6235 case Decl::FileScopeAsm:
6236 case Decl::StaticAssert:
6237 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00006238 case Decl::Captured:
Alexey Bataev4244be22016-02-11 05:35:55 +00006239 case Decl::OMPCapturedExpr:
Guy Benyei11169dd2012-12-18 14:30:41 +00006240 case Decl::Label: // FIXME: Is this right??
6241 case Decl::ClassScopeFunctionSpecialization:
Richard Smithbc491202017-02-17 20:05:37 +00006242 case Decl::CXXDeductionGuide:
Guy Benyei11169dd2012-12-18 14:30:41 +00006243 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +00006244 case Decl::OMPThreadPrivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00006245 case Decl::OMPAllocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00006246 case Decl::OMPDeclareReduction:
Michael Kruse251e1482019-02-01 20:25:04 +00006247 case Decl::OMPDeclareMapper:
Kelvin Li1408f912018-09-26 04:28:39 +00006248 case Decl::OMPRequires:
Douglas Gregor85f3f952015-07-07 03:57:15 +00006249 case Decl::ObjCTypeParam:
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006250 case Decl::BuiltinTemplate:
Nico Weber66220292016-03-02 17:28:48 +00006251 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +00006252 case Decl::PragmaDetectMismatch:
Richard Smith151c4562016-12-20 21:35:28 +00006253 case Decl::UsingPack:
Guy Benyei11169dd2012-12-18 14:30:41 +00006254 return C;
6255
6256 // Declaration kinds that don't make any sense here, but are
6257 // nonetheless harmless.
David Blaikief005d3c2013-02-22 17:44:58 +00006258 case Decl::Empty:
Guy Benyei11169dd2012-12-18 14:30:41 +00006259 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00006260 case Decl::ExternCContext:
Guy Benyei11169dd2012-12-18 14:30:41 +00006261 break;
6262
6263 // Declaration kinds for which the definition is not resolvable.
6264 case Decl::UnresolvedUsingTypename:
6265 case Decl::UnresolvedUsingValue:
6266 break;
6267
6268 case Decl::UsingDirective:
6269 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6270 TU);
6271
6272 case Decl::NamespaceAlias:
6273 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6274
6275 case Decl::Enum:
6276 case Decl::Record:
6277 case Decl::CXXRecord:
6278 case Decl::ClassTemplateSpecialization:
6279 case Decl::ClassTemplatePartialSpecialization:
6280 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6281 return MakeCXCursor(Def, TU);
6282 return clang_getNullCursor();
6283
6284 case Decl::Function:
6285 case Decl::CXXMethod:
6286 case Decl::CXXConstructor:
6287 case Decl::CXXDestructor:
6288 case Decl::CXXConversion: {
Craig Topper69186e72014-06-08 08:38:04 +00006289 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006290 if (cast<FunctionDecl>(D)->getBody(Def))
Dmitri Gribenko9c256e32013-01-14 00:46:27 +00006291 return MakeCXCursor(Def, TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006292 return clang_getNullCursor();
6293 }
6294
Larisse Voufo39a1e502013-08-06 01:03:05 +00006295 case Decl::Var:
6296 case Decl::VarTemplateSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00006297 case Decl::VarTemplatePartialSpecialization:
6298 case Decl::Decomposition: {
Guy Benyei11169dd2012-12-18 14:30:41 +00006299 // Ask the variable if it has a definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006300 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006301 return MakeCXCursor(Def, TU);
6302 return clang_getNullCursor();
6303 }
6304
6305 case Decl::FunctionTemplate: {
Craig Topper69186e72014-06-08 08:38:04 +00006306 const FunctionDecl *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006307 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6308 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6309 return clang_getNullCursor();
6310 }
6311
6312 case Decl::ClassTemplate: {
6313 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6314 ->getDefinition())
6315 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6316 TU);
6317 return clang_getNullCursor();
6318 }
6319
Larisse Voufo39a1e502013-08-06 01:03:05 +00006320 case Decl::VarTemplate: {
6321 if (VarDecl *Def =
6322 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6323 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6324 return clang_getNullCursor();
6325 }
6326
Guy Benyei11169dd2012-12-18 14:30:41 +00006327 case Decl::Using:
6328 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6329 D->getLocation(), TU);
6330
6331 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +00006332 case Decl::ConstructorUsingShadow:
Guy Benyei11169dd2012-12-18 14:30:41 +00006333 return clang_getCursorDefinition(
6334 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6335 TU));
6336
6337 case Decl::ObjCMethod: {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006338 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006339 if (Method->isThisDeclarationADefinition())
6340 return C;
6341
6342 // Dig out the method definition in the associated
6343 // @implementation, if we have it.
6344 // FIXME: The ASTs should make finding the definition easier.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006345 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006346 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6347 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6348 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6349 Method->isInstanceMethod()))
6350 if (Def->isThisDeclarationADefinition())
6351 return MakeCXCursor(Def, TU);
6352
6353 return clang_getNullCursor();
6354 }
6355
6356 case Decl::ObjCCategory:
6357 if (ObjCCategoryImplDecl *Impl
6358 = cast<ObjCCategoryDecl>(D)->getImplementation())
6359 return MakeCXCursor(Impl, TU);
6360 return clang_getNullCursor();
6361
6362 case Decl::ObjCProtocol:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006363 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006364 return MakeCXCursor(Def, TU);
6365 return clang_getNullCursor();
6366
6367 case Decl::ObjCInterface: {
6368 // There are two notions of a "definition" for an Objective-C
6369 // class: the interface and its implementation. When we resolved a
6370 // reference to an Objective-C class, produce the @interface as
6371 // the definition; when we were provided with the interface,
6372 // produce the @implementation as the definition.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006373 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006374 if (WasReference) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006375 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006376 return MakeCXCursor(Def, TU);
6377 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6378 return MakeCXCursor(Impl, TU);
6379 return clang_getNullCursor();
6380 }
6381
6382 case Decl::ObjCProperty:
6383 // FIXME: We don't really know where to find the
6384 // ObjCPropertyImplDecls that implement this property.
6385 return clang_getNullCursor();
6386
6387 case Decl::ObjCCompatibleAlias:
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006388 if (const ObjCInterfaceDecl *Class
Guy Benyei11169dd2012-12-18 14:30:41 +00006389 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006390 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00006391 return MakeCXCursor(Def, TU);
6392
6393 return clang_getNullCursor();
6394
6395 case Decl::Friend:
6396 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6397 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6398 return clang_getNullCursor();
6399
6400 case Decl::FriendTemplate:
6401 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6402 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6403 return clang_getNullCursor();
6404 }
6405
6406 return clang_getNullCursor();
6407}
6408
6409unsigned clang_isCursorDefinition(CXCursor C) {
6410 if (!clang_isDeclaration(C.kind))
6411 return 0;
6412
6413 return clang_getCursorDefinition(C) == C;
6414}
6415
6416CXCursor clang_getCanonicalCursor(CXCursor C) {
6417 if (!clang_isDeclaration(C.kind))
6418 return C;
6419
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006420 if (const Decl *D = getCursorDecl(C)) {
6421 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006422 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6423 return MakeCXCursor(CatD, getCursorTU(C));
6424
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006425 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6426 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
Guy Benyei11169dd2012-12-18 14:30:41 +00006427 return MakeCXCursor(IFD, getCursorTU(C));
6428
6429 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6430 }
6431
6432 return C;
6433}
6434
6435int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6436 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6437}
6438
6439unsigned clang_getNumOverloadedDecls(CXCursor C) {
6440 if (C.kind != CXCursor_OverloadedDeclRef)
6441 return 0;
6442
6443 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006444 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006445 return E->getNumDecls();
6446
6447 if (OverloadedTemplateStorage *S
6448 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6449 return S->size();
6450
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006451 const Decl *D = Storage.get<const Decl *>();
6452 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00006453 return Using->shadow_size();
6454
6455 return 0;
6456}
6457
6458CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6459 if (cursor.kind != CXCursor_OverloadedDeclRef)
6460 return clang_getNullCursor();
6461
6462 if (index >= clang_getNumOverloadedDecls(cursor))
6463 return clang_getNullCursor();
6464
6465 CXTranslationUnit TU = getCursorTU(cursor);
6466 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006467 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
Guy Benyei11169dd2012-12-18 14:30:41 +00006468 return MakeCXCursor(E->decls_begin()[index], TU);
6469
6470 if (OverloadedTemplateStorage *S
6471 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6472 return MakeCXCursor(S->begin()[index], TU);
6473
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006474 const Decl *D = Storage.get<const Decl *>();
6475 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006476 // FIXME: This is, unfortunately, linear time.
6477 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6478 std::advance(Pos, index);
6479 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6480 }
6481
6482 return clang_getNullCursor();
6483}
6484
6485void clang_getDefinitionSpellingAndExtent(CXCursor C,
6486 const char **startBuf,
6487 const char **endBuf,
6488 unsigned *startLine,
6489 unsigned *startColumn,
6490 unsigned *endLine,
6491 unsigned *endColumn) {
6492 assert(getCursorDecl(C) && "CXCursor has null decl");
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00006493 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
Guy Benyei11169dd2012-12-18 14:30:41 +00006494 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6495
6496 SourceManager &SM = FD->getASTContext().getSourceManager();
6497 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6498 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6499 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6500 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6501 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6502 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6503}
6504
6505
6506CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6507 unsigned PieceIndex) {
6508 RefNamePieces Pieces;
6509
6510 switch (C.kind) {
6511 case CXCursor_MemberRefExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006512 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00006513 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6514 E->getQualifierLoc().getSourceRange());
6515 break;
6516
6517 case CXCursor_DeclRefExpr:
James Y Knight04ec5bf2015-12-24 02:59:37 +00006518 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6519 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6520 Pieces =
6521 buildPieces(NameFlags, false, E->getNameInfo(),
6522 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6523 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006524 break;
6525
6526 case CXCursor_CallExpr:
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006527 if (const CXXOperatorCallExpr *OCE =
Guy Benyei11169dd2012-12-18 14:30:41 +00006528 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006529 const Expr *Callee = OCE->getCallee();
6530 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006531 Callee = ICE->getSubExpr();
6532
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00006533 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
Guy Benyei11169dd2012-12-18 14:30:41 +00006534 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6535 DRE->getQualifierLoc().getSourceRange());
6536 }
6537 break;
6538
6539 default:
6540 break;
6541 }
6542
6543 if (Pieces.empty()) {
6544 if (PieceIndex == 0)
6545 return clang_getCursorExtent(C);
6546 } else if (PieceIndex < Pieces.size()) {
6547 SourceRange R = Pieces[PieceIndex];
6548 if (R.isValid())
6549 return cxloc::translateSourceRange(getCursorContext(C), R);
6550 }
6551
6552 return clang_getNullRange();
6553}
6554
6555void clang_enableStackTraces(void) {
Richard Smithdfed58a2016-06-09 00:53:41 +00006556 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6557 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
Guy Benyei11169dd2012-12-18 14:30:41 +00006558}
6559
6560void clang_executeOnThread(void (*fn)(void*), void *user_data,
6561 unsigned stack_size) {
6562 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6563}
6564
Guy Benyei11169dd2012-12-18 14:30:41 +00006565//===----------------------------------------------------------------------===//
6566// Token-based Operations.
6567//===----------------------------------------------------------------------===//
6568
6569/* CXToken layout:
6570 * int_data[0]: a CXTokenKind
6571 * int_data[1]: starting token location
6572 * int_data[2]: token length
6573 * int_data[3]: reserved
6574 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6575 * otherwise unused.
6576 */
Guy Benyei11169dd2012-12-18 14:30:41 +00006577CXTokenKind clang_getTokenKind(CXToken CXTok) {
6578 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6579}
6580
6581CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6582 switch (clang_getTokenKind(CXTok)) {
6583 case CXToken_Identifier:
6584 case CXToken_Keyword:
6585 // We know we have an IdentifierInfo*, so use that.
Dmitri Gribenko3c66b0b2013-02-02 00:02:12 +00006586 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
Guy Benyei11169dd2012-12-18 14:30:41 +00006587 ->getNameStart());
6588
6589 case CXToken_Literal: {
6590 // We have stashed the starting pointer in the ptr_data field. Use it.
6591 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006592 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006593 }
6594
6595 case CXToken_Punctuation:
6596 case CXToken_Comment:
6597 break;
6598 }
6599
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006600 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006601 LOG_BAD_TU(TU);
6602 return cxstring::createEmpty();
6603 }
6604
Guy Benyei11169dd2012-12-18 14:30:41 +00006605 // We have to find the starting buffer pointer the hard way, by
6606 // deconstructing the source location.
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006607 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006608 if (!CXXUnit)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006609 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006610
6611 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6612 std::pair<FileID, unsigned> LocInfo
6613 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6614 bool Invalid = false;
6615 StringRef Buffer
6616 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6617 if (Invalid)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00006618 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006619
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00006620 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006621}
6622
6623CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006624 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006625 LOG_BAD_TU(TU);
6626 return clang_getNullLocation();
6627 }
6628
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006629 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006630 if (!CXXUnit)
6631 return clang_getNullLocation();
6632
6633 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6634 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6635}
6636
6637CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006638 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006639 LOG_BAD_TU(TU);
6640 return clang_getNullRange();
6641 }
6642
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006643 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006644 if (!CXXUnit)
6645 return clang_getNullRange();
6646
6647 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6648 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6649}
6650
6651static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6652 SmallVectorImpl<CXToken> &CXTokens) {
6653 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6654 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006655 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006656 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00006657 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00006658
6659 // Cannot tokenize across files.
6660 if (BeginLocInfo.first != EndLocInfo.first)
6661 return;
6662
6663 // Create a lexer
6664 bool Invalid = false;
6665 StringRef Buffer
6666 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6667 if (Invalid)
6668 return;
6669
6670 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6671 CXXUnit->getASTContext().getLangOpts(),
6672 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6673 Lex.SetCommentRetentionState(true);
6674
6675 // Lex tokens until we hit the end of the range.
6676 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6677 Token Tok;
6678 bool previousWasAt = false;
6679 do {
6680 // Lex the next token
6681 Lex.LexFromRawLexer(Tok);
6682 if (Tok.is(tok::eof))
6683 break;
6684
6685 // Initialize the CXToken.
6686 CXToken CXTok;
6687
6688 // - Common fields
6689 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6690 CXTok.int_data[2] = Tok.getLength();
6691 CXTok.int_data[3] = 0;
6692
6693 // - Kind-specific fields
6694 if (Tok.isLiteral()) {
6695 CXTok.int_data[0] = CXToken_Literal;
Dmitri Gribenkof9304482013-01-23 15:56:07 +00006696 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
Guy Benyei11169dd2012-12-18 14:30:41 +00006697 } else if (Tok.is(tok::raw_identifier)) {
6698 // Lookup the identifier to determine whether we have a keyword.
6699 IdentifierInfo *II
6700 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6701
6702 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6703 CXTok.int_data[0] = CXToken_Keyword;
6704 }
6705 else {
6706 CXTok.int_data[0] = Tok.is(tok::identifier)
6707 ? CXToken_Identifier
6708 : CXToken_Keyword;
6709 }
6710 CXTok.ptr_data = II;
6711 } else if (Tok.is(tok::comment)) {
6712 CXTok.int_data[0] = CXToken_Comment;
Craig Topper69186e72014-06-08 08:38:04 +00006713 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006714 } else {
6715 CXTok.int_data[0] = CXToken_Punctuation;
Craig Topper69186e72014-06-08 08:38:04 +00006716 CXTok.ptr_data = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006717 }
6718 CXTokens.push_back(CXTok);
6719 previousWasAt = Tok.is(tok::at);
Argyrios Kyrtzidisc7c6a072016-11-09 23:58:39 +00006720 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
Guy Benyei11169dd2012-12-18 14:30:41 +00006721}
6722
Ivan Donchevskii3957e482018-06-13 12:37:08 +00006723CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6724 LOG_FUNC_SECTION {
6725 *Log << TU << ' ' << Location;
6726 }
6727
6728 if (isNotUsableTU(TU)) {
6729 LOG_BAD_TU(TU);
6730 return NULL;
6731 }
6732
6733 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6734 if (!CXXUnit)
6735 return NULL;
6736
6737 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6738 if (Begin.isInvalid())
6739 return NULL;
6740 SourceManager &SM = CXXUnit->getSourceManager();
6741 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6742 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6743
6744 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6745
6746 SmallVector<CXToken, 32> CXTokens;
6747 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6748
6749 if (CXTokens.empty())
6750 return NULL;
6751
6752 CXTokens.resize(1);
6753 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6754
6755 memmove(Token, CXTokens.data(), sizeof(CXToken));
6756 return Token;
6757}
6758
Guy Benyei11169dd2012-12-18 14:30:41 +00006759void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6760 CXToken **Tokens, unsigned *NumTokens) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00006761 LOG_FUNC_SECTION {
6762 *Log << TU << ' ' << Range;
6763 }
6764
Guy Benyei11169dd2012-12-18 14:30:41 +00006765 if (Tokens)
Craig Topper69186e72014-06-08 08:38:04 +00006766 *Tokens = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006767 if (NumTokens)
6768 *NumTokens = 0;
6769
Dmitri Gribenko852d6222014-02-11 15:02:48 +00006770 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006771 LOG_BAD_TU(TU);
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006772 return;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00006773 }
Argyrios Kyrtzidis0e95fca2013-04-04 22:40:59 +00006774
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006775 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00006776 if (!CXXUnit || !Tokens || !NumTokens)
6777 return;
6778
6779 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6780
6781 SourceRange R = cxloc::translateCXSourceRange(Range);
6782 if (R.isInvalid())
6783 return;
6784
6785 SmallVector<CXToken, 32> CXTokens;
6786 getTokens(CXXUnit, R, CXTokens);
6787
6788 if (CXTokens.empty())
6789 return;
6790
Serge Pavlov52525732018-02-21 02:02:39 +00006791 *Tokens = static_cast<CXToken *>(
6792 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006793 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6794 *NumTokens = CXTokens.size();
6795}
6796
6797void clang_disposeTokens(CXTranslationUnit TU,
6798 CXToken *Tokens, unsigned NumTokens) {
6799 free(Tokens);
6800}
6801
Guy Benyei11169dd2012-12-18 14:30:41 +00006802//===----------------------------------------------------------------------===//
6803// Token annotation APIs.
6804//===----------------------------------------------------------------------===//
6805
Guy Benyei11169dd2012-12-18 14:30:41 +00006806static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6807 CXCursor parent,
6808 CXClientData client_data);
6809static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6810 CXClientData client_data);
6811
6812namespace {
6813class AnnotateTokensWorker {
Guy Benyei11169dd2012-12-18 14:30:41 +00006814 CXToken *Tokens;
6815 CXCursor *Cursors;
6816 unsigned NumTokens;
6817 unsigned TokIdx;
6818 unsigned PreprocessingTokIdx;
6819 CursorVisitor AnnotateVis;
6820 SourceManager &SrcMgr;
6821 bool HasContextSensitiveKeywords;
6822
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006823 struct PostChildrenAction {
6824 CXCursor cursor;
6825 enum Action { Invalid, Ignore, Postpone } action;
6826 };
6827 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
6828
Guy Benyei11169dd2012-12-18 14:30:41 +00006829 struct PostChildrenInfo {
6830 CXCursor Cursor;
6831 SourceRange CursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006832 unsigned BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00006833 unsigned BeforeChildrenTokenIdx;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006834 PostChildrenActions ChildActions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006835 };
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006836 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006837
6838 CXToken &getTok(unsigned Idx) {
6839 assert(Idx < NumTokens);
6840 return Tokens[Idx];
6841 }
6842 const CXToken &getTok(unsigned Idx) const {
6843 assert(Idx < NumTokens);
6844 return Tokens[Idx];
6845 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006846 bool MoreTokens() const { return TokIdx < NumTokens; }
6847 unsigned NextToken() const { return TokIdx; }
6848 void AdvanceToken() { ++TokIdx; }
6849 SourceLocation GetTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006850 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006851 }
6852 bool isFunctionMacroToken(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006853 return getTok(tokI).int_data[3] != 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00006854 }
6855 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00006856 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006857 }
6858
6859 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006860 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
Guy Benyei11169dd2012-12-18 14:30:41 +00006861 SourceRange);
6862
6863public:
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006864 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006865 CXTranslationUnit TU, SourceRange RegionOfInterest)
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006866 : Tokens(tokens), Cursors(cursors),
Guy Benyei11169dd2012-12-18 14:30:41 +00006867 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006868 AnnotateVis(TU,
Guy Benyei11169dd2012-12-18 14:30:41 +00006869 AnnotateTokensVisitor, this,
6870 /*VisitPreprocessorLast=*/true,
6871 /*VisitIncludedEntities=*/false,
6872 RegionOfInterest,
6873 /*VisitDeclsOnly=*/false,
6874 AnnotateTokensPostChildrenVisitor),
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00006875 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
Guy Benyei11169dd2012-12-18 14:30:41 +00006876 HasContextSensitiveKeywords(false) { }
6877
6878 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6879 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006880 bool IsIgnoredChildCursor(CXCursor cursor) const;
6881 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
6882
Guy Benyei11169dd2012-12-18 14:30:41 +00006883 bool postVisitChildren(CXCursor cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006884 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
6885 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
6886
Guy Benyei11169dd2012-12-18 14:30:41 +00006887 void AnnotateTokens();
6888
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006889 /// Determine whether the annotator saw any cursors that have
Guy Benyei11169dd2012-12-18 14:30:41 +00006890 /// context-sensitive keywords.
6891 bool hasContextSensitiveKeywords() const {
6892 return HasContextSensitiveKeywords;
6893 }
6894
6895 ~AnnotateTokensWorker() {
6896 assert(PostChildrenInfos.empty());
6897 }
6898};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006899}
Guy Benyei11169dd2012-12-18 14:30:41 +00006900
6901void AnnotateTokensWorker::AnnotateTokens() {
6902 // Walk the AST within the region of interest, annotating tokens
6903 // along the way.
6904 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006905}
Guy Benyei11169dd2012-12-18 14:30:41 +00006906
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006907bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
6908 if (PostChildrenInfos.empty())
6909 return false;
6910
6911 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
6912 if (ChildAction.cursor == cursor &&
6913 ChildAction.action == PostChildrenAction::Ignore) {
6914 return true;
6915 }
6916 }
6917
6918 return false;
6919}
6920
6921const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
6922 if (!clang_isExpression(Cursor.kind))
6923 return nullptr;
6924
6925 const Expr *E = getCursorExpr(Cursor);
6926 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
6927 const OverloadedOperatorKind Kind = OCE->getOperator();
6928 if (Kind == OO_Call || Kind == OO_Subscript)
6929 return OCE;
6930 }
6931
6932 return nullptr;
6933}
6934
6935AnnotateTokensWorker::PostChildrenActions
6936AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
6937 PostChildrenActions actions;
6938
6939 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
6940 // visited before the arguments to the operator call. For the Call and
6941 // Subscript operator the range of this DeclRefExpr includes the whole call
6942 // expression, so that all tokens in that range would be mapped to the
6943 // operator function, including the tokens of the arguments. To avoid that,
6944 // ensure to visit this DeclRefExpr as last node.
6945 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
6946 const Expr *Callee = OCE->getCallee();
6947 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
6948 const Expr *SubExpr = ICE->getSubExpr();
6949 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
Fangrui Songcabb36d2018-11-20 08:00:00 +00006950 const Decl *parentDecl = getCursorDecl(Cursor);
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00006951 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
6952
6953 // Visit the DeclRefExpr as last.
6954 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
6955 actions.push_back({cxChild, PostChildrenAction::Postpone});
6956
6957 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
6958 // wide range as the DeclRefExpr. We can skip visiting this entirely.
6959 cxChild = MakeCXCursor(ICE, parentDecl, TU);
6960 actions.push_back({cxChild, PostChildrenAction::Ignore});
6961 }
6962 }
6963 }
6964
6965 return actions;
6966}
6967
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006968static inline void updateCursorAnnotation(CXCursor &Cursor,
6969 const CXCursor &updateC) {
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006970 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00006971 return;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006972 Cursor = updateC;
Guy Benyei11169dd2012-12-18 14:30:41 +00006973}
6974
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006975/// It annotates and advances tokens with a cursor until the comparison
Guy Benyei11169dd2012-12-18 14:30:41 +00006976//// between the cursor location and the source range is the same as
6977/// \arg compResult.
6978///
6979/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6980/// Pass RangeOverlap to annotate tokens inside a range.
6981void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6982 RangeComparisonResult compResult,
6983 SourceRange range) {
6984 while (MoreTokens()) {
6985 const unsigned I = NextToken();
6986 if (isFunctionMacroToken(I))
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00006987 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6988 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00006989
6990 SourceLocation TokLoc = GetTokenLoc(I);
6991 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00006992 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00006993 AdvanceToken();
6994 continue;
6995 }
6996 break;
6997 }
6998}
6999
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007000/// Special annotation handling for macro argument tokens.
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007001/// \returns true if it advanced beyond all macro tokens, false otherwise.
7002bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
Guy Benyei11169dd2012-12-18 14:30:41 +00007003 CXCursor updateC,
7004 RangeComparisonResult compResult,
7005 SourceRange range) {
7006 assert(MoreTokens());
7007 assert(isFunctionMacroToken(NextToken()) &&
7008 "Should be called only for macro arg tokens");
7009
7010 // This works differently than annotateAndAdvanceTokens; because expanded
7011 // macro arguments can have arbitrary translation-unit source order, we do not
7012 // advance the token index one by one until a token fails the range test.
7013 // We only advance once past all of the macro arg tokens if all of them
7014 // pass the range test. If one of them fails we keep the token index pointing
7015 // at the start of the macro arg tokens so that the failing token will be
7016 // annotated by a subsequent annotation try.
7017
7018 bool atLeastOneCompFail = false;
7019
7020 unsigned I = NextToken();
7021 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7022 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7023 if (TokLoc.isFileID())
7024 continue; // not macro arg token, it's parens or comma.
7025 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7026 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7027 Cursors[I] = updateC;
7028 } else
7029 atLeastOneCompFail = true;
7030 }
7031
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007032 if (atLeastOneCompFail)
7033 return false;
7034
7035 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7036 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00007037}
7038
7039enum CXChildVisitResult
7040AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007041 SourceRange cursorRange = getRawCursorExtent(cursor);
7042 if (cursorRange.isInvalid())
7043 return CXChildVisit_Recurse;
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007044
7045 if (IsIgnoredChildCursor(cursor))
7046 return CXChildVisit_Continue;
7047
Guy Benyei11169dd2012-12-18 14:30:41 +00007048 if (!HasContextSensitiveKeywords) {
7049 // Objective-C properties can have context-sensitive keywords.
7050 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007051 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007052 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7053 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7054 }
7055 // Objective-C methods can have context-sensitive keywords.
7056 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7057 cursor.kind == CXCursor_ObjCClassMethodDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007058 if (const ObjCMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007059 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7060 if (Method->getObjCDeclQualifier())
7061 HasContextSensitiveKeywords = true;
7062 else {
David Majnemer59f77922016-06-24 04:05:48 +00007063 for (const auto *P : Method->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +00007064 if (P->getObjCDeclQualifier()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007065 HasContextSensitiveKeywords = true;
7066 break;
7067 }
7068 }
7069 }
7070 }
7071 }
7072 // C++ methods can have context-sensitive keywords.
7073 else if (cursor.kind == CXCursor_CXXMethod) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007074 if (const CXXMethodDecl *Method
Guy Benyei11169dd2012-12-18 14:30:41 +00007075 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7076 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7077 HasContextSensitiveKeywords = true;
7078 }
7079 }
7080 // C++ classes can have context-sensitive keywords.
7081 else if (cursor.kind == CXCursor_StructDecl ||
7082 cursor.kind == CXCursor_ClassDecl ||
7083 cursor.kind == CXCursor_ClassTemplate ||
7084 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007085 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00007086 if (D->hasAttr<FinalAttr>())
7087 HasContextSensitiveKeywords = true;
7088 }
7089 }
Argyrios Kyrtzidis990b3862013-06-04 18:24:30 +00007090
7091 // Don't override a property annotation with its getter/setter method.
7092 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7093 parent.kind == CXCursor_ObjCPropertyDecl)
7094 return CXChildVisit_Continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007095
7096 if (clang_isPreprocessing(cursor.kind)) {
7097 // Items in the preprocessing record are kept separate from items in
7098 // declarations, so we keep a separate token index.
7099 unsigned SavedTokIdx = TokIdx;
7100 TokIdx = PreprocessingTokIdx;
7101
7102 // Skip tokens up until we catch up to the beginning of the preprocessing
7103 // entry.
7104 while (MoreTokens()) {
7105 const unsigned I = NextToken();
7106 SourceLocation TokLoc = GetTokenLoc(I);
7107 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7108 case RangeBefore:
7109 AdvanceToken();
7110 continue;
7111 case RangeAfter:
7112 case RangeOverlap:
7113 break;
7114 }
7115 break;
7116 }
7117
7118 // Look at all of the tokens within this range.
7119 while (MoreTokens()) {
7120 const unsigned I = NextToken();
7121 SourceLocation TokLoc = GetTokenLoc(I);
7122 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7123 case RangeBefore:
7124 llvm_unreachable("Infeasible");
7125 case RangeAfter:
7126 break;
7127 case RangeOverlap:
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007128 // For macro expansions, just note where the beginning of the macro
7129 // expansion occurs.
7130 if (cursor.kind == CXCursor_MacroExpansion) {
7131 if (TokLoc == cursorRange.getBegin())
7132 Cursors[I] = cursor;
7133 AdvanceToken();
7134 break;
7135 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007136 // We may have already annotated macro names inside macro definitions.
7137 if (Cursors[I].kind != CXCursor_MacroExpansion)
7138 Cursors[I] = cursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007139 AdvanceToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007140 continue;
7141 }
7142 break;
7143 }
7144
7145 // Save the preprocessing token index; restore the non-preprocessing
7146 // token index.
7147 PreprocessingTokIdx = TokIdx;
7148 TokIdx = SavedTokIdx;
7149 return CXChildVisit_Recurse;
7150 }
7151
7152 if (cursorRange.isInvalid())
7153 return CXChildVisit_Continue;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007154
7155 unsigned BeforeReachingCursorIdx = NextToken();
Guy Benyei11169dd2012-12-18 14:30:41 +00007156 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007157 const enum CXCursorKind K = clang_getCursorKind(parent);
7158 const CXCursor updateC =
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007159 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7160 // Attributes are annotated out-of-order, skip tokens until we reach it.
7161 clang_isAttribute(cursor.kind))
Guy Benyei11169dd2012-12-18 14:30:41 +00007162 ? clang_getNullCursor() : parent;
7163
7164 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7165
7166 // Avoid having the cursor of an expression "overwrite" the annotation of the
7167 // variable declaration that it belongs to.
7168 // This can happen for C++ constructor expressions whose range generally
7169 // include the variable declaration, e.g.:
7170 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007171 if (clang_isExpression(cursorK) && MoreTokens()) {
Dmitri Gribenkoe8354062013-01-26 15:29:08 +00007172 const Expr *E = getCursorExpr(cursor);
Fangrui Songcabb36d2018-11-20 08:00:00 +00007173 if (const Decl *D = getCursorDecl(cursor)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007174 const unsigned I = NextToken();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007175 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7176 E->getBeginLoc() == D->getLocation() &&
7177 E->getBeginLoc() == GetTokenLoc(I)) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007178 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei11169dd2012-12-18 14:30:41 +00007179 AdvanceToken();
7180 }
7181 }
7182 }
7183
7184 // Before recursing into the children keep some state that we are going
7185 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7186 // extra work after the child nodes are visited.
7187 // Note that we don't call VisitChildren here to avoid traversing statements
7188 // code-recursively which can blow the stack.
7189
7190 PostChildrenInfo Info;
7191 Info.Cursor = cursor;
7192 Info.CursorRange = cursorRange;
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007193 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007194 Info.BeforeChildrenTokenIdx = NextToken();
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007195 Info.ChildActions = DetermineChildActions(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007196 PostChildrenInfos.push_back(Info);
7197
7198 return CXChildVisit_Recurse;
7199}
7200
7201bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7202 if (PostChildrenInfos.empty())
7203 return false;
7204 const PostChildrenInfo &Info = PostChildrenInfos.back();
7205 if (!clang_equalCursors(Info.Cursor, cursor))
7206 return false;
7207
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007208 HandlePostPonedChildCursors(Info);
7209
Guy Benyei11169dd2012-12-18 14:30:41 +00007210 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7211 const unsigned AfterChildren = NextToken();
7212 SourceRange cursorRange = Info.CursorRange;
7213
7214 // Scan the tokens that are at the end of the cursor, but are not captured
7215 // but the child cursors.
7216 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7217
7218 // Scan the tokens that are at the beginning of the cursor, but are not
7219 // capture by the child cursors.
7220 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7221 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7222 break;
7223
7224 Cursors[I] = cursor;
7225 }
7226
Argyrios Kyrtzidisa2ed8132013-02-08 01:12:25 +00007227 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7228 // encountered the attribute cursor.
7229 if (clang_isAttribute(cursor.kind))
7230 TokIdx = Info.BeforeReachingCursorIdx;
7231
Guy Benyei11169dd2012-12-18 14:30:41 +00007232 PostChildrenInfos.pop_back();
7233 return false;
7234}
7235
Ivan Donchevskiib3ae2bc2018-08-23 09:48:11 +00007236void AnnotateTokensWorker::HandlePostPonedChildCursors(
7237 const PostChildrenInfo &Info) {
7238 for (const auto &ChildAction : Info.ChildActions) {
7239 if (ChildAction.action == PostChildrenAction::Postpone) {
7240 HandlePostPonedChildCursor(ChildAction.cursor,
7241 Info.BeforeChildrenTokenIdx);
7242 }
7243 }
7244}
7245
7246void AnnotateTokensWorker::HandlePostPonedChildCursor(
7247 CXCursor Cursor, unsigned StartTokenIndex) {
7248 const auto flags = CXNameRange_WantQualifier | CXNameRange_WantQualifier;
7249 unsigned I = StartTokenIndex;
7250
7251 // The bracket tokens of a Call or Subscript operator are mapped to
7252 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7253 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7254 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
7255 const CXSourceRange CXRefNameRange =
7256 clang_getCursorReferenceNameRange(Cursor, flags, RefNameRangeNr);
7257 if (clang_Range_isNull(CXRefNameRange))
7258 break; // All ranges handled.
7259
7260 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7261 while (I < NumTokens) {
7262 const SourceLocation TokenLocation = GetTokenLoc(I);
7263 if (!TokenLocation.isValid())
7264 break;
7265
7266 // Adapt the end range, because LocationCompare() reports
7267 // RangeOverlap even for the not-inclusive end location.
7268 const SourceLocation fixedEnd =
7269 RefNameRange.getEnd().getLocWithOffset(-1);
7270 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7271
7272 const RangeComparisonResult ComparisonResult =
7273 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7274
7275 if (ComparisonResult == RangeOverlap) {
7276 Cursors[I++] = Cursor;
7277 } else if (ComparisonResult == RangeBefore) {
7278 ++I; // Not relevant token, check next one.
7279 } else if (ComparisonResult == RangeAfter) {
7280 break; // All tokens updated for current range, check next.
7281 }
7282 }
7283 }
7284}
7285
Guy Benyei11169dd2012-12-18 14:30:41 +00007286static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7287 CXCursor parent,
7288 CXClientData client_data) {
7289 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7290}
7291
7292static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7293 CXClientData client_data) {
7294 return static_cast<AnnotateTokensWorker*>(client_data)->
7295 postVisitChildren(cursor);
7296}
7297
7298namespace {
7299
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007300/// Uses the macro expansions in the preprocessing record to find
Guy Benyei11169dd2012-12-18 14:30:41 +00007301/// and mark tokens that are macro arguments. This info is used by the
7302/// AnnotateTokensWorker.
7303class MarkMacroArgTokensVisitor {
7304 SourceManager &SM;
7305 CXToken *Tokens;
7306 unsigned NumTokens;
7307 unsigned CurIdx;
7308
7309public:
7310 MarkMacroArgTokensVisitor(SourceManager &SM,
7311 CXToken *tokens, unsigned numTokens)
7312 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7313
7314 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7315 if (cursor.kind != CXCursor_MacroExpansion)
7316 return CXChildVisit_Continue;
7317
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00007318 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00007319 if (macroRange.getBegin() == macroRange.getEnd())
7320 return CXChildVisit_Continue; // it's not a function macro.
7321
7322 for (; CurIdx < NumTokens; ++CurIdx) {
7323 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7324 macroRange.getBegin()))
7325 break;
7326 }
7327
7328 if (CurIdx == NumTokens)
7329 return CXChildVisit_Break;
7330
7331 for (; CurIdx < NumTokens; ++CurIdx) {
7332 SourceLocation tokLoc = getTokenLoc(CurIdx);
7333 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7334 break;
7335
7336 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7337 }
7338
7339 if (CurIdx == NumTokens)
7340 return CXChildVisit_Break;
7341
7342 return CXChildVisit_Continue;
7343 }
7344
7345private:
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007346 CXToken &getTok(unsigned Idx) {
7347 assert(Idx < NumTokens);
7348 return Tokens[Idx];
7349 }
7350 const CXToken &getTok(unsigned Idx) const {
7351 assert(Idx < NumTokens);
7352 return Tokens[Idx];
7353 }
7354
Guy Benyei11169dd2012-12-18 14:30:41 +00007355 SourceLocation getTokenLoc(unsigned tokI) {
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007356 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007357 }
7358
7359 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7360 // The third field is reserved and currently not used. Use it here
7361 // to mark macro arg expanded tokens with their expanded locations.
Argyrios Kyrtzidis50126f12013-11-27 05:50:55 +00007362 getTok(tokI).int_data[3] = loc.getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00007363 }
7364};
7365
7366} // end anonymous namespace
7367
7368static CXChildVisitResult
7369MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7370 CXClientData client_data) {
7371 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7372 parent);
7373}
7374
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007375/// Used by \c annotatePreprocessorTokens.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007376/// \returns true if lexing was finished, false otherwise.
7377static bool lexNext(Lexer &Lex, Token &Tok,
7378 unsigned &NextIdx, unsigned NumTokens) {
7379 if (NextIdx >= NumTokens)
7380 return true;
7381
7382 ++NextIdx;
7383 Lex.LexFromRawLexer(Tok);
Alexander Kornienko1a9f1842015-12-28 15:24:08 +00007384 return Tok.is(tok::eof);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007385}
7386
Guy Benyei11169dd2012-12-18 14:30:41 +00007387static void annotatePreprocessorTokens(CXTranslationUnit TU,
7388 SourceRange RegionOfInterest,
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007389 CXCursor *Cursors,
7390 CXToken *Tokens,
7391 unsigned NumTokens) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007392 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007393
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007394 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei11169dd2012-12-18 14:30:41 +00007395 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7396 std::pair<FileID, unsigned> BeginLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007397 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00007398 std::pair<FileID, unsigned> EndLocInfo
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007399 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
Guy Benyei11169dd2012-12-18 14:30:41 +00007400
7401 if (BeginLocInfo.first != EndLocInfo.first)
7402 return;
7403
7404 StringRef Buffer;
7405 bool Invalid = false;
7406 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7407 if (Buffer.empty() || Invalid)
7408 return;
7409
7410 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7411 CXXUnit->getASTContext().getLangOpts(),
7412 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7413 Buffer.end());
7414 Lex.SetCommentRetentionState(true);
7415
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007416 unsigned NextIdx = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00007417 // Lex tokens in raw mode until we hit the end of the range, to avoid
7418 // entering #includes or expanding macros.
7419 while (true) {
7420 Token Tok;
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007421 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7422 break;
7423 unsigned TokIdx = NextIdx-1;
7424 assert(Tok.getLocation() ==
7425 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007426
7427 reprocess:
7428 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007429 // We have found a preprocessing directive. Annotate the tokens
7430 // appropriately.
Guy Benyei11169dd2012-12-18 14:30:41 +00007431 //
7432 // FIXME: Some simple tests here could identify macro definitions and
7433 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007434
7435 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007436 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7437 break;
7438
Craig Topper69186e72014-06-08 08:38:04 +00007439 MacroInfo *MI = nullptr;
Alp Toker2d57cea2014-05-17 04:53:25 +00007440 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007441 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7442 break;
7443
7444 if (Tok.is(tok::raw_identifier)) {
Alp Toker2d57cea2014-05-17 04:53:25 +00007445 IdentifierInfo &II =
7446 PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007447 SourceLocation MappedTokLoc =
7448 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7449 MI = getMacroInfo(II, MappedTokLoc, TU);
7450 }
7451 }
7452
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007453 bool finished = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007454 do {
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007455 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7456 finished = true;
7457 break;
7458 }
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007459 // If we are in a macro definition, check if the token was ever a
7460 // macro name and annotate it if that's the case.
7461 if (MI) {
7462 SourceLocation SaveLoc = Tok.getLocation();
7463 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
Richard Smith66a81862015-05-04 02:25:31 +00007464 MacroDefinitionRecord *MacroDef =
7465 checkForMacroInMacroDefinition(MI, Tok, TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007466 Tok.setLocation(SaveLoc);
7467 if (MacroDef)
Richard Smith66a81862015-05-04 02:25:31 +00007468 Cursors[NextIdx - 1] =
7469 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007470 }
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007471 } while (!Tok.isAtStartOfLine());
7472
7473 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7474 assert(TokIdx <= LastIdx);
7475 SourceLocation EndLoc =
7476 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7477 CXCursor Cursor =
7478 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7479
7480 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis68d31ce2013-01-07 19:16:32 +00007481 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007482
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007483 if (finished)
7484 break;
7485 goto reprocess;
Guy Benyei11169dd2012-12-18 14:30:41 +00007486 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007487 }
7488}
7489
7490// This gets run a separate thread to avoid stack blowout.
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007491static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7492 CXToken *Tokens, unsigned NumTokens,
7493 CXCursor *Cursors) {
Dmitri Gribenko183436e2013-01-26 21:49:50 +00007494 CIndexer *CXXIdx = TU->CIdx;
Guy Benyei11169dd2012-12-18 14:30:41 +00007495 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7496 setThreadBackgroundPriority();
7497
7498 // Determine the region of interest, which contains all of the tokens.
7499 SourceRange RegionOfInterest;
7500 RegionOfInterest.setBegin(
7501 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7502 RegionOfInterest.setEnd(
7503 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7504 Tokens[NumTokens-1])));
7505
Guy Benyei11169dd2012-12-18 14:30:41 +00007506 // Relex the tokens within the source range to look for preprocessing
7507 // directives.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007508 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Argyrios Kyrtzidis5d47a9b2013-02-13 18:33:28 +00007509
7510 // If begin location points inside a macro argument, set it to the expansion
7511 // location so we can have the full context when annotating semantically.
7512 {
7513 SourceManager &SM = CXXUnit->getSourceManager();
7514 SourceLocation Loc =
7515 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7516 if (Loc.isMacroID())
7517 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7518 }
7519
Guy Benyei11169dd2012-12-18 14:30:41 +00007520 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7521 // Search and mark tokens that are macro argument expansions.
7522 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7523 Tokens, NumTokens);
7524 CursorVisitor MacroArgMarker(TU,
7525 MarkMacroArgTokensVisitorDelegate, &Visitor,
7526 /*VisitPreprocessorLast=*/true,
7527 /*VisitIncludedEntities=*/false,
7528 RegionOfInterest);
7529 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7530 }
7531
7532 // Annotate all of the source locations in the region of interest that map to
7533 // a specific cursor.
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00007534 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei11169dd2012-12-18 14:30:41 +00007535
7536 // FIXME: We use a ridiculous stack size here because the data-recursion
7537 // algorithm uses a large stack frame than the non-data recursive version,
7538 // and AnnotationTokensWorker currently transforms the data-recursion
7539 // algorithm back into a traditional recursion by explicitly calling
7540 // VisitChildren(). We will need to remove this explicit recursive call.
7541 W.AnnotateTokens();
7542
7543 // If we ran into any entities that involve context-sensitive keywords,
7544 // take another pass through the tokens to mark them as such.
7545 if (W.hasContextSensitiveKeywords()) {
7546 for (unsigned I = 0; I != NumTokens; ++I) {
7547 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7548 continue;
7549
7550 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7551 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007552 if (const ObjCPropertyDecl *Property
Guy Benyei11169dd2012-12-18 14:30:41 +00007553 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7554 if (Property->getPropertyAttributesAsWritten() != 0 &&
7555 llvm::StringSwitch<bool>(II->getName())
7556 .Case("readonly", true)
7557 .Case("assign", true)
7558 .Case("unsafe_unretained", true)
7559 .Case("readwrite", true)
7560 .Case("retain", true)
7561 .Case("copy", true)
7562 .Case("nonatomic", true)
7563 .Case("atomic", true)
7564 .Case("getter", true)
7565 .Case("setter", true)
7566 .Case("strong", true)
7567 .Case("weak", true)
Manman Ren04fd4d82016-05-31 23:22:04 +00007568 .Case("class", true)
Guy Benyei11169dd2012-12-18 14:30:41 +00007569 .Default(false))
7570 Tokens[I].int_data[0] = CXToken_Keyword;
7571 }
7572 continue;
7573 }
7574
7575 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7576 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7577 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7578 if (llvm::StringSwitch<bool>(II->getName())
7579 .Case("in", true)
7580 .Case("out", true)
7581 .Case("inout", true)
7582 .Case("oneway", true)
7583 .Case("bycopy", true)
7584 .Case("byref", true)
7585 .Default(false))
7586 Tokens[I].int_data[0] = CXToken_Keyword;
7587 continue;
7588 }
7589
7590 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7591 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7592 Tokens[I].int_data[0] = CXToken_Keyword;
7593 continue;
7594 }
7595 }
7596 }
7597}
7598
Guy Benyei11169dd2012-12-18 14:30:41 +00007599void clang_annotateTokens(CXTranslationUnit TU,
7600 CXToken *Tokens, unsigned NumTokens,
7601 CXCursor *Cursors) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00007602 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00007603 LOG_BAD_TU(TU);
7604 return;
7605 }
7606 if (NumTokens == 0 || !Tokens || !Cursors) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007607 LOG_FUNC_SECTION { *Log << "<null input>"; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007608 return;
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00007609 }
7610
7611 LOG_FUNC_SECTION {
7612 *Log << TU << ' ';
7613 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7614 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7615 *Log << clang_getRange(bloc, eloc);
7616 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007617
7618 // Any token we don't specifically annotate will have a NULL cursor.
7619 CXCursor C = clang_getNullCursor();
7620 for (unsigned I = 0; I != NumTokens; ++I)
7621 Cursors[I] = C;
7622
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00007623 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
Guy Benyei11169dd2012-12-18 14:30:41 +00007624 if (!CXXUnit)
7625 return;
7626
7627 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007628
7629 auto AnnotateTokensImpl = [=]() {
7630 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7631 };
Guy Benyei11169dd2012-12-18 14:30:41 +00007632 llvm::CrashRecoveryContext CRC;
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00007633 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007634 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7635 }
7636}
7637
Guy Benyei11169dd2012-12-18 14:30:41 +00007638//===----------------------------------------------------------------------===//
7639// Operations for querying linkage of a cursor.
7640//===----------------------------------------------------------------------===//
7641
Guy Benyei11169dd2012-12-18 14:30:41 +00007642CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7643 if (!clang_isDeclaration(cursor.kind))
7644 return CXLinkage_Invalid;
7645
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007646 const Decl *D = cxcursor::getCursorDecl(cursor);
7647 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
Rafael Espindola3ae00052013-05-13 00:12:11 +00007648 switch (ND->getLinkageInternal()) {
Rafael Espindola50df3a02013-05-25 17:16:20 +00007649 case NoLinkage:
7650 case VisibleNoLinkage: return CXLinkage_NoLinkage;
Richard Smithaf10ea22017-07-08 00:37:59 +00007651 case ModuleInternalLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007652 case InternalLinkage: return CXLinkage_Internal;
7653 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
Richard Smithaf10ea22017-07-08 00:37:59 +00007654 case ModuleLinkage:
Guy Benyei11169dd2012-12-18 14:30:41 +00007655 case ExternalLinkage: return CXLinkage_External;
7656 };
7657
7658 return CXLinkage_Invalid;
7659}
Guy Benyei11169dd2012-12-18 14:30:41 +00007660
7661//===----------------------------------------------------------------------===//
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007662// Operations for querying visibility of a cursor.
7663//===----------------------------------------------------------------------===//
7664
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007665CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7666 if (!clang_isDeclaration(cursor.kind))
7667 return CXVisibility_Invalid;
7668
7669 const Decl *D = cxcursor::getCursorDecl(cursor);
7670 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7671 switch (ND->getVisibility()) {
7672 case HiddenVisibility: return CXVisibility_Hidden;
7673 case ProtectedVisibility: return CXVisibility_Protected;
7674 case DefaultVisibility: return CXVisibility_Default;
7675 };
7676
7677 return CXVisibility_Invalid;
7678}
Ehsan Akhgarib743de72016-05-31 15:55:51 +00007679
7680//===----------------------------------------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00007681// Operations for querying language of a cursor.
7682//===----------------------------------------------------------------------===//
7683
7684static CXLanguageKind getDeclLanguage(const Decl *D) {
7685 if (!D)
7686 return CXLanguage_C;
7687
7688 switch (D->getKind()) {
7689 default:
7690 break;
7691 case Decl::ImplicitParam:
7692 case Decl::ObjCAtDefsField:
7693 case Decl::ObjCCategory:
7694 case Decl::ObjCCategoryImpl:
7695 case Decl::ObjCCompatibleAlias:
7696 case Decl::ObjCImplementation:
7697 case Decl::ObjCInterface:
7698 case Decl::ObjCIvar:
7699 case Decl::ObjCMethod:
7700 case Decl::ObjCProperty:
7701 case Decl::ObjCPropertyImpl:
7702 case Decl::ObjCProtocol:
Douglas Gregor85f3f952015-07-07 03:57:15 +00007703 case Decl::ObjCTypeParam:
Guy Benyei11169dd2012-12-18 14:30:41 +00007704 return CXLanguage_ObjC;
7705 case Decl::CXXConstructor:
7706 case Decl::CXXConversion:
7707 case Decl::CXXDestructor:
7708 case Decl::CXXMethod:
7709 case Decl::CXXRecord:
7710 case Decl::ClassTemplate:
7711 case Decl::ClassTemplatePartialSpecialization:
7712 case Decl::ClassTemplateSpecialization:
7713 case Decl::Friend:
7714 case Decl::FriendTemplate:
7715 case Decl::FunctionTemplate:
7716 case Decl::LinkageSpec:
7717 case Decl::Namespace:
7718 case Decl::NamespaceAlias:
7719 case Decl::NonTypeTemplateParm:
7720 case Decl::StaticAssert:
7721 case Decl::TemplateTemplateParm:
7722 case Decl::TemplateTypeParm:
7723 case Decl::UnresolvedUsingTypename:
7724 case Decl::UnresolvedUsingValue:
7725 case Decl::Using:
7726 case Decl::UsingDirective:
7727 case Decl::UsingShadow:
7728 return CXLanguage_CPlusPlus;
7729 }
7730
7731 return CXLanguage_C;
7732}
7733
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007734static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7735 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
Manuel Klimek8e3a7ed2015-09-25 17:53:16 +00007736 return CXAvailability_NotAvailable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007737
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007738 switch (D->getAvailability()) {
7739 case AR_Available:
7740 case AR_NotYetIntroduced:
7741 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
Benjamin Kramer656363d2013-10-15 18:53:18 +00007742 return getCursorAvailabilityForDecl(
7743 cast<Decl>(EnumConst->getDeclContext()));
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007744 return CXAvailability_Available;
7745
7746 case AR_Deprecated:
7747 return CXAvailability_Deprecated;
7748
7749 case AR_Unavailable:
7750 return CXAvailability_NotAvailable;
7751 }
Benjamin Kramer656363d2013-10-15 18:53:18 +00007752
7753 llvm_unreachable("Unknown availability kind!");
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007754}
7755
Guy Benyei11169dd2012-12-18 14:30:41 +00007756enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7757 if (clang_isDeclaration(cursor.kind))
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007758 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7759 return getCursorAvailabilityForDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00007760
7761 return CXAvailability_Available;
7762}
7763
7764static CXVersion convertVersion(VersionTuple In) {
7765 CXVersion Out = { -1, -1, -1 };
7766 if (In.empty())
7767 return Out;
7768
7769 Out.Major = In.getMajor();
7770
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007771 Optional<unsigned> Minor = In.getMinor();
7772 if (Minor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007773 Out.Minor = *Minor;
7774 else
7775 return Out;
7776
NAKAMURA Takumic2b5d1f2013-02-21 02:32:34 +00007777 Optional<unsigned> Subminor = In.getSubminor();
7778 if (Subminor.hasValue())
Guy Benyei11169dd2012-12-18 14:30:41 +00007779 Out.Subminor = *Subminor;
7780
7781 return Out;
7782}
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007783
Alex Lorenz1345ea22017-06-12 19:06:30 +00007784static void getCursorPlatformAvailabilityForDecl(
7785 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7786 int *always_unavailable, CXString *unavailable_message,
7787 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007788 bool HadAvailAttr = false;
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007789 for (auto A : D->attrs()) {
7790 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007791 HadAvailAttr = true;
7792 if (always_deprecated)
7793 *always_deprecated = 1;
Nico Weberaacf0312014-04-24 05:16:45 +00007794 if (deprecated_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007795 clang_disposeString(*deprecated_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007796 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
Nico Weberaacf0312014-04-24 05:16:45 +00007797 }
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007798 continue;
7799 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007800
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007801 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007802 HadAvailAttr = true;
7803 if (always_unavailable)
7804 *always_unavailable = 1;
7805 if (unavailable_message) {
Argyrios Kyrtzidisedfe07f2014-04-24 06:05:40 +00007806 clang_disposeString(*unavailable_message);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007807 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7808 }
7809 continue;
7810 }
Alex Lorenz1345ea22017-06-12 19:06:30 +00007811
Aaron Ballmanb97112e2014-03-08 22:19:01 +00007812 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
Alex Lorenz1345ea22017-06-12 19:06:30 +00007813 AvailabilityAttrs.push_back(Avail);
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007814 HadAvailAttr = true;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007815 }
7816 }
7817
7818 if (!HadAvailAttr)
7819 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7820 return getCursorPlatformAvailabilityForDecl(
Alex Lorenz1345ea22017-06-12 19:06:30 +00007821 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7822 deprecated_message, always_unavailable, unavailable_message,
7823 AvailabilityAttrs);
7824
7825 if (AvailabilityAttrs.empty())
7826 return;
7827
Fangrui Song55fab262018-09-26 22:16:28 +00007828 llvm::sort(AvailabilityAttrs,
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00007829 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7830 return LHS->getPlatform()->getName() <
7831 RHS->getPlatform()->getName();
Fangrui Song55fab262018-09-26 22:16:28 +00007832 });
Alex Lorenz1345ea22017-06-12 19:06:30 +00007833 ASTContext &Ctx = D->getASTContext();
7834 auto It = std::unique(
7835 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7836 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7837 if (LHS->getPlatform() != RHS->getPlatform())
7838 return false;
7839
7840 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7841 LHS->getDeprecated() == RHS->getDeprecated() &&
7842 LHS->getObsoleted() == RHS->getObsoleted() &&
7843 LHS->getMessage() == RHS->getMessage() &&
7844 LHS->getReplacement() == RHS->getReplacement())
7845 return true;
7846
7847 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7848 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7849 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7850 return false;
7851
7852 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7853 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7854
7855 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7856 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7857 if (LHS->getMessage().empty())
7858 LHS->setMessage(Ctx, RHS->getMessage());
7859 if (LHS->getReplacement().empty())
7860 LHS->setReplacement(Ctx, RHS->getReplacement());
7861 }
7862
7863 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7864 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7865 if (LHS->getMessage().empty())
7866 LHS->setMessage(Ctx, RHS->getMessage());
7867 if (LHS->getReplacement().empty())
7868 LHS->setReplacement(Ctx, RHS->getReplacement());
7869 }
7870
7871 return true;
7872 });
7873 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007874}
7875
Alex Lorenz1345ea22017-06-12 19:06:30 +00007876int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
Guy Benyei11169dd2012-12-18 14:30:41 +00007877 CXString *deprecated_message,
7878 int *always_unavailable,
7879 CXString *unavailable_message,
7880 CXPlatformAvailability *availability,
7881 int availability_size) {
7882 if (always_deprecated)
7883 *always_deprecated = 0;
7884 if (deprecated_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007885 *deprecated_message = cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007886 if (always_unavailable)
7887 *always_unavailable = 0;
7888 if (unavailable_message)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00007889 *unavailable_message = cxstring::createEmpty();
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007890
Guy Benyei11169dd2012-12-18 14:30:41 +00007891 if (!clang_isDeclaration(cursor.kind))
7892 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007893
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007894 const Decl *D = cxcursor::getCursorDecl(cursor);
Guy Benyei11169dd2012-12-18 14:30:41 +00007895 if (!D)
7896 return 0;
Argyrios Kyrtzidisdc2973f2013-10-15 17:00:53 +00007897
Alex Lorenz1345ea22017-06-12 19:06:30 +00007898 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7899 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7900 always_unavailable, unavailable_message,
7901 AvailabilityAttrs);
7902 for (const auto &Avail :
7903 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7904 .take_front(availability_size))) {
7905 availability[Avail.index()].Platform =
7906 cxstring::createDup(Avail.value()->getPlatform()->getName());
7907 availability[Avail.index()].Introduced =
7908 convertVersion(Avail.value()->getIntroduced());
7909 availability[Avail.index()].Deprecated =
7910 convertVersion(Avail.value()->getDeprecated());
7911 availability[Avail.index()].Obsoleted =
7912 convertVersion(Avail.value()->getObsoleted());
7913 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7914 availability[Avail.index()].Message =
7915 cxstring::createDup(Avail.value()->getMessage());
7916 }
7917
7918 return AvailabilityAttrs.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00007919}
Alex Lorenz1345ea22017-06-12 19:06:30 +00007920
Guy Benyei11169dd2012-12-18 14:30:41 +00007921void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7922 clang_disposeString(availability->Platform);
7923 clang_disposeString(availability->Message);
7924}
7925
7926CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7927 if (clang_isDeclaration(cursor.kind))
7928 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7929
7930 return CXLanguage_Invalid;
7931}
7932
Saleem Abdulrasool50bc5652017-09-13 02:15:09 +00007933CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7934 const Decl *D = cxcursor::getCursorDecl(cursor);
7935 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7936 switch (VD->getTLSKind()) {
7937 case VarDecl::TLS_None:
7938 return CXTLS_None;
7939 case VarDecl::TLS_Dynamic:
7940 return CXTLS_Dynamic;
7941 case VarDecl::TLS_Static:
7942 return CXTLS_Static;
7943 }
7944 }
7945
7946 return CXTLS_None;
7947}
7948
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007949 /// If the given cursor is the "templated" declaration
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007950 /// describing a class or function template, return the class or
Guy Benyei11169dd2012-12-18 14:30:41 +00007951 /// function template.
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007952static const Decl *maybeGetTemplateCursor(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007953 if (!D)
Craig Topper69186e72014-06-08 08:38:04 +00007954 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007955
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007956 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007957 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7958 return FunTmpl;
7959
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00007960 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007961 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7962 return ClassTmpl;
7963
7964 return D;
7965}
7966
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007967
7968enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7969 StorageClass sc = SC_None;
7970 const Decl *D = getCursorDecl(C);
7971 if (D) {
7972 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7973 sc = FD->getStorageClass();
7974 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7975 sc = VD->getStorageClass();
7976 } else {
7977 return CX_SC_Invalid;
7978 }
7979 } else {
7980 return CX_SC_Invalid;
7981 }
7982 switch (sc) {
7983 case SC_None:
7984 return CX_SC_None;
7985 case SC_Extern:
7986 return CX_SC_Extern;
7987 case SC_Static:
7988 return CX_SC_Static;
7989 case SC_PrivateExtern:
7990 return CX_SC_PrivateExtern;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007991 case SC_Auto:
7992 return CX_SC_Auto;
7993 case SC_Register:
7994 return CX_SC_Register;
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007995 }
Kaelyn Takataab61e702014-10-15 18:03:26 +00007996 llvm_unreachable("Unhandled storage class!");
Argyrios Kyrtzidis4e0854f2014-10-15 17:05:31 +00007997}
7998
Guy Benyei11169dd2012-12-18 14:30:41 +00007999CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
8000 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008001 if (const Decl *D = getCursorDecl(cursor)) {
8002 const DeclContext *DC = D->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008003 if (!DC)
8004 return clang_getNullCursor();
8005
8006 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8007 getCursorTU(cursor));
8008 }
8009 }
8010
8011 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008012 if (const Decl *D = getCursorDecl(cursor))
Guy Benyei11169dd2012-12-18 14:30:41 +00008013 return MakeCXCursor(D, getCursorTU(cursor));
8014 }
8015
8016 return clang_getNullCursor();
8017}
8018
8019CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8020 if (clang_isDeclaration(cursor.kind)) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008021 if (const Decl *D = getCursorDecl(cursor)) {
8022 const DeclContext *DC = D->getLexicalDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008023 if (!DC)
8024 return clang_getNullCursor();
8025
8026 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8027 getCursorTU(cursor));
8028 }
8029 }
8030
8031 // FIXME: Note that we can't easily compute the lexical context of a
8032 // statement or expression, so we return nothing.
8033 return clang_getNullCursor();
8034}
8035
8036CXFile clang_getIncludedFile(CXCursor cursor) {
8037 if (cursor.kind != CXCursor_InclusionDirective)
Craig Topper69186e72014-06-08 08:38:04 +00008038 return nullptr;
8039
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008040 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
Dmitri Gribenkof9304482013-01-23 15:56:07 +00008041 return const_cast<FileEntry *>(ID->getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00008042}
8043
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008044unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8045 if (C.kind != CXCursor_ObjCPropertyDecl)
8046 return CXObjCPropertyAttr_noattr;
8047
8048 unsigned Result = CXObjCPropertyAttr_noattr;
8049 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8050 ObjCPropertyDecl::PropertyAttributeKind Attr =
8051 PD->getPropertyAttributesAsWritten();
8052
8053#define SET_CXOBJCPROP_ATTR(A) \
8054 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8055 Result |= CXObjCPropertyAttr_##A
8056 SET_CXOBJCPROP_ATTR(readonly);
8057 SET_CXOBJCPROP_ATTR(getter);
8058 SET_CXOBJCPROP_ATTR(assign);
8059 SET_CXOBJCPROP_ATTR(readwrite);
8060 SET_CXOBJCPROP_ATTR(retain);
8061 SET_CXOBJCPROP_ATTR(copy);
8062 SET_CXOBJCPROP_ATTR(nonatomic);
8063 SET_CXOBJCPROP_ATTR(setter);
8064 SET_CXOBJCPROP_ATTR(atomic);
8065 SET_CXOBJCPROP_ATTR(weak);
8066 SET_CXOBJCPROP_ATTR(strong);
8067 SET_CXOBJCPROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +00008068 SET_CXOBJCPROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +00008069#undef SET_CXOBJCPROP_ATTR
8070
8071 return Result;
8072}
8073
Michael Wu6e88f532018-08-03 05:38:29 +00008074CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8075 if (C.kind != CXCursor_ObjCPropertyDecl)
8076 return cxstring::createNull();
8077
8078 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8079 Selector sel = PD->getGetterName();
8080 if (sel.isNull())
8081 return cxstring::createNull();
8082
8083 return cxstring::createDup(sel.getAsString());
8084}
8085
8086CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8087 if (C.kind != CXCursor_ObjCPropertyDecl)
8088 return cxstring::createNull();
8089
8090 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8091 Selector sel = PD->getSetterName();
8092 if (sel.isNull())
8093 return cxstring::createNull();
8094
8095 return cxstring::createDup(sel.getAsString());
8096}
8097
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +00008098unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8099 if (!clang_isDeclaration(C.kind))
8100 return CXObjCDeclQualifier_None;
8101
8102 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8103 const Decl *D = getCursorDecl(C);
8104 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8105 QT = MD->getObjCDeclQualifier();
8106 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8107 QT = PD->getObjCDeclQualifier();
8108 if (QT == Decl::OBJC_TQ_None)
8109 return CXObjCDeclQualifier_None;
8110
8111 unsigned Result = CXObjCDeclQualifier_None;
8112 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
8113 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
8114 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
8115 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
8116 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
8117 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
8118
8119 return Result;
8120}
8121
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +00008122unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8123 if (!clang_isDeclaration(C.kind))
8124 return 0;
8125
8126 const Decl *D = getCursorDecl(C);
8127 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8128 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8129 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8130 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8131
8132 return 0;
8133}
8134
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +00008135unsigned clang_Cursor_isVariadic(CXCursor C) {
8136 if (!clang_isDeclaration(C.kind))
8137 return 0;
8138
8139 const Decl *D = getCursorDecl(C);
8140 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8141 return FD->isVariadic();
8142 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8143 return MD->isVariadic();
8144
8145 return 0;
8146}
8147
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008148unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8149 CXString *language, CXString *definedIn,
8150 unsigned *isGenerated) {
8151 if (!clang_isDeclaration(C.kind))
8152 return 0;
8153
8154 const Decl *D = getCursorDecl(C);
8155
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +00008156 if (auto *attr = D->getExternalSourceSymbolAttr()) {
Argyrios Kyrtzidis0381cc72017-05-10 15:10:36 +00008157 if (language)
8158 *language = cxstring::createDup(attr->getLanguage());
8159 if (definedIn)
8160 *definedIn = cxstring::createDup(attr->getDefinedIn());
8161 if (isGenerated)
8162 *isGenerated = attr->getGeneratedDeclaration();
8163 return 1;
8164 }
8165 return 0;
8166}
8167
Guy Benyei11169dd2012-12-18 14:30:41 +00008168CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8169 if (!clang_isDeclaration(C.kind))
8170 return clang_getNullRange();
8171
8172 const Decl *D = getCursorDecl(C);
8173 ASTContext &Context = getCursorContext(C);
8174 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8175 if (!RC)
8176 return clang_getNullRange();
8177
8178 return cxloc::translateSourceRange(Context, RC->getSourceRange());
8179}
8180
8181CXString clang_Cursor_getRawCommentText(CXCursor C) {
8182 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008183 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008184
8185 const Decl *D = getCursorDecl(C);
8186 ASTContext &Context = getCursorContext(C);
8187 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8188 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8189 StringRef();
8190
8191 // Don't duplicate the string because RawText points directly into source
8192 // code.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008193 return cxstring::createRef(RawText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008194}
8195
8196CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8197 if (!clang_isDeclaration(C.kind))
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008198 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008199
8200 const Decl *D = getCursorDecl(C);
8201 const ASTContext &Context = getCursorContext(C);
8202 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8203
8204 if (RC) {
8205 StringRef BriefText = RC->getBriefText(Context);
8206
8207 // Don't duplicate the string because RawComment ensures that this memory
8208 // will not go away.
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008209 return cxstring::createRef(BriefText);
Guy Benyei11169dd2012-12-18 14:30:41 +00008210 }
8211
Dmitri Gribenkof98dfba2013-02-01 14:13:32 +00008212 return cxstring::createNull();
Guy Benyei11169dd2012-12-18 14:30:41 +00008213}
8214
Guy Benyei11169dd2012-12-18 14:30:41 +00008215CXModule clang_Cursor_getModule(CXCursor C) {
8216 if (C.kind == CXCursor_ModuleImportDecl) {
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008217 if (const ImportDecl *ImportD =
8218 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
Guy Benyei11169dd2012-12-18 14:30:41 +00008219 return ImportD->getImportedModule();
8220 }
8221
Craig Topper69186e72014-06-08 08:38:04 +00008222 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008223}
8224
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008225CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8226 if (isNotUsableTU(TU)) {
8227 LOG_BAD_TU(TU);
8228 return nullptr;
8229 }
8230 if (!File)
8231 return nullptr;
8232 FileEntry *FE = static_cast<FileEntry *>(File);
8233
8234 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8235 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8236 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8237
Richard Smithfeb54b62014-10-23 02:01:19 +00008238 return Header.getModule();
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00008239}
8240
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008241CXFile clang_Module_getASTFile(CXModule CXMod) {
8242 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008243 return nullptr;
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00008244 Module *Mod = static_cast<Module*>(CXMod);
8245 return const_cast<FileEntry *>(Mod->getASTFile());
8246}
8247
Guy Benyei11169dd2012-12-18 14:30:41 +00008248CXModule clang_Module_getParent(CXModule CXMod) {
8249 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008250 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008251 Module *Mod = static_cast<Module*>(CXMod);
8252 return Mod->Parent;
8253}
8254
8255CXString clang_Module_getName(CXModule CXMod) {
8256 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008257 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008258 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008259 return cxstring::createDup(Mod->Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00008260}
8261
8262CXString clang_Module_getFullName(CXModule CXMod) {
8263 if (!CXMod)
Dmitri Gribenko36a6dd02013-02-01 14:21:22 +00008264 return cxstring::createEmpty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008265 Module *Mod = static_cast<Module*>(CXMod);
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008266 return cxstring::createDup(Mod->getFullModuleName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008267}
8268
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00008269int clang_Module_isSystem(CXModule CXMod) {
8270 if (!CXMod)
8271 return 0;
8272 Module *Mod = static_cast<Module*>(CXMod);
8273 return Mod->IsSystem;
8274}
8275
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008276unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8277 CXModule CXMod) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008278 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008279 LOG_BAD_TU(TU);
8280 return 0;
8281 }
8282 if (!CXMod)
Guy Benyei11169dd2012-12-18 14:30:41 +00008283 return 0;
8284 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008285 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8286 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8287 return TopHeaders.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00008288}
8289
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008290CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8291 CXModule CXMod, unsigned Index) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008292 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008293 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008294 return nullptr;
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008295 }
8296 if (!CXMod)
Craig Topper69186e72014-06-08 08:38:04 +00008297 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008298 Module *Mod = static_cast<Module*>(CXMod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008299 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
Guy Benyei11169dd2012-12-18 14:30:41 +00008300
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00008301 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8302 if (Index < TopHeaders.size())
8303 return const_cast<FileEntry *>(TopHeaders[Index]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008304
Craig Topper69186e72014-06-08 08:38:04 +00008305 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008306}
8307
Guy Benyei11169dd2012-12-18 14:30:41 +00008308//===----------------------------------------------------------------------===//
8309// C++ AST instrospection.
8310//===----------------------------------------------------------------------===//
8311
Jonathan Coe29565352016-04-27 12:48:25 +00008312unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8313 if (!clang_isDeclaration(C.kind))
8314 return 0;
8315
8316 const Decl *D = cxcursor::getCursorDecl(C);
8317 const CXXConstructorDecl *Constructor =
8318 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8319 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8320}
8321
8322unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8323 if (!clang_isDeclaration(C.kind))
8324 return 0;
8325
8326 const Decl *D = cxcursor::getCursorDecl(C);
8327 const CXXConstructorDecl *Constructor =
8328 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8329 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8330}
8331
8332unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8333 if (!clang_isDeclaration(C.kind))
8334 return 0;
8335
8336 const Decl *D = cxcursor::getCursorDecl(C);
8337 const CXXConstructorDecl *Constructor =
8338 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8339 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8340}
8341
8342unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8343 if (!clang_isDeclaration(C.kind))
8344 return 0;
8345
8346 const Decl *D = cxcursor::getCursorDecl(C);
8347 const CXXConstructorDecl *Constructor =
8348 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8349 // Passing 'false' excludes constructors marked 'explicit'.
8350 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8351}
8352
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +00008353unsigned clang_CXXField_isMutable(CXCursor C) {
8354 if (!clang_isDeclaration(C.kind))
8355 return 0;
8356
8357 if (const auto D = cxcursor::getCursorDecl(C))
8358 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8359 return FD->isMutable() ? 1 : 0;
8360 return 0;
8361}
8362
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008363unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8364 if (!clang_isDeclaration(C.kind))
8365 return 0;
8366
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008367 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008368 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008369 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Dmitri Gribenko62770be2013-05-17 18:38:35 +00008370 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8371}
8372
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008373unsigned clang_CXXMethod_isConst(CXCursor C) {
8374 if (!clang_isDeclaration(C.kind))
8375 return 0;
8376
8377 const Decl *D = cxcursor::getCursorDecl(C);
8378 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008379 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008380 return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0;
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +00008381}
8382
Jonathan Coe29565352016-04-27 12:48:25 +00008383unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8384 if (!clang_isDeclaration(C.kind))
8385 return 0;
8386
8387 const Decl *D = cxcursor::getCursorDecl(C);
8388 const CXXMethodDecl *Method =
8389 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8390 return (Method && Method->isDefaulted()) ? 1 : 0;
8391}
8392
Guy Benyei11169dd2012-12-18 14:30:41 +00008393unsigned clang_CXXMethod_isStatic(CXCursor C) {
8394 if (!clang_isDeclaration(C.kind))
8395 return 0;
8396
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008397 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008398 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008399 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008400 return (Method && Method->isStatic()) ? 1 : 0;
8401}
8402
8403unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8404 if (!clang_isDeclaration(C.kind))
8405 return 0;
8406
Dmitri Gribenkod15bb302013-01-23 17:25:27 +00008407 const Decl *D = cxcursor::getCursorDecl(C);
Alp Tokera2794f92014-01-22 07:29:52 +00008408 const CXXMethodDecl *Method =
Craig Topper69186e72014-06-08 08:38:04 +00008409 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008410 return (Method && Method->isVirtual()) ? 1 : 0;
8411}
Guy Benyei11169dd2012-12-18 14:30:41 +00008412
Alex Lorenz34ccadc2017-12-14 22:01:50 +00008413unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8414 if (!clang_isDeclaration(C.kind))
8415 return 0;
8416
8417 const auto *D = cxcursor::getCursorDecl(C);
8418 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8419 if (RD)
8420 RD = RD->getDefinition();
8421 return (RD && RD->isAbstract()) ? 1 : 0;
8422}
8423
Alex Lorenzff7f42e2017-07-12 11:35:11 +00008424unsigned clang_EnumDecl_isScoped(CXCursor C) {
8425 if (!clang_isDeclaration(C.kind))
8426 return 0;
8427
8428 const Decl *D = cxcursor::getCursorDecl(C);
8429 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8430 return (Enum && Enum->isScoped()) ? 1 : 0;
8431}
8432
Guy Benyei11169dd2012-12-18 14:30:41 +00008433//===----------------------------------------------------------------------===//
8434// Attribute introspection.
8435//===----------------------------------------------------------------------===//
8436
Guy Benyei11169dd2012-12-18 14:30:41 +00008437CXType clang_getIBOutletCollectionType(CXCursor C) {
8438 if (C.kind != CXCursor_IBOutletCollectionAttr)
8439 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8440
Dmitri Gribenkoe4baea62013-01-26 18:08:08 +00008441 const IBOutletCollectionAttr *A =
Guy Benyei11169dd2012-12-18 14:30:41 +00008442 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8443
8444 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8445}
Guy Benyei11169dd2012-12-18 14:30:41 +00008446
8447//===----------------------------------------------------------------------===//
8448// Inspecting memory usage.
8449//===----------------------------------------------------------------------===//
8450
8451typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8452
8453static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8454 enum CXTUResourceUsageKind k,
8455 unsigned long amount) {
8456 CXTUResourceUsageEntry entry = { k, amount };
8457 entries.push_back(entry);
8458}
8459
Guy Benyei11169dd2012-12-18 14:30:41 +00008460const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8461 const char *str = "";
8462 switch (kind) {
8463 case CXTUResourceUsage_AST:
8464 str = "ASTContext: expressions, declarations, and types";
8465 break;
8466 case CXTUResourceUsage_Identifiers:
8467 str = "ASTContext: identifiers";
8468 break;
8469 case CXTUResourceUsage_Selectors:
8470 str = "ASTContext: selectors";
8471 break;
8472 case CXTUResourceUsage_GlobalCompletionResults:
8473 str = "Code completion: cached global results";
8474 break;
8475 case CXTUResourceUsage_SourceManagerContentCache:
8476 str = "SourceManager: content cache allocator";
8477 break;
8478 case CXTUResourceUsage_AST_SideTables:
8479 str = "ASTContext: side tables";
8480 break;
8481 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8482 str = "SourceManager: malloc'ed memory buffers";
8483 break;
8484 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8485 str = "SourceManager: mmap'ed memory buffers";
8486 break;
8487 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8488 str = "ExternalASTSource: malloc'ed memory buffers";
8489 break;
8490 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8491 str = "ExternalASTSource: mmap'ed memory buffers";
8492 break;
8493 case CXTUResourceUsage_Preprocessor:
8494 str = "Preprocessor: malloc'ed memory";
8495 break;
8496 case CXTUResourceUsage_PreprocessingRecord:
8497 str = "Preprocessor: PreprocessingRecord";
8498 break;
8499 case CXTUResourceUsage_SourceManager_DataStructures:
8500 str = "SourceManager: data structures and tables";
8501 break;
8502 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8503 str = "Preprocessor: header search tables";
8504 break;
8505 }
8506 return str;
8507}
8508
8509CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008510 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008511 LOG_BAD_TU(TU);
Craig Topper69186e72014-06-08 08:38:04 +00008512 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
Guy Benyei11169dd2012-12-18 14:30:41 +00008513 return usage;
8514 }
8515
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008516 ASTUnit *astUnit = cxtu::getASTUnit(TU);
Ahmed Charlesb8984322014-03-07 20:03:18 +00008517 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
Guy Benyei11169dd2012-12-18 14:30:41 +00008518 ASTContext &astContext = astUnit->getASTContext();
8519
8520 // How much memory is used by AST nodes and types?
8521 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8522 (unsigned long) astContext.getASTAllocatedMemory());
8523
8524 // How much memory is used by identifiers?
8525 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8526 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8527
8528 // How much memory is used for selectors?
8529 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8530 (unsigned long) astContext.Selectors.getTotalMemory());
8531
8532 // How much memory is used by ASTContext's side tables?
8533 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8534 (unsigned long) astContext.getSideTableAllocatedMemory());
8535
8536 // How much memory is used for caching global code completion results?
8537 unsigned long completionBytes = 0;
8538 if (GlobalCodeCompletionAllocator *completionAllocator =
Alp Tokerf994cef2014-07-05 03:08:06 +00008539 astUnit->getCachedCompletionAllocator().get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008540 completionBytes = completionAllocator->getTotalMemory();
8541 }
8542 createCXTUResourceUsageEntry(*entries,
8543 CXTUResourceUsage_GlobalCompletionResults,
8544 completionBytes);
8545
8546 // How much memory is being used by SourceManager's content cache?
8547 createCXTUResourceUsageEntry(*entries,
8548 CXTUResourceUsage_SourceManagerContentCache,
8549 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8550
8551 // How much memory is being used by the MemoryBuffer's in SourceManager?
8552 const SourceManager::MemoryBufferSizes &srcBufs =
8553 astUnit->getSourceManager().getMemoryBufferSizes();
8554
8555 createCXTUResourceUsageEntry(*entries,
8556 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8557 (unsigned long) srcBufs.malloc_bytes);
8558 createCXTUResourceUsageEntry(*entries,
8559 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8560 (unsigned long) srcBufs.mmap_bytes);
8561 createCXTUResourceUsageEntry(*entries,
8562 CXTUResourceUsage_SourceManager_DataStructures,
8563 (unsigned long) astContext.getSourceManager()
8564 .getDataStructureSizes());
8565
8566 // How much memory is being used by the ExternalASTSource?
8567 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8568 const ExternalASTSource::MemoryBufferSizes &sizes =
8569 esrc->getMemoryBufferSizes();
8570
8571 createCXTUResourceUsageEntry(*entries,
8572 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8573 (unsigned long) sizes.malloc_bytes);
8574 createCXTUResourceUsageEntry(*entries,
8575 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8576 (unsigned long) sizes.mmap_bytes);
8577 }
8578
8579 // How much memory is being used by the Preprocessor?
8580 Preprocessor &pp = astUnit->getPreprocessor();
8581 createCXTUResourceUsageEntry(*entries,
8582 CXTUResourceUsage_Preprocessor,
8583 pp.getTotalMemory());
8584
8585 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8586 createCXTUResourceUsageEntry(*entries,
8587 CXTUResourceUsage_PreprocessingRecord,
8588 pRec->getTotalMemory());
8589 }
8590
8591 createCXTUResourceUsageEntry(*entries,
8592 CXTUResourceUsage_Preprocessor_HeaderSearch,
8593 pp.getHeaderSearchInfo().getTotalMemory());
Craig Topper69186e72014-06-08 08:38:04 +00008594
Guy Benyei11169dd2012-12-18 14:30:41 +00008595 CXTUResourceUsage usage = { (void*) entries.get(),
8596 (unsigned) entries->size(),
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00008597 !entries->empty() ? &(*entries)[0] : nullptr };
Eric Fiseliere95fc442016-11-14 07:03:50 +00008598 (void)entries.release();
Guy Benyei11169dd2012-12-18 14:30:41 +00008599 return usage;
8600}
8601
8602void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8603 if (usage.data)
8604 delete (MemUsageEntries*) usage.data;
8605}
8606
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008607CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8608 CXSourceRangeList *skipped = new CXSourceRangeList;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008609 skipped->count = 0;
Craig Topper69186e72014-06-08 08:38:04 +00008610 skipped->ranges = nullptr;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008611
Dmitri Gribenko852d6222014-02-11 15:02:48 +00008612 if (isNotUsableTU(TU)) {
Dmitri Gribenko256454f2014-02-11 14:34:14 +00008613 LOG_BAD_TU(TU);
8614 return skipped;
8615 }
8616
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008617 if (!file)
8618 return skipped;
8619
8620 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8621 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8622 if (!ppRec)
8623 return skipped;
8624
8625 ASTContext &Ctx = astUnit->getASTContext();
8626 SourceManager &sm = Ctx.getSourceManager();
8627 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8628 FileID wantedFileID = sm.translateFile(fileEntry);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008629 bool isMainFile = wantedFileID == sm.getMainFileID();
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008630
8631 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8632 std::vector<SourceRange> wantedRanges;
8633 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8634 i != ei; ++i) {
8635 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8636 wantedRanges.push_back(*i);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00008637 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8638 wantedRanges.push_back(*i);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008639 }
8640
8641 skipped->count = wantedRanges.size();
8642 skipped->ranges = new CXSourceRange[skipped->count];
8643 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8644 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8645
8646 return skipped;
8647}
8648
Cameron Desrochersd8091282016-08-18 15:43:55 +00008649CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8650 CXSourceRangeList *skipped = new CXSourceRangeList;
8651 skipped->count = 0;
8652 skipped->ranges = nullptr;
8653
8654 if (isNotUsableTU(TU)) {
8655 LOG_BAD_TU(TU);
8656 return skipped;
8657 }
8658
8659 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8660 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8661 if (!ppRec)
8662 return skipped;
8663
8664 ASTContext &Ctx = astUnit->getASTContext();
8665
8666 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8667
8668 skipped->count = SkippedRanges.size();
8669 skipped->ranges = new CXSourceRange[skipped->count];
8670 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8671 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8672
8673 return skipped;
8674}
8675
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00008676void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8677 if (ranges) {
8678 delete[] ranges->ranges;
8679 delete ranges;
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00008680 }
8681}
8682
Guy Benyei11169dd2012-12-18 14:30:41 +00008683void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8684 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8685 for (unsigned I = 0; I != Usage.numEntries; ++I)
8686 fprintf(stderr, " %s: %lu\n",
8687 clang_getTUResourceUsageName(Usage.entries[I].kind),
8688 Usage.entries[I].amount);
8689
8690 clang_disposeCXTUResourceUsage(Usage);
8691}
8692
8693//===----------------------------------------------------------------------===//
8694// Misc. utility functions.
8695//===----------------------------------------------------------------------===//
8696
Richard Smith0a7b2972018-07-03 21:34:13 +00008697/// Default to using our desired 8 MB stack size on "safety" threads.
8698static unsigned SafetyStackThreadSize = DesiredStackSize;
Guy Benyei11169dd2012-12-18 14:30:41 +00008699
8700namespace clang {
8701
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008702bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
Guy Benyei11169dd2012-12-18 14:30:41 +00008703 unsigned Size) {
8704 if (!Size)
8705 Size = GetSafetyThreadStackSize();
Erik Verbruggen3cc39112017-11-14 09:34:39 +00008706 if (Size && !getenv("LIBCLANG_NOTHREADS"))
Benjamin Kramer11a9cd92015-07-25 20:55:44 +00008707 return CRC.RunSafelyOnThread(Fn, Size);
8708 return CRC.RunSafely(Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00008709}
8710
8711unsigned GetSafetyThreadStackSize() {
8712 return SafetyStackThreadSize;
8713}
8714
8715void SetSafetyThreadStackSize(unsigned Value) {
8716 SafetyStackThreadSize = Value;
8717}
8718
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008719}
Guy Benyei11169dd2012-12-18 14:30:41 +00008720
8721void clang::setThreadBackgroundPriority() {
8722 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8723 return;
8724
Nico Weber18cfd9f2019-04-21 19:18:41 +00008725#if LLVM_ENABLE_THREADS
Kadir Cetinkayab8f82ca2019-04-18 13:49:20 +00008726 llvm::set_thread_priority(llvm::ThreadPriority::Background);
Nico Weber18cfd9f2019-04-21 19:18:41 +00008727#endif
Guy Benyei11169dd2012-12-18 14:30:41 +00008728}
8729
8730void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8731 if (!Unit)
8732 return;
8733
8734 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8735 DEnd = Unit->stored_diag_end();
8736 D != DEnd; ++D) {
Ben Langmuir749323f2014-04-22 17:40:12 +00008737 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +00008738 CXString Msg = clang_formatDiagnostic(&Diag,
8739 clang_defaultDiagnosticDisplayOptions());
8740 fprintf(stderr, "%s\n", clang_getCString(Msg));
8741 clang_disposeString(Msg);
8742 }
Nico Weber1865df42018-04-27 19:11:14 +00008743#ifdef _WIN32
Guy Benyei11169dd2012-12-18 14:30:41 +00008744 // On Windows, force a flush, since there may be multiple copies of
8745 // stderr and stdout in the file system, all with different buffers
8746 // but writing to the same device.
8747 fflush(stderr);
8748#endif
8749}
8750
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008751MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8752 SourceLocation MacroDefLoc,
8753 CXTranslationUnit TU){
8754 if (MacroDefLoc.isInvalid() || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008755 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008756 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008757 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008758
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008759 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis2d77aeb2013-01-07 19:16:30 +00008760 Preprocessor &PP = Unit->getPreprocessor();
Richard Smith20e883e2015-04-29 23:20:19 +00008761 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008762 if (MD) {
8763 for (MacroDirective::DefInfo
8764 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8765 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8766 return Def.getMacroInfo();
8767 }
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008768 }
8769
Craig Topper69186e72014-06-08 08:38:04 +00008770 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008771}
8772
Richard Smith66a81862015-05-04 02:25:31 +00008773const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
Dmitri Gribenkoba2f7462013-01-11 21:01:49 +00008774 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008775 if (!MacroDef || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008776 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008777 const IdentifierInfo *II = MacroDef->getName();
8778 if (!II)
Craig Topper69186e72014-06-08 08:38:04 +00008779 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008780
8781 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8782}
8783
Richard Smith66a81862015-05-04 02:25:31 +00008784MacroDefinitionRecord *
8785cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8786 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008787 if (!MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008788 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008789 if (Tok.isNot(tok::raw_identifier))
Craig Topper69186e72014-06-08 08:38:04 +00008790 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008791
8792 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008793 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008794 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8795 MI->getDefinitionEndLoc());
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008796 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008797
8798 // Check that the token is inside the definition and not its argument list.
8799 SourceManager &SM = Unit->getSourceManager();
8800 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
Craig Topper69186e72014-06-08 08:38:04 +00008801 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008802 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
Craig Topper69186e72014-06-08 08:38:04 +00008803 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008804
8805 Preprocessor &PP = Unit->getPreprocessor();
8806 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8807 if (!PPRec)
Craig Topper69186e72014-06-08 08:38:04 +00008808 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008809
Alp Toker2d57cea2014-05-17 04:53:25 +00008810 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008811 if (!II.hadMacroDefinition())
Craig Topper69186e72014-06-08 08:38:04 +00008812 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008813
8814 // Check that the identifier is not one of the macro arguments.
Faisal Valiac506d72017-07-17 17:18:43 +00008815 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
Craig Topper69186e72014-06-08 08:38:04 +00008816 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008817
Richard Smith20e883e2015-04-29 23:20:19 +00008818 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00008819 if (!InnerMD)
Craig Topper69186e72014-06-08 08:38:04 +00008820 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008821
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00008822 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008823}
8824
Richard Smith66a81862015-05-04 02:25:31 +00008825MacroDefinitionRecord *
8826cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8827 CXTranslationUnit TU) {
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008828 if (Loc.isInvalid() || !MI || !TU)
Craig Topper69186e72014-06-08 08:38:04 +00008829 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008830
8831 if (MI->getNumTokens() == 0)
Craig Topper69186e72014-06-08 08:38:04 +00008832 return nullptr;
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008833 ASTUnit *Unit = cxtu::getASTUnit(TU);
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008834 Preprocessor &PP = Unit->getPreprocessor();
8835 if (!PP.getPreprocessingRecord())
Craig Topper69186e72014-06-08 08:38:04 +00008836 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008837 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8838 Token Tok;
8839 if (PP.getRawToken(Loc, Tok))
Craig Topper69186e72014-06-08 08:38:04 +00008840 return nullptr;
Argyrios Kyrtzidis579825a2013-01-07 19:16:25 +00008841
8842 return checkForMacroInMacroDefinition(MI, Tok, TU);
8843}
8844
Guy Benyei11169dd2012-12-18 14:30:41 +00008845CXString clang_getClangVersion() {
Dmitri Gribenko2f23e9c2013-02-02 02:19:29 +00008846 return cxstring::createDup(getClangFullVersion());
Guy Benyei11169dd2012-12-18 14:30:41 +00008847}
8848
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008849Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8850 if (TU) {
Dmitri Gribenkoc22ea1c2013-01-26 18:53:38 +00008851 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008852 LogOS << '<' << Unit->getMainFileName() << '>';
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00008853 if (Unit->isMainFileAST())
8854 LogOS << " (" << Unit->getASTFileName() << ')';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008855 return *this;
8856 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00008857 } else {
8858 LogOS << "<NULL TU>";
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008859 }
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008860 return *this;
8861}
8862
Argyrios Kyrtzidisba4b5f82013-03-08 02:32:26 +00008863Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8864 *this << FE->getName();
8865 return *this;
8866}
8867
8868Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8869 CXString cursorName = clang_getCursorDisplayName(cursor);
8870 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8871 clang_disposeString(cursorName);
8872 return *this;
8873}
8874
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008875Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8876 CXFile File;
8877 unsigned Line, Column;
Craig Topper69186e72014-06-08 08:38:04 +00008878 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008879 CXString FileName = clang_getFileName(File);
8880 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8881 clang_disposeString(FileName);
8882 return *this;
8883}
8884
8885Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8886 CXSourceLocation BLoc = clang_getRangeStart(range);
8887 CXSourceLocation ELoc = clang_getRangeEnd(range);
8888
8889 CXFile BFile;
8890 unsigned BLine, BColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008891 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008892
8893 CXFile EFile;
8894 unsigned ELine, EColumn;
Craig Topper69186e72014-06-08 08:38:04 +00008895 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008896
8897 CXString BFileName = clang_getFileName(BFile);
8898 if (BFile == EFile) {
8899 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8900 BLine, BColumn, ELine, EColumn);
8901 } else {
8902 CXString EFileName = clang_getFileName(EFile);
8903 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8904 BLine, BColumn)
8905 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8906 ELine, EColumn);
8907 clang_disposeString(EFileName);
8908 }
8909 clang_disposeString(BFileName);
8910 return *this;
8911}
8912
8913Logger &cxindex::Logger::operator<<(CXString Str) {
8914 *this << clang_getCString(Str);
8915 return *this;
8916}
8917
8918Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8919 LogOS << Fmt;
8920 return *this;
8921}
8922
Chandler Carruth37ad2582014-06-27 15:14:39 +00008923static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8924
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008925cxindex::Logger::~Logger() {
Chandler Carruth37ad2582014-06-27 15:14:39 +00008926 llvm::sys::ScopedLock L(*LoggingMutex);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008927
8928 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8929
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008930 raw_ostream &OS = llvm::errs();
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008931 OS << "[libclang:" << Name << ':';
8932
Alp Toker1a86ad22014-07-06 06:24:00 +00008933#ifdef USE_DARWIN_THREADS
8934 // TODO: Portability.
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008935 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8936 OS << tid << ':';
8937#endif
8938
8939 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8940 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
Yaron Keren09fb7c62015-03-10 07:33:23 +00008941 OS << Msg << '\n';
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008942
8943 if (Trace) {
Zachary Turner1fe2a8d2015-03-05 19:15:09 +00008944 llvm::sys::PrintStackTrace(OS);
Argyrios Kyrtzidisea474352013-01-10 18:54:52 +00008945 OS << "--------------------------------------------------\n";
8946 }
8947}
Ivan Donchevskiic5929132018-12-10 15:58:50 +00008948
8949#ifdef CLANG_TOOL_EXTRA_BUILD
8950// This anchor is used to force the linker to link the clang-tidy plugin.
8951extern volatile int ClangTidyPluginAnchorSource;
8952static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8953 ClangTidyPluginAnchorSource;
8954
8955// This anchor is used to force the linker to link the clang-include-fixer
8956// plugin.
8957extern volatile int ClangIncludeFixerPluginAnchorSource;
8958static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8959 ClangIncludeFixerPluginAnchorSource;
8960#endif