[libclang] Migrate away from PointerUnion::dyn_cast (NFC) (#125381)
[llvm-project.git] / clang / tools / libclang / CIndex.cpp
blobbf7fdeec0cc51b0ee38d9f054e7af5fe8068ae1a
1 //===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the main API hooks in the Clang-C Source Indexing
10 // library.
12 //===----------------------------------------------------------------------===//
14 #include "CIndexDiagnostic.h"
15 #include "CIndexer.h"
16 #include "CLog.h"
17 #include "CXCursor.h"
18 #include "CXFile.h"
19 #include "CXSourceLocation.h"
20 #include "CXString.h"
21 #include "CXTranslationUnit.h"
22 #include "CXType.h"
23 #include "CursorVisitor.h"
24 #include "clang-c/FatalErrorHandler.h"
25 #include "clang/AST/Attr.h"
26 #include "clang/AST/AttrVisitor.h"
27 #include "clang/AST/DeclObjCCommon.h"
28 #include "clang/AST/Expr.h"
29 #include "clang/AST/ExprCXX.h"
30 #include "clang/AST/Mangle.h"
31 #include "clang/AST/OpenACCClause.h"
32 #include "clang/AST/OpenMPClause.h"
33 #include "clang/AST/OperationKinds.h"
34 #include "clang/AST/StmtVisitor.h"
35 #include "clang/Basic/Diagnostic.h"
36 #include "clang/Basic/DiagnosticCategories.h"
37 #include "clang/Basic/DiagnosticIDs.h"
38 #include "clang/Basic/Stack.h"
39 #include "clang/Basic/TargetInfo.h"
40 #include "clang/Basic/Version.h"
41 #include "clang/Frontend/ASTUnit.h"
42 #include "clang/Frontend/CompilerInstance.h"
43 #include "clang/Index/CommentToXML.h"
44 #include "clang/Lex/HeaderSearch.h"
45 #include "clang/Lex/Lexer.h"
46 #include "clang/Lex/PreprocessingRecord.h"
47 #include "clang/Lex/Preprocessor.h"
48 #include "llvm/ADT/STLExtras.h"
49 #include "llvm/ADT/StringSwitch.h"
50 #include "llvm/Config/llvm-config.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/Support/CrashRecoveryContext.h"
53 #include "llvm/Support/Format.h"
54 #include "llvm/Support/ManagedStatic.h"
55 #include "llvm/Support/MemoryBuffer.h"
56 #include "llvm/Support/Program.h"
57 #include "llvm/Support/SaveAndRestore.h"
58 #include "llvm/Support/Signals.h"
59 #include "llvm/Support/TargetSelect.h"
60 #include "llvm/Support/Threading.h"
61 #include "llvm/Support/Timer.h"
62 #include "llvm/Support/VirtualFileSystem.h"
63 #include "llvm/Support/raw_ostream.h"
64 #include "llvm/Support/thread.h"
65 #include <mutex>
66 #include <optional>
68 #if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
69 #define USE_DARWIN_THREADS
70 #endif
72 #ifdef USE_DARWIN_THREADS
73 #include <pthread.h>
74 #endif
76 using namespace clang;
77 using namespace clang::cxcursor;
78 using namespace clang::cxtu;
79 using namespace clang::cxindex;
81 CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
82 std::unique_ptr<ASTUnit> AU) {
83 if (!AU)
84 return nullptr;
85 assert(CIdx);
86 CXTranslationUnit D = new CXTranslationUnitImpl();
87 D->CIdx = CIdx;
88 D->TheASTUnit = AU.release();
89 D->StringPool = new cxstring::CXStringPool();
90 D->Diagnostics = nullptr;
91 D->OverridenCursorsPool = createOverridenCXCursorsPool();
92 D->CommentToXML = nullptr;
93 D->ParsingOptions = 0;
94 D->Arguments = {};
95 return D;
98 bool cxtu::isASTReadError(ASTUnit *AU) {
99 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
100 DEnd = AU->stored_diag_end();
101 D != DEnd; ++D) {
102 if (D->getLevel() >= DiagnosticsEngine::Error &&
103 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
104 diag::DiagCat_AST_Deserialization_Issue)
105 return true;
107 return false;
110 cxtu::CXTUOwner::~CXTUOwner() {
111 if (TU)
112 clang_disposeTranslationUnit(TU);
115 /// Compare two source ranges to determine their relative position in
116 /// the translation unit.
117 static RangeComparisonResult RangeCompare(SourceManager &SM, SourceRange R1,
118 SourceRange R2) {
119 assert(R1.isValid() && "First range is invalid?");
120 assert(R2.isValid() && "Second range is invalid?");
121 if (R1.getEnd() != R2.getBegin() &&
122 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
123 return RangeBefore;
124 if (R2.getEnd() != R1.getBegin() &&
125 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
126 return RangeAfter;
127 return RangeOverlap;
130 /// Determine if a source location falls within, before, or after a
131 /// a given source range.
132 static RangeComparisonResult LocationCompare(SourceManager &SM,
133 SourceLocation L, SourceRange R) {
134 assert(R.isValid() && "First range is invalid?");
135 assert(L.isValid() && "Second range is invalid?");
136 if (L == R.getBegin() || L == R.getEnd())
137 return RangeOverlap;
138 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
139 return RangeBefore;
140 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
141 return RangeAfter;
142 return RangeOverlap;
145 /// Translate a Clang source range into a CIndex source range.
147 /// Clang internally represents ranges where the end location points to the
148 /// start of the token at the end. However, for external clients it is more
149 /// useful to have a CXSourceRange be a proper half-open interval. This routine
150 /// does the appropriate translation.
151 CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
152 const LangOptions &LangOpts,
153 const CharSourceRange &R) {
154 // We want the last character in this location, so we will adjust the
155 // location accordingly.
156 SourceLocation EndLoc = R.getEnd();
157 bool IsTokenRange = R.isTokenRange();
158 if (EndLoc.isValid() && EndLoc.isMacroID() &&
159 !SM.isMacroArgExpansion(EndLoc)) {
160 CharSourceRange Expansion = SM.getExpansionRange(EndLoc);
161 EndLoc = Expansion.getEnd();
162 IsTokenRange = Expansion.isTokenRange();
164 if (IsTokenRange && EndLoc.isValid()) {
165 unsigned Length =
166 Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc), SM, LangOpts);
167 EndLoc = EndLoc.getLocWithOffset(Length);
170 CXSourceRange Result = {
171 {&SM, &LangOpts}, R.getBegin().getRawEncoding(), EndLoc.getRawEncoding()};
172 return Result;
175 CharSourceRange cxloc::translateCXRangeToCharRange(CXSourceRange R) {
176 return CharSourceRange::getCharRange(
177 SourceLocation::getFromRawEncoding(R.begin_int_data),
178 SourceLocation::getFromRawEncoding(R.end_int_data));
181 //===----------------------------------------------------------------------===//
182 // Cursor visitor.
183 //===----------------------------------------------------------------------===//
185 static SourceRange getRawCursorExtent(CXCursor C);
186 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
188 RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
189 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
192 /// Visit the given cursor and, if requested by the visitor,
193 /// its children.
195 /// \param Cursor the cursor to visit.
197 /// \param CheckedRegionOfInterest if true, then the caller already checked
198 /// that this cursor is within the region of interest.
200 /// \returns true if the visitation should be aborted, false if it
201 /// should continue.
202 bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
203 if (clang_isInvalid(Cursor.kind))
204 return false;
206 if (clang_isDeclaration(Cursor.kind)) {
207 const Decl *D = getCursorDecl(Cursor);
208 if (!D) {
209 assert(0 && "Invalid declaration cursor");
210 return true; // abort.
213 // Ignore implicit declarations, unless it's an objc method because
214 // currently we should report implicit methods for properties when indexing.
215 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
216 return false;
219 // If we have a range of interest, and this cursor doesn't intersect with it,
220 // we're done.
221 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
222 SourceRange Range = getRawCursorExtent(Cursor);
223 if (Range.isInvalid() || CompareRegionOfInterest(Range))
224 return false;
227 switch (Visitor(Cursor, Parent, ClientData)) {
228 case CXChildVisit_Break:
229 return true;
231 case CXChildVisit_Continue:
232 return false;
234 case CXChildVisit_Recurse: {
235 bool ret = VisitChildren(Cursor);
236 if (PostChildrenVisitor)
237 if (PostChildrenVisitor(Cursor, ClientData))
238 return true;
239 return ret;
243 llvm_unreachable("Invalid CXChildVisitResult!");
246 static bool visitPreprocessedEntitiesInRange(SourceRange R,
247 PreprocessingRecord &PPRec,
248 CursorVisitor &Visitor) {
249 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
250 FileID FID;
252 if (!Visitor.shouldVisitIncludedEntities()) {
253 // If the begin/end of the range lie in the same FileID, do the optimization
254 // where we skip preprocessed entities that do not come from the same
255 // FileID.
256 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
257 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
258 FID = FileID();
261 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
262 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
263 PPRec, FID);
266 bool CursorVisitor::visitFileRegion() {
267 if (RegionOfInterest.isInvalid())
268 return false;
270 ASTUnit *Unit = cxtu::getASTUnit(TU);
271 SourceManager &SM = Unit->getSourceManager();
273 std::pair<FileID, unsigned> Begin = SM.getDecomposedLoc(
274 SM.getFileLoc(RegionOfInterest.getBegin())),
275 End = SM.getDecomposedLoc(
276 SM.getFileLoc(RegionOfInterest.getEnd()));
278 if (End.first != Begin.first) {
279 // If the end does not reside in the same file, try to recover by
280 // picking the end of the file of begin location.
281 End.first = Begin.first;
282 End.second = SM.getFileIDSize(Begin.first);
285 assert(Begin.first == End.first);
286 if (Begin.second > End.second)
287 return false;
289 FileID File = Begin.first;
290 unsigned Offset = Begin.second;
291 unsigned Length = End.second - Begin.second;
293 if (!VisitDeclsOnly && !VisitPreprocessorLast)
294 if (visitPreprocessedEntitiesInRegion())
295 return true; // visitation break.
297 if (visitDeclsFromFileRegion(File, Offset, Length))
298 return true; // visitation break.
300 if (!VisitDeclsOnly && VisitPreprocessorLast)
301 return visitPreprocessedEntitiesInRegion();
303 return false;
306 static bool isInLexicalContext(Decl *D, DeclContext *DC) {
307 if (!DC)
308 return false;
310 for (DeclContext *DeclDC = D->getLexicalDeclContext(); DeclDC;
311 DeclDC = DeclDC->getLexicalParent()) {
312 if (DeclDC == DC)
313 return true;
315 return false;
318 bool CursorVisitor::visitDeclsFromFileRegion(FileID File, unsigned Offset,
319 unsigned Length) {
320 ASTUnit *Unit = cxtu::getASTUnit(TU);
321 SourceManager &SM = Unit->getSourceManager();
322 SourceRange Range = RegionOfInterest;
324 SmallVector<Decl *, 16> Decls;
325 Unit->findFileRegionDecls(File, Offset, Length, Decls);
327 // If we didn't find any file level decls for the file, try looking at the
328 // file that it was included from.
329 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
330 bool Invalid = false;
331 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
332 if (Invalid)
333 return false;
335 SourceLocation Outer;
336 if (SLEntry.isFile())
337 Outer = SLEntry.getFile().getIncludeLoc();
338 else
339 Outer = SLEntry.getExpansion().getExpansionLocStart();
340 if (Outer.isInvalid())
341 return false;
343 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
344 Length = 0;
345 Unit->findFileRegionDecls(File, Offset, Length, Decls);
348 assert(!Decls.empty());
350 bool VisitedAtLeastOnce = false;
351 DeclContext *CurDC = nullptr;
352 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
353 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
354 Decl *D = *DIt;
355 if (D->getSourceRange().isInvalid())
356 continue;
358 if (isInLexicalContext(D, CurDC))
359 continue;
361 CurDC = dyn_cast<DeclContext>(D);
363 if (TagDecl *TD = dyn_cast<TagDecl>(D))
364 if (!TD->isFreeStanding())
365 continue;
367 RangeComparisonResult CompRes =
368 RangeCompare(SM, D->getSourceRange(), Range);
369 if (CompRes == RangeBefore)
370 continue;
371 if (CompRes == RangeAfter)
372 break;
374 assert(CompRes == RangeOverlap);
375 VisitedAtLeastOnce = true;
377 if (isa<ObjCContainerDecl>(D)) {
378 FileDI_current = &DIt;
379 FileDE_current = DE;
380 } else {
381 FileDI_current = nullptr;
384 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
385 return true; // visitation break.
388 if (VisitedAtLeastOnce)
389 return false;
391 // No Decls overlapped with the range. Move up the lexical context until there
392 // is a context that contains the range or we reach the translation unit
393 // level.
394 DeclContext *DC = DIt == Decls.begin()
395 ? (*DIt)->getLexicalDeclContext()
396 : (*(DIt - 1))->getLexicalDeclContext();
398 while (DC && !DC->isTranslationUnit()) {
399 Decl *D = cast<Decl>(DC);
400 SourceRange CurDeclRange = D->getSourceRange();
401 if (CurDeclRange.isInvalid())
402 break;
404 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
405 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
406 return true; // visitation break.
409 DC = D->getLexicalDeclContext();
412 return false;
415 bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
416 if (!AU->getPreprocessor().getPreprocessingRecord())
417 return false;
419 PreprocessingRecord &PPRec = *AU->getPreprocessor().getPreprocessingRecord();
420 SourceManager &SM = AU->getSourceManager();
422 if (RegionOfInterest.isValid()) {
423 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
424 SourceLocation B = MappedRange.getBegin();
425 SourceLocation E = MappedRange.getEnd();
427 if (AU->isInPreambleFileID(B)) {
428 if (SM.isLoadedSourceLocation(E))
429 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec,
430 *this);
432 // Beginning of range lies in the preamble but it also extends beyond
433 // it into the main file. Split the range into 2 parts, one covering
434 // the preamble and another covering the main file. This allows subsequent
435 // calls to visitPreprocessedEntitiesInRange to accept a source range that
436 // lies in the same FileID, allowing it to skip preprocessed entities that
437 // do not come from the same FileID.
438 bool breaked = visitPreprocessedEntitiesInRange(
439 SourceRange(B, AU->getEndOfPreambleFileID()), PPRec, *this);
440 if (breaked)
441 return true;
442 return visitPreprocessedEntitiesInRange(
443 SourceRange(AU->getStartOfMainFileID(), E), PPRec, *this);
446 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
449 bool OnlyLocalDecls = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
451 if (OnlyLocalDecls)
452 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
453 PPRec);
455 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
458 template <typename InputIterator>
459 bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
460 InputIterator Last,
461 PreprocessingRecord &PPRec,
462 FileID FID) {
463 for (; First != Last; ++First) {
464 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
465 continue;
467 PreprocessedEntity *PPE = *First;
468 if (!PPE)
469 continue;
471 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
472 if (Visit(MakeMacroExpansionCursor(ME, TU)))
473 return true;
475 continue;
478 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
479 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
480 return true;
482 continue;
485 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
486 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
487 return true;
489 continue;
493 return false;
496 /// Visit the children of the given cursor.
498 /// \returns true if the visitation should be aborted, false if it
499 /// should continue.
500 bool CursorVisitor::VisitChildren(CXCursor Cursor) {
501 if (clang_isReference(Cursor.kind) &&
502 Cursor.kind != CXCursor_CXXBaseSpecifier) {
503 // By definition, references have no children.
504 return false;
507 // Set the Parent field to Cursor, then back to its old value once we're
508 // done.
509 SetParentRAII SetParent(Parent, StmtParent, Cursor);
511 if (clang_isDeclaration(Cursor.kind)) {
512 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
513 if (!D)
514 return false;
516 return VisitAttributes(D) || Visit(D);
519 if (clang_isStatement(Cursor.kind)) {
520 if (const Stmt *S = getCursorStmt(Cursor))
521 return Visit(S);
523 return false;
526 if (clang_isExpression(Cursor.kind)) {
527 if (const Expr *E = getCursorExpr(Cursor))
528 return Visit(E);
530 return false;
533 if (clang_isTranslationUnit(Cursor.kind)) {
534 CXTranslationUnit TU = getCursorTU(Cursor);
535 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
537 int VisitOrder[2] = {VisitPreprocessorLast, !VisitPreprocessorLast};
538 for (unsigned I = 0; I != 2; ++I) {
539 if (VisitOrder[I]) {
540 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
541 RegionOfInterest.isInvalid()) {
542 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
543 TLEnd = CXXUnit->top_level_end();
544 TL != TLEnd; ++TL) {
545 const std::optional<bool> V = handleDeclForVisitation(*TL);
546 if (!V)
547 continue;
548 return *V;
550 } else if (VisitDeclContext(
551 CXXUnit->getASTContext().getTranslationUnitDecl()))
552 return true;
553 continue;
556 // Walk the preprocessing record.
557 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
558 visitPreprocessedEntitiesInRegion();
561 return false;
564 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
565 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
566 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
567 return Visit(BaseTSInfo->getTypeLoc());
572 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
573 const IBOutletCollectionAttr *A =
574 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
575 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
576 return Visit(cxcursor::MakeCursorObjCClassRef(
577 ObjT->getInterface(),
578 A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU));
581 if (clang_isAttribute(Cursor.kind)) {
582 if (const Attr *A = getCursorAttr(Cursor))
583 return Visit(A);
585 return false;
588 // If pointing inside a macro definition, check if the token is an identifier
589 // that was ever defined as a macro. In such a case, create a "pseudo" macro
590 // expansion cursor for that token.
591 SourceLocation BeginLoc = RegionOfInterest.getBegin();
592 if (Cursor.kind == CXCursor_MacroDefinition &&
593 BeginLoc == RegionOfInterest.getEnd()) {
594 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
595 const MacroInfo *MI =
596 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
597 if (MacroDefinitionRecord *MacroDef =
598 checkForMacroInMacroDefinition(MI, Loc, TU))
599 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
602 // Nothing to visit at the moment.
603 return false;
606 bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
607 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
608 if (Visit(TSInfo->getTypeLoc()))
609 return true;
611 if (Stmt *Body = B->getBody())
612 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
614 return false;
617 std::optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
618 if (RegionOfInterest.isValid()) {
619 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
620 if (Range.isInvalid())
621 return std::nullopt;
623 switch (CompareRegionOfInterest(Range)) {
624 case RangeBefore:
625 // This declaration comes before the region of interest; skip it.
626 return std::nullopt;
628 case RangeAfter:
629 // This declaration comes after the region of interest; we're done.
630 return false;
632 case RangeOverlap:
633 // This declaration overlaps the region of interest; visit it.
634 break;
637 return true;
640 bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
641 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
643 // FIXME: Eventually remove. This part of a hack to support proper
644 // iteration over all Decls contained lexically within an ObjC container.
645 SaveAndRestore DI_saved(DI_current, &I);
646 SaveAndRestore DE_saved(DE_current, E);
648 for (; I != E; ++I) {
649 Decl *D = *I;
650 if (D->getLexicalDeclContext() != DC)
651 continue;
652 // Filter out synthesized property accessor redeclarations.
653 if (isa<ObjCImplDecl>(DC))
654 if (auto *OMD = dyn_cast<ObjCMethodDecl>(D))
655 if (OMD->isSynthesizedAccessorStub())
656 continue;
657 const std::optional<bool> V = handleDeclForVisitation(D);
658 if (!V)
659 continue;
660 return *V;
662 return false;
665 std::optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
666 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
668 // Ignore synthesized ivars here, otherwise if we have something like:
669 // @synthesize prop = _prop;
670 // and '_prop' is not declared, we will encounter a '_prop' ivar before
671 // encountering the 'prop' synthesize declaration and we will think that
672 // we passed the region-of-interest.
673 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
674 if (ivarD->getSynthesize())
675 return std::nullopt;
678 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
679 // declarations is a mismatch with the compiler semantics.
680 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
681 auto *ID = cast<ObjCInterfaceDecl>(D);
682 if (!ID->isThisDeclarationADefinition())
683 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
685 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
686 auto *PD = cast<ObjCProtocolDecl>(D);
687 if (!PD->isThisDeclarationADefinition())
688 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
691 const std::optional<bool> V = shouldVisitCursor(Cursor);
692 if (!V)
693 return std::nullopt;
694 if (!*V)
695 return false;
696 if (Visit(Cursor, true))
697 return true;
698 return std::nullopt;
701 bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
702 llvm_unreachable("Translation units are visited directly by Visit()");
705 bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
706 if (VisitTemplateParameters(D->getTemplateParameters()))
707 return true;
709 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
712 bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
713 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
714 return Visit(TSInfo->getTypeLoc());
716 return false;
719 bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
720 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
721 return Visit(TSInfo->getTypeLoc());
723 return false;
726 bool CursorVisitor::VisitTagDecl(TagDecl *D) { return VisitDeclContext(D); }
728 bool CursorVisitor::VisitClassTemplateSpecializationDecl(
729 ClassTemplateSpecializationDecl *D) {
730 bool ShouldVisitBody = false;
731 switch (D->getSpecializationKind()) {
732 case TSK_Undeclared:
733 case TSK_ImplicitInstantiation:
734 // Nothing to visit
735 return false;
737 case TSK_ExplicitInstantiationDeclaration:
738 case TSK_ExplicitInstantiationDefinition:
739 break;
741 case TSK_ExplicitSpecialization:
742 ShouldVisitBody = true;
743 break;
746 // Visit the template arguments used in the specialization.
747 if (const auto *ArgsWritten = D->getTemplateArgsAsWritten()) {
748 for (const TemplateArgumentLoc &Arg : ArgsWritten->arguments())
749 if (VisitTemplateArgumentLoc(Arg))
750 return true;
753 return ShouldVisitBody && VisitCXXRecordDecl(D);
756 bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
757 ClassTemplatePartialSpecializationDecl *D) {
758 // FIXME: Visit the "outer" template parameter lists on the TagDecl
759 // before visiting these template parameters.
760 if (VisitTemplateParameters(D->getTemplateParameters()))
761 return true;
763 // Visit the partial specialization arguments.
764 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
765 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
766 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
767 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
768 return true;
770 return VisitCXXRecordDecl(D);
773 bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
774 if (const auto *TC = D->getTypeConstraint()) {
775 if (VisitTypeConstraint(*TC))
776 return true;
779 // Visit the default argument.
780 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
781 VisitTemplateArgumentLoc(D->getDefaultArgument()))
782 return true;
784 return false;
787 bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
788 if (Expr *Init = D->getInitExpr())
789 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
790 return false;
793 bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
794 unsigned NumParamList = DD->getNumTemplateParameterLists();
795 for (unsigned i = 0; i < NumParamList; i++) {
796 TemplateParameterList *Params = DD->getTemplateParameterList(i);
797 if (VisitTemplateParameters(Params))
798 return true;
801 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
802 if (Visit(TSInfo->getTypeLoc()))
803 return true;
805 // Visit the nested-name-specifier, if present.
806 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
807 if (VisitNestedNameSpecifierLoc(QualifierLoc))
808 return true;
810 return false;
813 static bool HasTrailingReturnType(FunctionDecl *ND) {
814 const QualType Ty = ND->getType();
815 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
816 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT))
817 return FT->hasTrailingReturn();
820 return false;
823 /// Compare two base or member initializers based on their source order.
824 static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
825 CXXCtorInitializer *const *Y) {
826 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
829 bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
830 unsigned NumParamList = ND->getNumTemplateParameterLists();
831 for (unsigned i = 0; i < NumParamList; i++) {
832 TemplateParameterList *Params = ND->getTemplateParameterList(i);
833 if (VisitTemplateParameters(Params))
834 return true;
837 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
838 // Visit the function declaration's syntactic components in the order
839 // written. This requires a bit of work.
840 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
841 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
842 const bool HasTrailingRT = HasTrailingReturnType(ND);
844 // If we have a function declared directly (without the use of a typedef),
845 // visit just the return type. Otherwise, just visit the function's type
846 // now.
847 if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT &&
848 Visit(FTL.getReturnLoc())) ||
849 (!FTL && Visit(TL)))
850 return true;
852 // Visit the nested-name-specifier, if present.
853 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
854 if (VisitNestedNameSpecifierLoc(QualifierLoc))
855 return true;
857 // Visit the declaration name.
858 if (!isa<CXXDestructorDecl>(ND))
859 if (VisitDeclarationNameInfo(ND->getNameInfo()))
860 return true;
862 // FIXME: Visit explicitly-specified template arguments!
864 // Visit the function parameters, if we have a function type.
865 if (FTL && VisitFunctionTypeLoc(FTL, true))
866 return true;
868 // Visit the function's trailing return type.
869 if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc()))
870 return true;
872 // FIXME: Attributes?
875 if (auto *E = ND->getTrailingRequiresClause()) {
876 if (Visit(E))
877 return true;
880 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
881 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
882 // Find the initializers that were written in the source.
883 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
884 for (auto *I : Constructor->inits()) {
885 if (!I->isWritten())
886 continue;
888 WrittenInits.push_back(I);
891 // Sort the initializers in source order
892 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
893 &CompareCXXCtorInitializers);
895 // Visit the initializers in source order
896 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
897 CXXCtorInitializer *Init = WrittenInits[I];
898 if (Init->isAnyMemberInitializer()) {
899 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
900 Init->getMemberLocation(), TU)))
901 return true;
902 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
903 if (Visit(TInfo->getTypeLoc()))
904 return true;
907 // Visit the initializer value.
908 if (Expr *Initializer = Init->getInit())
909 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
910 return true;
914 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
915 return true;
918 return false;
921 bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
922 if (VisitDeclaratorDecl(D))
923 return true;
925 if (Expr *BitWidth = D->getBitWidth())
926 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
928 if (Expr *Init = D->getInClassInitializer())
929 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
931 return false;
934 bool CursorVisitor::VisitVarDecl(VarDecl *D) {
935 if (VisitDeclaratorDecl(D))
936 return true;
938 if (Expr *Init = D->getInit())
939 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
941 return false;
944 bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
945 if (VisitDeclaratorDecl(D))
946 return true;
948 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
949 if (D->hasDefaultArgument() &&
950 VisitTemplateArgumentLoc(D->getDefaultArgument()))
951 return true;
953 return false;
956 bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
957 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
958 // before visiting these template parameters.
959 if (VisitTemplateParameters(D->getTemplateParameters()))
960 return true;
962 auto *FD = D->getTemplatedDecl();
963 return VisitAttributes(FD) || VisitFunctionDecl(FD);
966 bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
967 // FIXME: Visit the "outer" template parameter lists on the TagDecl
968 // before visiting these template parameters.
969 if (VisitTemplateParameters(D->getTemplateParameters()))
970 return true;
972 auto *CD = D->getTemplatedDecl();
973 return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
976 bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
977 if (VisitTemplateParameters(D->getTemplateParameters()))
978 return true;
980 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
981 VisitTemplateArgumentLoc(D->getDefaultArgument()))
982 return true;
984 return false;
987 bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
988 // Visit the bound, if it's explicit.
989 if (D->hasExplicitBound()) {
990 if (auto TInfo = D->getTypeSourceInfo()) {
991 if (Visit(TInfo->getTypeLoc()))
992 return true;
996 return false;
999 bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
1000 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
1001 if (Visit(TSInfo->getTypeLoc()))
1002 return true;
1004 for (const auto *P : ND->parameters()) {
1005 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
1006 return true;
1009 return ND->isThisDeclarationADefinition() &&
1010 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
1013 template <typename DeclIt>
1014 static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
1015 SourceManager &SM, SourceLocation EndLoc,
1016 SmallVectorImpl<Decl *> &Decls) {
1017 DeclIt next = *DI_current;
1018 while (++next != DE_current) {
1019 Decl *D_next = *next;
1020 if (!D_next)
1021 break;
1022 SourceLocation L = D_next->getBeginLoc();
1023 if (!L.isValid())
1024 break;
1025 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
1026 *DI_current = next;
1027 Decls.push_back(D_next);
1028 continue;
1030 break;
1034 bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
1035 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
1036 // an @implementation can lexically contain Decls that are not properly
1037 // nested in the AST. When we identify such cases, we need to retrofit
1038 // this nesting here.
1039 if (!DI_current && !FileDI_current)
1040 return VisitDeclContext(D);
1042 // Scan the Decls that immediately come after the container
1043 // in the current DeclContext. If any fall within the
1044 // container's lexical region, stash them into a vector
1045 // for later processing.
1046 SmallVector<Decl *, 24> DeclsInContainer;
1047 SourceLocation EndLoc = D->getSourceRange().getEnd();
1048 SourceManager &SM = AU->getSourceManager();
1049 if (EndLoc.isValid()) {
1050 if (DI_current) {
1051 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
1052 DeclsInContainer);
1053 } else {
1054 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1055 DeclsInContainer);
1059 // The common case.
1060 if (DeclsInContainer.empty())
1061 return VisitDeclContext(D);
1063 // Get all the Decls in the DeclContext, and sort them with the
1064 // additional ones we've collected. Then visit them.
1065 for (auto *SubDecl : D->decls()) {
1066 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1067 SubDecl->getBeginLoc().isInvalid())
1068 continue;
1069 DeclsInContainer.push_back(SubDecl);
1072 // Now sort the Decls so that they appear in lexical order.
1073 llvm::sort(DeclsInContainer, [&SM](Decl *A, Decl *B) {
1074 SourceLocation L_A = A->getBeginLoc();
1075 SourceLocation L_B = B->getBeginLoc();
1076 return L_A != L_B
1077 ? SM.isBeforeInTranslationUnit(L_A, L_B)
1078 : SM.isBeforeInTranslationUnit(A->getEndLoc(), B->getEndLoc());
1081 // Now visit the decls.
1082 for (SmallVectorImpl<Decl *>::iterator I = DeclsInContainer.begin(),
1083 E = DeclsInContainer.end();
1084 I != E; ++I) {
1085 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
1086 const std::optional<bool> &V = shouldVisitCursor(Cursor);
1087 if (!V)
1088 continue;
1089 if (!*V)
1090 return false;
1091 if (Visit(Cursor, true))
1092 return true;
1094 return false;
1097 bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1098 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1099 TU)))
1100 return true;
1102 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1103 return true;
1105 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1106 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1107 E = ND->protocol_end();
1108 I != E; ++I, ++PL)
1109 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1110 return true;
1112 return VisitObjCContainerDecl(ND);
1115 bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1116 if (!PID->isThisDeclarationADefinition())
1117 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1119 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1120 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1121 E = PID->protocol_end();
1122 I != E; ++I, ++PL)
1123 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1124 return true;
1126 return VisitObjCContainerDecl(PID);
1129 bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1130 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1131 return true;
1133 // FIXME: This implements a workaround with @property declarations also being
1134 // installed in the DeclContext for the @interface. Eventually this code
1135 // should be removed.
1136 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1137 if (!CDecl || !CDecl->IsClassExtension())
1138 return false;
1140 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1141 if (!ID)
1142 return false;
1144 IdentifierInfo *PropertyId = PD->getIdentifier();
1145 ObjCPropertyDecl *prevDecl = ObjCPropertyDecl::findPropertyDecl(
1146 cast<DeclContext>(ID), PropertyId, PD->getQueryKind());
1148 if (!prevDecl)
1149 return false;
1151 // Visit synthesized methods since they will be skipped when visiting
1152 // the @interface.
1153 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1154 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1155 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1156 return true;
1158 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1159 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1160 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1161 return true;
1163 return false;
1166 bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1167 if (!typeParamList)
1168 return false;
1170 for (auto *typeParam : *typeParamList) {
1171 // Visit the type parameter.
1172 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1173 return true;
1176 return false;
1179 bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1180 if (!D->isThisDeclarationADefinition()) {
1181 // Forward declaration is treated like a reference.
1182 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1185 // Objective-C type parameters.
1186 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1187 return true;
1189 // Issue callbacks for super class.
1190 if (D->getSuperClass() && Visit(MakeCursorObjCSuperClassRef(
1191 D->getSuperClass(), D->getSuperClassLoc(), TU)))
1192 return true;
1194 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1195 if (Visit(SuperClassTInfo->getTypeLoc()))
1196 return true;
1198 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1199 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1200 E = D->protocol_end();
1201 I != E; ++I, ++PL)
1202 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1203 return true;
1205 return VisitObjCContainerDecl(D);
1208 bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1209 return VisitObjCContainerDecl(D);
1212 bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1213 // 'ID' could be null when dealing with invalid code.
1214 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1215 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1216 return true;
1218 return VisitObjCImplDecl(D);
1221 bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1222 #if 0
1223 // Issue callbacks for super class.
1224 // FIXME: No source location information!
1225 if (D->getSuperClass() &&
1226 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1227 D->getSuperClassLoc(),
1228 TU)))
1229 return true;
1230 #endif
1232 return VisitObjCImplDecl(D);
1235 bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1236 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1237 if (PD->isIvarNameSpecified())
1238 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1240 return false;
1243 bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1244 return VisitDeclContext(D);
1247 bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1248 // Visit nested-name-specifier.
1249 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1250 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1251 return true;
1253 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1254 D->getTargetNameLoc(), TU));
1257 bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1258 // Visit nested-name-specifier.
1259 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1260 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1261 return true;
1264 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1265 return true;
1267 return VisitDeclarationNameInfo(D->getNameInfo());
1270 bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1271 // Visit nested-name-specifier.
1272 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1273 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1274 return true;
1276 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1277 D->getIdentLocation(), TU));
1280 bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1281 // Visit nested-name-specifier.
1282 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1283 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1284 return true;
1287 return VisitDeclarationNameInfo(D->getNameInfo());
1290 bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1291 UnresolvedUsingTypenameDecl *D) {
1292 // Visit nested-name-specifier.
1293 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1294 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1295 return true;
1297 return false;
1300 bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1301 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1302 return true;
1303 if (auto *Message = D->getMessage())
1304 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1305 return true;
1306 return false;
1309 bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1310 if (NamedDecl *FriendD = D->getFriendDecl()) {
1311 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1312 return true;
1313 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1314 if (Visit(TI->getTypeLoc()))
1315 return true;
1317 return false;
1320 bool CursorVisitor::VisitDecompositionDecl(DecompositionDecl *D) {
1321 for (auto *B : D->bindings()) {
1322 if (Visit(MakeCXCursor(B, TU, RegionOfInterest)))
1323 return true;
1325 return VisitVarDecl(D);
1328 bool CursorVisitor::VisitConceptDecl(ConceptDecl *D) {
1329 if (VisitTemplateParameters(D->getTemplateParameters()))
1330 return true;
1332 if (auto *E = D->getConstraintExpr()) {
1333 if (Visit(MakeCXCursor(E, D, TU, RegionOfInterest)))
1334 return true;
1336 return false;
1339 bool CursorVisitor::VisitTypeConstraint(const TypeConstraint &TC) {
1340 if (TC.getNestedNameSpecifierLoc()) {
1341 if (VisitNestedNameSpecifierLoc(TC.getNestedNameSpecifierLoc()))
1342 return true;
1344 if (TC.getNamedConcept()) {
1345 if (Visit(MakeCursorTemplateRef(TC.getNamedConcept(),
1346 TC.getConceptNameLoc(), TU)))
1347 return true;
1349 if (auto Args = TC.getTemplateArgsAsWritten()) {
1350 for (const auto &Arg : Args->arguments()) {
1351 if (VisitTemplateArgumentLoc(Arg))
1352 return true;
1355 return false;
1358 bool CursorVisitor::VisitConceptRequirement(const concepts::Requirement &R) {
1359 using namespace concepts;
1360 switch (R.getKind()) {
1361 case Requirement::RK_Type: {
1362 const TypeRequirement &TR = cast<TypeRequirement>(R);
1363 if (!TR.isSubstitutionFailure()) {
1364 if (Visit(TR.getType()->getTypeLoc()))
1365 return true;
1367 break;
1369 case Requirement::RK_Simple:
1370 case Requirement::RK_Compound: {
1371 const ExprRequirement &ER = cast<ExprRequirement>(R);
1372 if (!ER.isExprSubstitutionFailure()) {
1373 if (Visit(ER.getExpr()))
1374 return true;
1376 if (ER.getKind() == Requirement::RK_Compound) {
1377 const auto &RTR = ER.getReturnTypeRequirement();
1378 if (RTR.isTypeConstraint()) {
1379 if (const auto *Cons = RTR.getTypeConstraint())
1380 VisitTypeConstraint(*Cons);
1383 break;
1385 case Requirement::RK_Nested: {
1386 const NestedRequirement &NR = cast<NestedRequirement>(R);
1387 if (!NR.hasInvalidConstraint()) {
1388 if (Visit(NR.getConstraintExpr()))
1389 return true;
1391 break;
1394 return false;
1397 bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1398 switch (Name.getName().getNameKind()) {
1399 case clang::DeclarationName::Identifier:
1400 case clang::DeclarationName::CXXLiteralOperatorName:
1401 case clang::DeclarationName::CXXDeductionGuideName:
1402 case clang::DeclarationName::CXXOperatorName:
1403 case clang::DeclarationName::CXXUsingDirective:
1404 return false;
1406 case clang::DeclarationName::CXXConstructorName:
1407 case clang::DeclarationName::CXXDestructorName:
1408 case clang::DeclarationName::CXXConversionFunctionName:
1409 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1410 return Visit(TSInfo->getTypeLoc());
1411 return false;
1413 case clang::DeclarationName::ObjCZeroArgSelector:
1414 case clang::DeclarationName::ObjCOneArgSelector:
1415 case clang::DeclarationName::ObjCMultiArgSelector:
1416 // FIXME: Per-identifier location info?
1417 return false;
1420 llvm_unreachable("Invalid DeclarationName::Kind!");
1423 bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1424 SourceRange Range) {
1425 // FIXME: This whole routine is a hack to work around the lack of proper
1426 // source information in nested-name-specifiers (PR5791). Since we do have
1427 // a beginning source location, we can visit the first component of the
1428 // nested-name-specifier, if it's a single-token component.
1429 if (!NNS)
1430 return false;
1432 // Get the first component in the nested-name-specifier.
1433 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1434 NNS = Prefix;
1436 switch (NNS->getKind()) {
1437 case NestedNameSpecifier::Namespace:
1438 return Visit(
1439 MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(), TU));
1441 case NestedNameSpecifier::NamespaceAlias:
1442 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1443 Range.getBegin(), TU));
1445 case NestedNameSpecifier::TypeSpec: {
1446 // If the type has a form where we know that the beginning of the source
1447 // range matches up with a reference cursor. Visit the appropriate reference
1448 // cursor.
1449 const Type *T = NNS->getAsType();
1450 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1451 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1452 if (const TagType *Tag = dyn_cast<TagType>(T))
1453 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1454 if (const TemplateSpecializationType *TST =
1455 dyn_cast<TemplateSpecializationType>(T))
1456 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1457 break;
1460 case NestedNameSpecifier::TypeSpecWithTemplate:
1461 case NestedNameSpecifier::Global:
1462 case NestedNameSpecifier::Identifier:
1463 case NestedNameSpecifier::Super:
1464 break;
1467 return false;
1470 bool CursorVisitor::VisitNestedNameSpecifierLoc(
1471 NestedNameSpecifierLoc Qualifier) {
1472 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1473 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1474 Qualifiers.push_back(Qualifier);
1476 while (!Qualifiers.empty()) {
1477 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1478 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1479 switch (NNS->getKind()) {
1480 case NestedNameSpecifier::Namespace:
1481 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1482 Q.getLocalBeginLoc(), TU)))
1483 return true;
1485 break;
1487 case NestedNameSpecifier::NamespaceAlias:
1488 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1489 Q.getLocalBeginLoc(), TU)))
1490 return true;
1492 break;
1494 case NestedNameSpecifier::TypeSpec:
1495 case NestedNameSpecifier::TypeSpecWithTemplate:
1496 if (Visit(Q.getTypeLoc()))
1497 return true;
1499 break;
1501 case NestedNameSpecifier::Global:
1502 case NestedNameSpecifier::Identifier:
1503 case NestedNameSpecifier::Super:
1504 break;
1508 return false;
1511 bool CursorVisitor::VisitTemplateParameters(
1512 const TemplateParameterList *Params) {
1513 if (!Params)
1514 return false;
1516 for (TemplateParameterList::const_iterator P = Params->begin(),
1517 PEnd = Params->end();
1518 P != PEnd; ++P) {
1519 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1520 return true;
1523 if (const auto *E = Params->getRequiresClause()) {
1524 if (Visit(MakeCXCursor(E, nullptr, TU, RegionOfInterest)))
1525 return true;
1528 return false;
1531 bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1532 switch (Name.getKind()) {
1533 case TemplateName::Template:
1534 case TemplateName::UsingTemplate:
1535 case TemplateName::QualifiedTemplate: // FIXME: Visit nested-name-specifier.
1536 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1538 case TemplateName::OverloadedTemplate:
1539 // Visit the overloaded template set.
1540 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1541 return true;
1543 return false;
1545 case TemplateName::AssumedTemplate:
1546 // FIXME: Visit DeclarationName?
1547 return false;
1549 case TemplateName::DependentTemplate:
1550 // FIXME: Visit nested-name-specifier.
1551 return false;
1553 case TemplateName::SubstTemplateTemplateParm:
1554 return Visit(MakeCursorTemplateRef(
1555 Name.getAsSubstTemplateTemplateParm()->getParameter(), Loc, TU));
1557 case TemplateName::SubstTemplateTemplateParmPack:
1558 return Visit(MakeCursorTemplateRef(
1559 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(), Loc,
1560 TU));
1562 case TemplateName::DeducedTemplate:
1563 llvm_unreachable("DeducedTemplate shouldn't appear in source");
1566 llvm_unreachable("Invalid TemplateName::Kind!");
1569 bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1570 switch (TAL.getArgument().getKind()) {
1571 case TemplateArgument::Null:
1572 case TemplateArgument::Integral:
1573 case TemplateArgument::Pack:
1574 return false;
1576 case TemplateArgument::Type:
1577 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1578 return Visit(TSInfo->getTypeLoc());
1579 return false;
1581 case TemplateArgument::Declaration:
1582 if (Expr *E = TAL.getSourceDeclExpression())
1583 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1584 return false;
1586 case TemplateArgument::StructuralValue:
1587 if (Expr *E = TAL.getSourceStructuralValueExpression())
1588 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1589 return false;
1591 case TemplateArgument::NullPtr:
1592 if (Expr *E = TAL.getSourceNullPtrExpression())
1593 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1594 return false;
1596 case TemplateArgument::Expression:
1597 if (Expr *E = TAL.getSourceExpression())
1598 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1599 return false;
1601 case TemplateArgument::Template:
1602 case TemplateArgument::TemplateExpansion:
1603 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1604 return true;
1606 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1607 TAL.getTemplateNameLoc());
1610 llvm_unreachable("Invalid TemplateArgument::Kind!");
1613 bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1614 return VisitDeclContext(D);
1617 bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1618 return Visit(TL.getUnqualifiedLoc());
1621 bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1622 ASTContext &Context = AU->getASTContext();
1624 // Some builtin types (such as Objective-C's "id", "sel", and
1625 // "Class") have associated declarations. Create cursors for those.
1626 QualType VisitType;
1627 switch (TL.getTypePtr()->getKind()) {
1629 case BuiltinType::Void:
1630 case BuiltinType::NullPtr:
1631 case BuiltinType::Dependent:
1632 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1633 case BuiltinType::Id:
1634 #include "clang/Basic/OpenCLImageTypes.def"
1635 #define EXT_OPAQUE_TYPE(ExtTYpe, Id, Ext) case BuiltinType::Id:
1636 #include "clang/Basic/OpenCLExtensionTypes.def"
1637 case BuiltinType::OCLSampler:
1638 case BuiltinType::OCLEvent:
1639 case BuiltinType::OCLClkEvent:
1640 case BuiltinType::OCLQueue:
1641 case BuiltinType::OCLReserveID:
1642 #define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
1643 #include "clang/Basic/AArch64SVEACLETypes.def"
1644 #define PPC_VECTOR_TYPE(Name, Id, Size) case BuiltinType::Id:
1645 #include "clang/Basic/PPCTypes.def"
1646 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
1647 #include "clang/Basic/RISCVVTypes.def"
1648 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
1649 #include "clang/Basic/WebAssemblyReferenceTypes.def"
1650 #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
1651 #include "clang/Basic/AMDGPUTypes.def"
1652 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
1653 #include "clang/Basic/HLSLIntangibleTypes.def"
1654 #define BUILTIN_TYPE(Id, SingletonId)
1655 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1656 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1657 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1658 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1659 #include "clang/AST/BuiltinTypes.def"
1660 break;
1662 case BuiltinType::ObjCId:
1663 VisitType = Context.getObjCIdType();
1664 break;
1666 case BuiltinType::ObjCClass:
1667 VisitType = Context.getObjCClassType();
1668 break;
1670 case BuiltinType::ObjCSel:
1671 VisitType = Context.getObjCSelType();
1672 break;
1675 if (!VisitType.isNull()) {
1676 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1677 return Visit(
1678 MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(), TU));
1681 return false;
1684 bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1685 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1688 bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1689 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1692 bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1693 if (TL.isDefinition())
1694 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1696 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1699 bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1700 if (const auto *TC = TL.getDecl()->getTypeConstraint()) {
1701 if (VisitTypeConstraint(*TC))
1702 return true;
1705 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1708 bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1709 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
1712 bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
1713 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getBeginLoc(), TU)))
1714 return true;
1715 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1716 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1717 TU)))
1718 return true;
1721 return false;
1724 bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1725 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1726 return true;
1728 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1729 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1730 return true;
1733 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1734 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1735 TU)))
1736 return true;
1739 return false;
1742 bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1743 return Visit(TL.getPointeeLoc());
1746 bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1747 return Visit(TL.getInnerLoc());
1750 bool CursorVisitor::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
1751 return Visit(TL.getInnerLoc());
1754 bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1755 return Visit(TL.getPointeeLoc());
1758 bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1759 return Visit(TL.getPointeeLoc());
1762 bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1763 return Visit(TL.getPointeeLoc());
1766 bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1767 return Visit(TL.getPointeeLoc());
1770 bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1771 return Visit(TL.getPointeeLoc());
1774 bool CursorVisitor::VisitUsingTypeLoc(UsingTypeLoc TL) {
1775 auto *underlyingDecl = TL.getUnderlyingType()->getAsTagDecl();
1776 if (underlyingDecl) {
1777 return Visit(MakeCursorTypeRef(underlyingDecl, TL.getNameLoc(), TU));
1779 return false;
1782 bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1783 return Visit(TL.getModifiedLoc());
1786 bool CursorVisitor::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
1787 return Visit(TL.getInnerLoc());
1790 bool CursorVisitor::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
1791 return Visit(TL.getWrappedLoc());
1794 bool CursorVisitor::VisitHLSLAttributedResourceTypeLoc(
1795 HLSLAttributedResourceTypeLoc TL) {
1796 return Visit(TL.getWrappedLoc());
1799 bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1800 bool SkipResultType) {
1801 if (!SkipResultType && Visit(TL.getReturnLoc()))
1802 return true;
1804 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1805 if (Decl *D = TL.getParam(I))
1806 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1807 return true;
1809 return false;
1812 bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1813 if (Visit(TL.getElementLoc()))
1814 return true;
1816 if (Expr *Size = TL.getSizeExpr())
1817 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1819 return false;
1822 bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1823 return Visit(TL.getOriginalLoc());
1826 bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1827 return Visit(TL.getOriginalLoc());
1830 bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1831 DeducedTemplateSpecializationTypeLoc TL) {
1832 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1833 TL.getTemplateNameLoc()))
1834 return true;
1836 return false;
1839 bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1840 TemplateSpecializationTypeLoc TL) {
1841 // Visit the template name.
1842 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1843 TL.getTemplateNameLoc()))
1844 return true;
1846 // Visit the template arguments.
1847 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1848 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1849 return true;
1851 return false;
1854 bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1855 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1858 bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1859 if (TypeSourceInfo *TSInfo = TL.getUnmodifiedTInfo())
1860 return Visit(TSInfo->getTypeLoc());
1862 return false;
1865 bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1866 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1867 return Visit(TSInfo->getTypeLoc());
1869 return false;
1872 bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1873 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
1876 bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1877 DependentTemplateSpecializationTypeLoc TL) {
1878 // Visit the nested-name-specifier, if there is one.
1879 if (TL.getQualifierLoc() && VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1880 return true;
1882 // Visit the template arguments.
1883 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1884 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1885 return true;
1887 return false;
1890 bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1891 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1892 return true;
1894 return Visit(TL.getNamedTypeLoc());
1897 bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1898 return Visit(TL.getPatternLoc());
1901 bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1902 if (Expr *E = TL.getUnderlyingExpr())
1903 return Visit(MakeCXCursor(E, StmtParent, TU));
1905 return false;
1908 bool CursorVisitor::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
1909 if (Visit(TL.getPatternLoc()))
1910 return true;
1911 return Visit(MakeCXCursor(TL.getIndexExpr(), StmtParent, TU));
1914 bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1915 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1918 bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1919 return Visit(TL.getValueLoc());
1922 bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1923 return Visit(TL.getValueLoc());
1926 #define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1927 bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1928 return Visit##PARENT##Loc(TL); \
1931 DEFAULT_TYPELOC_IMPL(Complex, Type)
1932 DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1933 DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1934 DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1935 DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1936 DEFAULT_TYPELOC_IMPL(ArrayParameter, ConstantArrayType)
1937 DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
1938 DEFAULT_TYPELOC_IMPL(DependentVector, Type)
1939 DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1940 DEFAULT_TYPELOC_IMPL(Vector, Type)
1941 DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1942 DEFAULT_TYPELOC_IMPL(ConstantMatrix, MatrixType)
1943 DEFAULT_TYPELOC_IMPL(DependentSizedMatrix, MatrixType)
1944 DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1945 DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1946 DEFAULT_TYPELOC_IMPL(Record, TagType)
1947 DEFAULT_TYPELOC_IMPL(Enum, TagType)
1948 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1949 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1950 DEFAULT_TYPELOC_IMPL(Auto, Type)
1951 DEFAULT_TYPELOC_IMPL(BitInt, Type)
1952 DEFAULT_TYPELOC_IMPL(DependentBitInt, Type)
1954 bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1955 // Visit the nested-name-specifier, if present.
1956 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1957 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1958 return true;
1960 if (D->isCompleteDefinition()) {
1961 for (const auto &I : D->bases()) {
1962 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
1963 return true;
1967 return VisitTagDecl(D);
1970 bool CursorVisitor::VisitAttributes(Decl *D) {
1971 for (const auto *I : D->attrs())
1972 if ((TU->ParsingOptions & CXTranslationUnit_VisitImplicitAttributes ||
1973 !I->isImplicit()) &&
1974 Visit(MakeCXCursor(I, D, TU)))
1975 return true;
1977 return false;
1980 //===----------------------------------------------------------------------===//
1981 // Data-recursive visitor methods.
1982 //===----------------------------------------------------------------------===//
1984 namespace {
1985 #define DEF_JOB(NAME, DATA, KIND) \
1986 class NAME : public VisitorJob { \
1987 public: \
1988 NAME(const DATA *d, CXCursor parent) \
1989 : VisitorJob(parent, VisitorJob::KIND, d) {} \
1990 static bool classof(const VisitorJob *VJ) { \
1991 return VJ->getKind() == KIND; \
1993 const DATA *get() const { return static_cast<const DATA *>(data[0]); } \
1996 DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1997 DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1998 DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1999 DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
2000 DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
2001 DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
2002 DEF_JOB(ConceptSpecializationExprVisit, ConceptSpecializationExpr,
2003 ConceptSpecializationExprVisitKind)
2004 DEF_JOB(RequiresExprVisit, RequiresExpr, RequiresExprVisitKind)
2005 DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
2006 #undef DEF_JOB
2008 class ExplicitTemplateArgsVisit : public VisitorJob {
2009 public:
2010 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
2011 const TemplateArgumentLoc *End, CXCursor parent)
2012 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
2013 End) {}
2014 static bool classof(const VisitorJob *VJ) {
2015 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
2017 const TemplateArgumentLoc *begin() const {
2018 return static_cast<const TemplateArgumentLoc *>(data[0]);
2020 const TemplateArgumentLoc *end() {
2021 return static_cast<const TemplateArgumentLoc *>(data[1]);
2024 class DeclVisit : public VisitorJob {
2025 public:
2026 DeclVisit(const Decl *D, CXCursor parent, bool isFirst)
2027 : VisitorJob(parent, VisitorJob::DeclVisitKind, D,
2028 isFirst ? (void *)1 : (void *)nullptr) {}
2029 static bool classof(const VisitorJob *VJ) {
2030 return VJ->getKind() == DeclVisitKind;
2032 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
2033 bool isFirst() const { return data[1] != nullptr; }
2035 class TypeLocVisit : public VisitorJob {
2036 public:
2037 TypeLocVisit(TypeLoc tl, CXCursor parent)
2038 : VisitorJob(parent, VisitorJob::TypeLocVisitKind,
2039 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
2041 static bool classof(const VisitorJob *VJ) {
2042 return VJ->getKind() == TypeLocVisitKind;
2045 TypeLoc get() const {
2046 QualType T = QualType::getFromOpaquePtr(data[0]);
2047 return TypeLoc(T, const_cast<void *>(data[1]));
2051 class LabelRefVisit : public VisitorJob {
2052 public:
2053 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
2054 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
2055 labelLoc.getPtrEncoding()) {}
2057 static bool classof(const VisitorJob *VJ) {
2058 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
2060 const LabelDecl *get() const {
2061 return static_cast<const LabelDecl *>(data[0]);
2063 SourceLocation getLoc() const {
2064 return SourceLocation::getFromPtrEncoding(data[1]);
2068 class NestedNameSpecifierLocVisit : public VisitorJob {
2069 public:
2070 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
2071 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
2072 Qualifier.getNestedNameSpecifier(),
2073 Qualifier.getOpaqueData()) {}
2075 static bool classof(const VisitorJob *VJ) {
2076 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
2079 NestedNameSpecifierLoc get() const {
2080 return NestedNameSpecifierLoc(
2081 const_cast<NestedNameSpecifier *>(
2082 static_cast<const NestedNameSpecifier *>(data[0])),
2083 const_cast<void *>(data[1]));
2087 class DeclarationNameInfoVisit : public VisitorJob {
2088 public:
2089 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
2090 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
2091 static bool classof(const VisitorJob *VJ) {
2092 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
2094 DeclarationNameInfo get() const {
2095 const Stmt *S = static_cast<const Stmt *>(data[0]);
2096 switch (S->getStmtClass()) {
2097 default:
2098 llvm_unreachable("Unhandled Stmt");
2099 case clang::Stmt::MSDependentExistsStmtClass:
2100 return cast<MSDependentExistsStmt>(S)->getNameInfo();
2101 case Stmt::CXXDependentScopeMemberExprClass:
2102 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
2103 case Stmt::DependentScopeDeclRefExprClass:
2104 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
2105 case Stmt::OMPCriticalDirectiveClass:
2106 return cast<OMPCriticalDirective>(S)->getDirectiveName();
2110 class MemberRefVisit : public VisitorJob {
2111 public:
2112 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
2113 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
2114 L.getPtrEncoding()) {}
2115 static bool classof(const VisitorJob *VJ) {
2116 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
2118 const FieldDecl *get() const {
2119 return static_cast<const FieldDecl *>(data[0]);
2121 SourceLocation getLoc() const {
2122 return SourceLocation::getFromRawEncoding(
2123 (SourceLocation::UIntTy)(uintptr_t)data[1]);
2126 class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void>,
2127 public ConstAttrVisitor<EnqueueVisitor, void> {
2128 friend class OpenACCClauseEnqueue;
2129 friend class OMPClauseEnqueue;
2130 VisitorWorkList &WL;
2131 CXCursor Parent;
2133 public:
2134 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
2135 : WL(wl), Parent(parent) {}
2137 void VisitAddrLabelExpr(const AddrLabelExpr *E);
2138 void VisitBlockExpr(const BlockExpr *B);
2139 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2140 void VisitCompoundStmt(const CompoundStmt *S);
2141 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */
2143 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
2144 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
2145 void VisitCXXNewExpr(const CXXNewExpr *E);
2146 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
2147 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
2148 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
2149 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
2150 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
2151 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
2152 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
2153 void VisitCXXCatchStmt(const CXXCatchStmt *S);
2154 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
2155 void VisitDeclRefExpr(const DeclRefExpr *D);
2156 void VisitDeclStmt(const DeclStmt *S);
2157 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
2158 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
2159 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
2160 void VisitForStmt(const ForStmt *FS);
2161 void VisitGotoStmt(const GotoStmt *GS);
2162 void VisitIfStmt(const IfStmt *If);
2163 void VisitInitListExpr(const InitListExpr *IE);
2164 void VisitMemberExpr(const MemberExpr *M);
2165 void VisitOffsetOfExpr(const OffsetOfExpr *E);
2166 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
2167 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
2168 void VisitOverloadExpr(const OverloadExpr *E);
2169 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
2170 void VisitStmt(const Stmt *S);
2171 void VisitSwitchStmt(const SwitchStmt *S);
2172 void VisitWhileStmt(const WhileStmt *W);
2173 void VisitTypeTraitExpr(const TypeTraitExpr *E);
2174 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
2175 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
2176 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
2177 void VisitVAArgExpr(const VAArgExpr *E);
2178 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
2179 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
2180 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
2181 void VisitLambdaExpr(const LambdaExpr *E);
2182 void VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
2183 void VisitRequiresExpr(const RequiresExpr *E);
2184 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
2185 void VisitOpenACCComputeConstruct(const OpenACCComputeConstruct *D);
2186 void VisitOpenACCLoopConstruct(const OpenACCLoopConstruct *D);
2187 void VisitOpenACCCombinedConstruct(const OpenACCCombinedConstruct *D);
2188 void VisitOpenACCDataConstruct(const OpenACCDataConstruct *D);
2189 void VisitOpenACCEnterDataConstruct(const OpenACCEnterDataConstruct *D);
2190 void VisitOpenACCExitDataConstruct(const OpenACCExitDataConstruct *D);
2191 void VisitOpenACCHostDataConstruct(const OpenACCHostDataConstruct *D);
2192 void VisitOpenACCWaitConstruct(const OpenACCWaitConstruct *D);
2193 void VisitOpenACCInitConstruct(const OpenACCInitConstruct *D);
2194 void VisitOpenACCShutdownConstruct(const OpenACCShutdownConstruct *D);
2195 void VisitOpenACCSetConstruct(const OpenACCSetConstruct *D);
2196 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
2197 void VisitOMPLoopBasedDirective(const OMPLoopBasedDirective *D);
2198 void VisitOMPLoopDirective(const OMPLoopDirective *D);
2199 void VisitOMPParallelDirective(const OMPParallelDirective *D);
2200 void VisitOMPSimdDirective(const OMPSimdDirective *D);
2201 void
2202 VisitOMPLoopTransformationDirective(const OMPLoopTransformationDirective *D);
2203 void VisitOMPTileDirective(const OMPTileDirective *D);
2204 void VisitOMPUnrollDirective(const OMPUnrollDirective *D);
2205 void VisitOMPReverseDirective(const OMPReverseDirective *D);
2206 void VisitOMPInterchangeDirective(const OMPInterchangeDirective *D);
2207 void VisitOMPForDirective(const OMPForDirective *D);
2208 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
2209 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
2210 void VisitOMPSectionDirective(const OMPSectionDirective *D);
2211 void VisitOMPSingleDirective(const OMPSingleDirective *D);
2212 void VisitOMPMasterDirective(const OMPMasterDirective *D);
2213 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
2214 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
2215 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
2216 void VisitOMPParallelMasterDirective(const OMPParallelMasterDirective *D);
2217 void VisitOMPParallelMaskedDirective(const OMPParallelMaskedDirective *D);
2218 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
2219 void VisitOMPTaskDirective(const OMPTaskDirective *D);
2220 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
2221 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
2222 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
2223 void VisitOMPAssumeDirective(const OMPAssumeDirective *D);
2224 void VisitOMPErrorDirective(const OMPErrorDirective *D);
2225 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
2226 void
2227 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
2228 void VisitOMPCancelDirective(const OMPCancelDirective *D);
2229 void VisitOMPFlushDirective(const OMPFlushDirective *D);
2230 void VisitOMPDepobjDirective(const OMPDepobjDirective *D);
2231 void VisitOMPScanDirective(const OMPScanDirective *D);
2232 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
2233 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
2234 void VisitOMPTargetDirective(const OMPTargetDirective *D);
2235 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
2236 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
2237 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
2238 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
2239 void
2240 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
2241 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
2242 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
2243 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
2244 void VisitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective *D);
2245 void VisitOMPMaskedTaskLoopDirective(const OMPMaskedTaskLoopDirective *D);
2246 void
2247 VisitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective *D);
2248 void VisitOMPMaskedTaskLoopSimdDirective(
2249 const OMPMaskedTaskLoopSimdDirective *D);
2250 void VisitOMPParallelMasterTaskLoopDirective(
2251 const OMPParallelMasterTaskLoopDirective *D);
2252 void VisitOMPParallelMaskedTaskLoopDirective(
2253 const OMPParallelMaskedTaskLoopDirective *D);
2254 void VisitOMPParallelMasterTaskLoopSimdDirective(
2255 const OMPParallelMasterTaskLoopSimdDirective *D);
2256 void VisitOMPParallelMaskedTaskLoopSimdDirective(
2257 const OMPParallelMaskedTaskLoopSimdDirective *D);
2258 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
2259 void VisitOMPDistributeParallelForDirective(
2260 const OMPDistributeParallelForDirective *D);
2261 void VisitOMPDistributeParallelForSimdDirective(
2262 const OMPDistributeParallelForSimdDirective *D);
2263 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
2264 void VisitOMPTargetParallelForSimdDirective(
2265 const OMPTargetParallelForSimdDirective *D);
2266 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
2267 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
2268 void VisitOMPTeamsDistributeSimdDirective(
2269 const OMPTeamsDistributeSimdDirective *D);
2270 void VisitOMPTeamsDistributeParallelForSimdDirective(
2271 const OMPTeamsDistributeParallelForSimdDirective *D);
2272 void VisitOMPTeamsDistributeParallelForDirective(
2273 const OMPTeamsDistributeParallelForDirective *D);
2274 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
2275 void VisitOMPTargetTeamsDistributeDirective(
2276 const OMPTargetTeamsDistributeDirective *D);
2277 void VisitOMPTargetTeamsDistributeParallelForDirective(
2278 const OMPTargetTeamsDistributeParallelForDirective *D);
2279 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2280 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
2281 void VisitOMPTargetTeamsDistributeSimdDirective(
2282 const OMPTargetTeamsDistributeSimdDirective *D);
2284 // Attributes
2285 void VisitAnnotateAttr(const AnnotateAttr *A);
2287 private:
2288 void AddDeclarationNameInfo(const Stmt *S);
2289 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
2290 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2291 unsigned NumTemplateArgs);
2292 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2293 void AddStmt(const Stmt *S);
2294 void AddDecl(const Decl *D, bool isFirst = true);
2295 void AddTypeLoc(TypeSourceInfo *TI);
2296 void EnqueueChildren(const Stmt *S);
2297 void EnqueueChildren(const OpenACCClause *S);
2298 void EnqueueChildren(const OMPClause *S);
2299 void EnqueueChildren(const AnnotateAttr *A);
2301 } // namespace
2303 void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
2304 // 'S' should always be non-null, since it comes from the
2305 // statement we are visiting.
2306 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2309 void EnqueueVisitor::AddNestedNameSpecifierLoc(
2310 NestedNameSpecifierLoc Qualifier) {
2311 if (Qualifier)
2312 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2315 void EnqueueVisitor::AddStmt(const Stmt *S) {
2316 if (S)
2317 WL.push_back(StmtVisit(S, Parent));
2319 void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
2320 if (D)
2321 WL.push_back(DeclVisit(D, Parent, isFirst));
2323 void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2324 unsigned NumTemplateArgs) {
2325 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
2327 void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
2328 if (D)
2329 WL.push_back(MemberRefVisit(D, L, Parent));
2331 void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2332 if (TI)
2333 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2335 void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
2336 unsigned size = WL.size();
2337 for (const Stmt *SubStmt : S->children()) {
2338 AddStmt(SubStmt);
2340 if (size == WL.size())
2341 return;
2342 // Now reverse the entries we just added. This will match the DFS
2343 // ordering performed by the worklist.
2344 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2345 std::reverse(I, E);
2347 namespace {
2348 class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2349 EnqueueVisitor *Visitor;
2350 /// Process clauses with list of variables.
2351 template <typename T> void VisitOMPClauseList(T *Node);
2353 public:
2354 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) {}
2355 #define GEN_CLANG_CLAUSE_CLASS
2356 #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(const Class *C);
2357 #include "llvm/Frontend/OpenMP/OMP.inc"
2358 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
2359 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
2362 void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2363 const OMPClauseWithPreInit *C) {
2364 Visitor->AddStmt(C->getPreInitStmt());
2367 void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2368 const OMPClauseWithPostUpdate *C) {
2369 VisitOMPClauseWithPreInit(C);
2370 Visitor->AddStmt(C->getPostUpdateExpr());
2373 void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
2374 VisitOMPClauseWithPreInit(C);
2375 Visitor->AddStmt(C->getCondition());
2378 void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2379 Visitor->AddStmt(C->getCondition());
2382 void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
2383 VisitOMPClauseWithPreInit(C);
2384 Visitor->AddStmt(C->getNumThreads());
2387 void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2388 Visitor->AddStmt(C->getSafelen());
2391 void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2392 Visitor->AddStmt(C->getSimdlen());
2395 void OMPClauseEnqueue::VisitOMPSizesClause(const OMPSizesClause *C) {
2396 for (auto E : C->getSizesRefs())
2397 Visitor->AddStmt(E);
2400 void OMPClauseEnqueue::VisitOMPPermutationClause(
2401 const OMPPermutationClause *C) {
2402 for (auto E : C->getArgsRefs())
2403 Visitor->AddStmt(E);
2406 void OMPClauseEnqueue::VisitOMPFullClause(const OMPFullClause *C) {}
2408 void OMPClauseEnqueue::VisitOMPPartialClause(const OMPPartialClause *C) {
2409 Visitor->AddStmt(C->getFactor());
2412 void OMPClauseEnqueue::VisitOMPAllocatorClause(const OMPAllocatorClause *C) {
2413 Visitor->AddStmt(C->getAllocator());
2416 void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2417 Visitor->AddStmt(C->getNumForLoops());
2420 void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) {}
2422 void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) {}
2424 void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
2425 VisitOMPClauseWithPreInit(C);
2426 Visitor->AddStmt(C->getChunkSize());
2429 void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2430 Visitor->AddStmt(C->getNumForLoops());
2433 void OMPClauseEnqueue::VisitOMPDetachClause(const OMPDetachClause *C) {
2434 Visitor->AddStmt(C->getEventHandler());
2437 void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2439 void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2441 void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2443 void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2445 void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2447 void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2449 void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2451 void OMPClauseEnqueue::VisitOMPCompareClause(const OMPCompareClause *) {}
2453 void OMPClauseEnqueue::VisitOMPFailClause(const OMPFailClause *) {}
2455 void OMPClauseEnqueue::VisitOMPAbsentClause(const OMPAbsentClause *) {}
2457 void OMPClauseEnqueue::VisitOMPHoldsClause(const OMPHoldsClause *) {}
2459 void OMPClauseEnqueue::VisitOMPContainsClause(const OMPContainsClause *) {}
2461 void OMPClauseEnqueue::VisitOMPNoOpenMPClause(const OMPNoOpenMPClause *) {}
2463 void OMPClauseEnqueue::VisitOMPNoOpenMPRoutinesClause(
2464 const OMPNoOpenMPRoutinesClause *) {}
2466 void OMPClauseEnqueue::VisitOMPNoParallelismClause(
2467 const OMPNoParallelismClause *) {}
2469 void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2471 void OMPClauseEnqueue::VisitOMPAcqRelClause(const OMPAcqRelClause *) {}
2473 void OMPClauseEnqueue::VisitOMPAcquireClause(const OMPAcquireClause *) {}
2475 void OMPClauseEnqueue::VisitOMPReleaseClause(const OMPReleaseClause *) {}
2477 void OMPClauseEnqueue::VisitOMPRelaxedClause(const OMPRelaxedClause *) {}
2479 void OMPClauseEnqueue::VisitOMPWeakClause(const OMPWeakClause *) {}
2481 void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2483 void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2485 void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2487 void OMPClauseEnqueue::VisitOMPInitClause(const OMPInitClause *C) {
2488 VisitOMPClauseList(C);
2491 void OMPClauseEnqueue::VisitOMPUseClause(const OMPUseClause *C) {
2492 Visitor->AddStmt(C->getInteropVar());
2495 void OMPClauseEnqueue::VisitOMPDestroyClause(const OMPDestroyClause *C) {
2496 if (C->getInteropVar())
2497 Visitor->AddStmt(C->getInteropVar());
2500 void OMPClauseEnqueue::VisitOMPNovariantsClause(const OMPNovariantsClause *C) {
2501 Visitor->AddStmt(C->getCondition());
2504 void OMPClauseEnqueue::VisitOMPNocontextClause(const OMPNocontextClause *C) {
2505 Visitor->AddStmt(C->getCondition());
2508 void OMPClauseEnqueue::VisitOMPFilterClause(const OMPFilterClause *C) {
2509 VisitOMPClauseWithPreInit(C);
2510 Visitor->AddStmt(C->getThreadID());
2513 void OMPClauseEnqueue::VisitOMPAlignClause(const OMPAlignClause *C) {
2514 Visitor->AddStmt(C->getAlignment());
2517 void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2518 const OMPUnifiedAddressClause *) {}
2520 void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2521 const OMPUnifiedSharedMemoryClause *) {}
2523 void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2524 const OMPReverseOffloadClause *) {}
2526 void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2527 const OMPDynamicAllocatorsClause *) {}
2529 void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2530 const OMPAtomicDefaultMemOrderClause *) {}
2532 void OMPClauseEnqueue::VisitOMPAtClause(const OMPAtClause *) {}
2534 void OMPClauseEnqueue::VisitOMPSeverityClause(const OMPSeverityClause *) {}
2536 void OMPClauseEnqueue::VisitOMPMessageClause(const OMPMessageClause *) {}
2538 void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2539 Visitor->AddStmt(C->getDevice());
2542 void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
2543 VisitOMPClauseList(C);
2544 VisitOMPClauseWithPreInit(C);
2547 void OMPClauseEnqueue::VisitOMPThreadLimitClause(
2548 const OMPThreadLimitClause *C) {
2549 VisitOMPClauseList(C);
2550 VisitOMPClauseWithPreInit(C);
2553 void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2554 Visitor->AddStmt(C->getPriority());
2557 void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2558 Visitor->AddStmt(C->getGrainsize());
2561 void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2562 Visitor->AddStmt(C->getNumTasks());
2565 void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2566 Visitor->AddStmt(C->getHint());
2569 template <typename T> void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
2570 for (const auto *I : Node->varlist()) {
2571 Visitor->AddStmt(I);
2575 void OMPClauseEnqueue::VisitOMPInclusiveClause(const OMPInclusiveClause *C) {
2576 VisitOMPClauseList(C);
2578 void OMPClauseEnqueue::VisitOMPExclusiveClause(const OMPExclusiveClause *C) {
2579 VisitOMPClauseList(C);
2581 void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) {
2582 VisitOMPClauseList(C);
2583 Visitor->AddStmt(C->getAllocator());
2585 void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
2586 VisitOMPClauseList(C);
2587 for (const auto *E : C->private_copies()) {
2588 Visitor->AddStmt(E);
2591 void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2592 const OMPFirstprivateClause *C) {
2593 VisitOMPClauseList(C);
2594 VisitOMPClauseWithPreInit(C);
2595 for (const auto *E : C->private_copies()) {
2596 Visitor->AddStmt(E);
2598 for (const auto *E : C->inits()) {
2599 Visitor->AddStmt(E);
2602 void OMPClauseEnqueue::VisitOMPLastprivateClause(
2603 const OMPLastprivateClause *C) {
2604 VisitOMPClauseList(C);
2605 VisitOMPClauseWithPostUpdate(C);
2606 for (auto *E : C->private_copies()) {
2607 Visitor->AddStmt(E);
2609 for (auto *E : C->source_exprs()) {
2610 Visitor->AddStmt(E);
2612 for (auto *E : C->destination_exprs()) {
2613 Visitor->AddStmt(E);
2615 for (auto *E : C->assignment_ops()) {
2616 Visitor->AddStmt(E);
2619 void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
2620 VisitOMPClauseList(C);
2622 void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2623 VisitOMPClauseList(C);
2624 VisitOMPClauseWithPostUpdate(C);
2625 for (auto *E : C->privates()) {
2626 Visitor->AddStmt(E);
2628 for (auto *E : C->lhs_exprs()) {
2629 Visitor->AddStmt(E);
2631 for (auto *E : C->rhs_exprs()) {
2632 Visitor->AddStmt(E);
2634 for (auto *E : C->reduction_ops()) {
2635 Visitor->AddStmt(E);
2637 if (C->getModifier() == clang::OMPC_REDUCTION_inscan) {
2638 for (auto *E : C->copy_ops()) {
2639 Visitor->AddStmt(E);
2641 for (auto *E : C->copy_array_temps()) {
2642 Visitor->AddStmt(E);
2644 for (auto *E : C->copy_array_elems()) {
2645 Visitor->AddStmt(E);
2649 void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2650 const OMPTaskReductionClause *C) {
2651 VisitOMPClauseList(C);
2652 VisitOMPClauseWithPostUpdate(C);
2653 for (auto *E : C->privates()) {
2654 Visitor->AddStmt(E);
2656 for (auto *E : C->lhs_exprs()) {
2657 Visitor->AddStmt(E);
2659 for (auto *E : C->rhs_exprs()) {
2660 Visitor->AddStmt(E);
2662 for (auto *E : C->reduction_ops()) {
2663 Visitor->AddStmt(E);
2666 void OMPClauseEnqueue::VisitOMPInReductionClause(
2667 const OMPInReductionClause *C) {
2668 VisitOMPClauseList(C);
2669 VisitOMPClauseWithPostUpdate(C);
2670 for (auto *E : C->privates()) {
2671 Visitor->AddStmt(E);
2673 for (auto *E : C->lhs_exprs()) {
2674 Visitor->AddStmt(E);
2676 for (auto *E : C->rhs_exprs()) {
2677 Visitor->AddStmt(E);
2679 for (auto *E : C->reduction_ops()) {
2680 Visitor->AddStmt(E);
2682 for (auto *E : C->taskgroup_descriptors())
2683 Visitor->AddStmt(E);
2685 void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2686 VisitOMPClauseList(C);
2687 VisitOMPClauseWithPostUpdate(C);
2688 for (const auto *E : C->privates()) {
2689 Visitor->AddStmt(E);
2691 for (const auto *E : C->inits()) {
2692 Visitor->AddStmt(E);
2694 for (const auto *E : C->updates()) {
2695 Visitor->AddStmt(E);
2697 for (const auto *E : C->finals()) {
2698 Visitor->AddStmt(E);
2700 Visitor->AddStmt(C->getStep());
2701 Visitor->AddStmt(C->getCalcStep());
2703 void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2704 VisitOMPClauseList(C);
2705 Visitor->AddStmt(C->getAlignment());
2707 void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2708 VisitOMPClauseList(C);
2709 for (auto *E : C->source_exprs()) {
2710 Visitor->AddStmt(E);
2712 for (auto *E : C->destination_exprs()) {
2713 Visitor->AddStmt(E);
2715 for (auto *E : C->assignment_ops()) {
2716 Visitor->AddStmt(E);
2719 void OMPClauseEnqueue::VisitOMPCopyprivateClause(
2720 const OMPCopyprivateClause *C) {
2721 VisitOMPClauseList(C);
2722 for (auto *E : C->source_exprs()) {
2723 Visitor->AddStmt(E);
2725 for (auto *E : C->destination_exprs()) {
2726 Visitor->AddStmt(E);
2728 for (auto *E : C->assignment_ops()) {
2729 Visitor->AddStmt(E);
2732 void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2733 VisitOMPClauseList(C);
2735 void OMPClauseEnqueue::VisitOMPDepobjClause(const OMPDepobjClause *C) {
2736 Visitor->AddStmt(C->getDepobj());
2738 void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2739 VisitOMPClauseList(C);
2741 void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2742 VisitOMPClauseList(C);
2744 void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2745 const OMPDistScheduleClause *C) {
2746 VisitOMPClauseWithPreInit(C);
2747 Visitor->AddStmt(C->getChunkSize());
2749 void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2750 const OMPDefaultmapClause * /*C*/) {}
2751 void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2752 VisitOMPClauseList(C);
2754 void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2755 VisitOMPClauseList(C);
2757 void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(
2758 const OMPUseDevicePtrClause *C) {
2759 VisitOMPClauseList(C);
2761 void OMPClauseEnqueue::VisitOMPUseDeviceAddrClause(
2762 const OMPUseDeviceAddrClause *C) {
2763 VisitOMPClauseList(C);
2765 void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(
2766 const OMPIsDevicePtrClause *C) {
2767 VisitOMPClauseList(C);
2769 void OMPClauseEnqueue::VisitOMPHasDeviceAddrClause(
2770 const OMPHasDeviceAddrClause *C) {
2771 VisitOMPClauseList(C);
2773 void OMPClauseEnqueue::VisitOMPNontemporalClause(
2774 const OMPNontemporalClause *C) {
2775 VisitOMPClauseList(C);
2776 for (const auto *E : C->private_refs())
2777 Visitor->AddStmt(E);
2779 void OMPClauseEnqueue::VisitOMPOrderClause(const OMPOrderClause *C) {}
2780 void OMPClauseEnqueue::VisitOMPUsesAllocatorsClause(
2781 const OMPUsesAllocatorsClause *C) {
2782 for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
2783 const OMPUsesAllocatorsClause::Data &D = C->getAllocatorData(I);
2784 Visitor->AddStmt(D.Allocator);
2785 Visitor->AddStmt(D.AllocatorTraits);
2788 void OMPClauseEnqueue::VisitOMPAffinityClause(const OMPAffinityClause *C) {
2789 Visitor->AddStmt(C->getModifier());
2790 for (const Expr *E : C->varlist())
2791 Visitor->AddStmt(E);
2793 void OMPClauseEnqueue::VisitOMPBindClause(const OMPBindClause *C) {}
2794 void OMPClauseEnqueue::VisitOMPXDynCGroupMemClause(
2795 const OMPXDynCGroupMemClause *C) {
2796 VisitOMPClauseWithPreInit(C);
2797 Visitor->AddStmt(C->getSize());
2799 void OMPClauseEnqueue::VisitOMPDoacrossClause(const OMPDoacrossClause *C) {
2800 VisitOMPClauseList(C);
2802 void OMPClauseEnqueue::VisitOMPXAttributeClause(const OMPXAttributeClause *C) {
2804 void OMPClauseEnqueue::VisitOMPXBareClause(const OMPXBareClause *C) {}
2806 } // namespace
2808 void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2809 unsigned size = WL.size();
2810 OMPClauseEnqueue Visitor(this);
2811 Visitor.Visit(S);
2812 if (size == WL.size())
2813 return;
2814 // Now reverse the entries we just added. This will match the DFS
2815 // ordering performed by the worklist.
2816 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2817 std::reverse(I, E);
2820 namespace {
2821 class OpenACCClauseEnqueue : public OpenACCClauseVisitor<OpenACCClauseEnqueue> {
2822 EnqueueVisitor &Visitor;
2824 public:
2825 OpenACCClauseEnqueue(EnqueueVisitor &V) : Visitor(V) {}
2827 void VisitVarList(const OpenACCClauseWithVarList &C) {
2828 for (Expr *Var : C.getVarList())
2829 Visitor.AddStmt(Var);
2832 #define VISIT_CLAUSE(CLAUSE_NAME) \
2833 void Visit##CLAUSE_NAME##Clause(const OpenACC##CLAUSE_NAME##Clause &C);
2834 #include "clang/Basic/OpenACCClauses.def"
2837 void OpenACCClauseEnqueue::VisitDefaultClause(const OpenACCDefaultClause &C) {}
2838 void OpenACCClauseEnqueue::VisitIfClause(const OpenACCIfClause &C) {
2839 Visitor.AddStmt(C.getConditionExpr());
2841 void OpenACCClauseEnqueue::VisitSelfClause(const OpenACCSelfClause &C) {
2842 if (C.isConditionExprClause()) {
2843 if (C.hasConditionExpr())
2844 Visitor.AddStmt(C.getConditionExpr());
2845 } else {
2846 for (Expr *Var : C.getVarList())
2847 Visitor.AddStmt(Var);
2850 void OpenACCClauseEnqueue::VisitNumWorkersClause(
2851 const OpenACCNumWorkersClause &C) {
2852 Visitor.AddStmt(C.getIntExpr());
2854 void OpenACCClauseEnqueue::VisitDeviceNumClause(
2855 const OpenACCDeviceNumClause &C) {
2856 Visitor.AddStmt(C.getIntExpr());
2858 void OpenACCClauseEnqueue::VisitDefaultAsyncClause(
2859 const OpenACCDefaultAsyncClause &C) {
2860 Visitor.AddStmt(C.getIntExpr());
2862 void OpenACCClauseEnqueue::VisitVectorLengthClause(
2863 const OpenACCVectorLengthClause &C) {
2864 Visitor.AddStmt(C.getIntExpr());
2866 void OpenACCClauseEnqueue::VisitNumGangsClause(const OpenACCNumGangsClause &C) {
2867 for (Expr *IE : C.getIntExprs())
2868 Visitor.AddStmt(IE);
2871 void OpenACCClauseEnqueue::VisitTileClause(const OpenACCTileClause &C) {
2872 for (Expr *IE : C.getSizeExprs())
2873 Visitor.AddStmt(IE);
2876 void OpenACCClauseEnqueue::VisitPrivateClause(const OpenACCPrivateClause &C) {
2877 VisitVarList(C);
2880 void OpenACCClauseEnqueue::VisitHostClause(const OpenACCHostClause &C) {
2881 VisitVarList(C);
2884 void OpenACCClauseEnqueue::VisitDeviceClause(const OpenACCDeviceClause &C) {
2885 VisitVarList(C);
2888 void OpenACCClauseEnqueue::VisitFirstPrivateClause(
2889 const OpenACCFirstPrivateClause &C) {
2890 VisitVarList(C);
2893 void OpenACCClauseEnqueue::VisitPresentClause(const OpenACCPresentClause &C) {
2894 VisitVarList(C);
2896 void OpenACCClauseEnqueue::VisitNoCreateClause(const OpenACCNoCreateClause &C) {
2897 VisitVarList(C);
2899 void OpenACCClauseEnqueue::VisitCopyClause(const OpenACCCopyClause &C) {
2900 VisitVarList(C);
2902 void OpenACCClauseEnqueue::VisitCopyInClause(const OpenACCCopyInClause &C) {
2903 VisitVarList(C);
2905 void OpenACCClauseEnqueue::VisitCopyOutClause(const OpenACCCopyOutClause &C) {
2906 VisitVarList(C);
2908 void OpenACCClauseEnqueue::VisitCreateClause(const OpenACCCreateClause &C) {
2909 VisitVarList(C);
2911 void OpenACCClauseEnqueue::VisitAttachClause(const OpenACCAttachClause &C) {
2912 VisitVarList(C);
2915 void OpenACCClauseEnqueue::VisitDetachClause(const OpenACCDetachClause &C) {
2916 VisitVarList(C);
2918 void OpenACCClauseEnqueue::VisitDeleteClause(const OpenACCDeleteClause &C) {
2919 VisitVarList(C);
2922 void OpenACCClauseEnqueue::VisitUseDeviceClause(
2923 const OpenACCUseDeviceClause &C) {
2924 VisitVarList(C);
2927 void OpenACCClauseEnqueue::VisitDevicePtrClause(
2928 const OpenACCDevicePtrClause &C) {
2929 VisitVarList(C);
2931 void OpenACCClauseEnqueue::VisitAsyncClause(const OpenACCAsyncClause &C) {
2932 if (C.hasIntExpr())
2933 Visitor.AddStmt(C.getIntExpr());
2936 void OpenACCClauseEnqueue::VisitWorkerClause(const OpenACCWorkerClause &C) {
2937 if (C.hasIntExpr())
2938 Visitor.AddStmt(C.getIntExpr());
2941 void OpenACCClauseEnqueue::VisitVectorClause(const OpenACCVectorClause &C) {
2942 if (C.hasIntExpr())
2943 Visitor.AddStmt(C.getIntExpr());
2946 void OpenACCClauseEnqueue::VisitWaitClause(const OpenACCWaitClause &C) {
2947 if (const Expr *DevNumExpr = C.getDevNumExpr())
2948 Visitor.AddStmt(DevNumExpr);
2949 for (Expr *QE : C.getQueueIdExprs())
2950 Visitor.AddStmt(QE);
2952 void OpenACCClauseEnqueue::VisitDeviceTypeClause(
2953 const OpenACCDeviceTypeClause &C) {}
2954 void OpenACCClauseEnqueue::VisitReductionClause(
2955 const OpenACCReductionClause &C) {
2956 VisitVarList(C);
2958 void OpenACCClauseEnqueue::VisitAutoClause(const OpenACCAutoClause &C) {}
2959 void OpenACCClauseEnqueue::VisitIndependentClause(
2960 const OpenACCIndependentClause &C) {}
2961 void OpenACCClauseEnqueue::VisitSeqClause(const OpenACCSeqClause &C) {}
2962 void OpenACCClauseEnqueue::VisitFinalizeClause(const OpenACCFinalizeClause &C) {
2964 void OpenACCClauseEnqueue::VisitIfPresentClause(
2965 const OpenACCIfPresentClause &C) {}
2966 void OpenACCClauseEnqueue::VisitCollapseClause(const OpenACCCollapseClause &C) {
2967 Visitor.AddStmt(C.getLoopCount());
2969 void OpenACCClauseEnqueue::VisitGangClause(const OpenACCGangClause &C) {
2970 for (unsigned I = 0; I < C.getNumExprs(); ++I) {
2971 Visitor.AddStmt(C.getExpr(I).second);
2974 } // namespace
2976 void EnqueueVisitor::EnqueueChildren(const OpenACCClause *C) {
2977 unsigned size = WL.size();
2978 OpenACCClauseEnqueue Visitor(*this);
2979 Visitor.Visit(C);
2981 if (size == WL.size())
2982 return;
2983 // Now reverse the entries we just added. This will match the DFS
2984 // ordering performed by the worklist.
2985 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2986 std::reverse(I, E);
2989 void EnqueueVisitor::EnqueueChildren(const AnnotateAttr *A) {
2990 unsigned size = WL.size();
2991 for (const Expr *Arg : A->args()) {
2992 VisitStmt(Arg);
2994 if (size == WL.size())
2995 return;
2996 // Now reverse the entries we just added. This will match the DFS
2997 // ordering performed by the worklist.
2998 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2999 std::reverse(I, E);
3002 void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
3003 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
3005 void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
3006 AddDecl(B->getBlockDecl());
3008 void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
3009 EnqueueChildren(E);
3010 AddTypeLoc(E->getTypeSourceInfo());
3012 void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
3013 for (auto &I : llvm::reverse(S->body()))
3014 AddStmt(I);
3016 void EnqueueVisitor::VisitMSDependentExistsStmt(
3017 const MSDependentExistsStmt *S) {
3018 AddStmt(S->getSubStmt());
3019 AddDeclarationNameInfo(S);
3020 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
3021 AddNestedNameSpecifierLoc(QualifierLoc);
3024 void EnqueueVisitor::VisitCXXDependentScopeMemberExpr(
3025 const CXXDependentScopeMemberExpr *E) {
3026 if (E->hasExplicitTemplateArgs())
3027 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
3028 AddDeclarationNameInfo(E);
3029 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
3030 AddNestedNameSpecifierLoc(QualifierLoc);
3031 if (!E->isImplicitAccess())
3032 AddStmt(E->getBase());
3034 void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
3035 // Enqueue the initializer , if any.
3036 AddStmt(E->getInitializer());
3037 // Enqueue the array size, if any.
3038 AddStmt(E->getArraySize().value_or(nullptr));
3039 // Enqueue the allocated type.
3040 AddTypeLoc(E->getAllocatedTypeSourceInfo());
3041 // Enqueue the placement arguments.
3042 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
3043 AddStmt(E->getPlacementArg(I - 1));
3045 void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
3046 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
3047 AddStmt(CE->getArg(I - 1));
3048 AddStmt(CE->getCallee());
3049 AddStmt(CE->getArg(0));
3051 void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
3052 const CXXPseudoDestructorExpr *E) {
3053 // Visit the name of the type being destroyed.
3054 AddTypeLoc(E->getDestroyedTypeInfo());
3055 // Visit the scope type that looks disturbingly like the nested-name-specifier
3056 // but isn't.
3057 AddTypeLoc(E->getScopeTypeInfo());
3058 // Visit the nested-name-specifier.
3059 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
3060 AddNestedNameSpecifierLoc(QualifierLoc);
3061 // Visit base expression.
3062 AddStmt(E->getBase());
3064 void EnqueueVisitor::VisitCXXScalarValueInitExpr(
3065 const CXXScalarValueInitExpr *E) {
3066 AddTypeLoc(E->getTypeSourceInfo());
3068 void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
3069 const CXXTemporaryObjectExpr *E) {
3070 EnqueueChildren(E);
3071 AddTypeLoc(E->getTypeSourceInfo());
3073 void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
3074 EnqueueChildren(E);
3075 if (E->isTypeOperand())
3076 AddTypeLoc(E->getTypeOperandSourceInfo());
3079 void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
3080 const CXXUnresolvedConstructExpr *E) {
3081 EnqueueChildren(E);
3082 AddTypeLoc(E->getTypeSourceInfo());
3084 void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
3085 EnqueueChildren(E);
3086 if (E->isTypeOperand())
3087 AddTypeLoc(E->getTypeOperandSourceInfo());
3090 void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
3091 EnqueueChildren(S);
3092 AddDecl(S->getExceptionDecl());
3095 void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
3096 AddStmt(S->getBody());
3097 AddStmt(S->getRangeInit());
3098 AddDecl(S->getLoopVariable());
3101 void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
3102 if (DR->hasExplicitTemplateArgs())
3103 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
3104 WL.push_back(DeclRefExprParts(DR, Parent));
3106 void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
3107 const DependentScopeDeclRefExpr *E) {
3108 if (E->hasExplicitTemplateArgs())
3109 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
3110 AddDeclarationNameInfo(E);
3111 AddNestedNameSpecifierLoc(E->getQualifierLoc());
3113 void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
3114 unsigned size = WL.size();
3115 bool isFirst = true;
3116 for (const auto *D : S->decls()) {
3117 AddDecl(D, isFirst);
3118 isFirst = false;
3120 if (size == WL.size())
3121 return;
3122 // Now reverse the entries we just added. This will match the DFS
3123 // ordering performed by the worklist.
3124 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
3125 std::reverse(I, E);
3127 void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
3128 AddStmt(E->getInit());
3129 for (const DesignatedInitExpr::Designator &D :
3130 llvm::reverse(E->designators())) {
3131 if (D.isFieldDesignator()) {
3132 if (const FieldDecl *Field = D.getFieldDecl())
3133 AddMemberRef(Field, D.getFieldLoc());
3134 continue;
3136 if (D.isArrayDesignator()) {
3137 AddStmt(E->getArrayIndex(D));
3138 continue;
3140 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
3141 AddStmt(E->getArrayRangeEnd(D));
3142 AddStmt(E->getArrayRangeStart(D));
3145 void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
3146 EnqueueChildren(E);
3147 AddTypeLoc(E->getTypeInfoAsWritten());
3149 void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
3150 AddStmt(FS->getBody());
3151 AddStmt(FS->getInc());
3152 AddStmt(FS->getCond());
3153 AddDecl(FS->getConditionVariable());
3154 AddStmt(FS->getInit());
3156 void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
3157 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
3159 void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
3160 AddStmt(If->getElse());
3161 AddStmt(If->getThen());
3162 AddStmt(If->getCond());
3163 AddStmt(If->getInit());
3164 AddDecl(If->getConditionVariable());
3166 void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
3167 // We care about the syntactic form of the initializer list, only.
3168 if (InitListExpr *Syntactic = IE->getSyntacticForm())
3169 IE = Syntactic;
3170 EnqueueChildren(IE);
3172 void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
3173 WL.push_back(MemberExprParts(M, Parent));
3175 // If the base of the member access expression is an implicit 'this', don't
3176 // visit it.
3177 // FIXME: If we ever want to show these implicit accesses, this will be
3178 // unfortunate. However, clang_getCursor() relies on this behavior.
3179 if (M->isImplicitAccess())
3180 return;
3182 // Ignore base anonymous struct/union fields, otherwise they will shadow the
3183 // real field that we are interested in.
3184 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
3185 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
3186 if (FD->isAnonymousStructOrUnion()) {
3187 AddStmt(SubME->getBase());
3188 return;
3193 AddStmt(M->getBase());
3195 void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
3196 AddTypeLoc(E->getEncodedTypeSourceInfo());
3198 void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
3199 EnqueueChildren(M);
3200 AddTypeLoc(M->getClassReceiverTypeInfo());
3202 void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
3203 // Visit the components of the offsetof expression.
3204 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
3205 const OffsetOfNode &Node = E->getComponent(I - 1);
3206 switch (Node.getKind()) {
3207 case OffsetOfNode::Array:
3208 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
3209 break;
3210 case OffsetOfNode::Field:
3211 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
3212 break;
3213 case OffsetOfNode::Identifier:
3214 case OffsetOfNode::Base:
3215 continue;
3218 // Visit the type into which we're computing the offset.
3219 AddTypeLoc(E->getTypeSourceInfo());
3221 void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
3222 if (E->hasExplicitTemplateArgs())
3223 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
3224 WL.push_back(OverloadExprParts(E, Parent));
3226 void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
3227 const UnaryExprOrTypeTraitExpr *E) {
3228 EnqueueChildren(E);
3229 if (E->isArgumentType())
3230 AddTypeLoc(E->getArgumentTypeInfo());
3232 void EnqueueVisitor::VisitStmt(const Stmt *S) { EnqueueChildren(S); }
3233 void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
3234 AddStmt(S->getBody());
3235 AddStmt(S->getCond());
3236 AddDecl(S->getConditionVariable());
3239 void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
3240 AddStmt(W->getBody());
3241 AddStmt(W->getCond());
3242 AddDecl(W->getConditionVariable());
3245 void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
3246 for (unsigned I = E->getNumArgs(); I > 0; --I)
3247 AddTypeLoc(E->getArg(I - 1));
3250 void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3251 AddTypeLoc(E->getQueriedTypeSourceInfo());
3254 void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3255 EnqueueChildren(E);
3258 void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
3259 VisitOverloadExpr(U);
3260 if (!U->isImplicitAccess())
3261 AddStmt(U->getBase());
3263 void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
3264 AddStmt(E->getSubExpr());
3265 AddTypeLoc(E->getWrittenTypeInfo());
3267 void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
3268 WL.push_back(SizeOfPackExprParts(E, Parent));
3270 void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
3271 // If the opaque value has a source expression, just transparently
3272 // visit that. This is useful for (e.g.) pseudo-object expressions.
3273 if (Expr *SourceExpr = E->getSourceExpr())
3274 return ConstStmtVisitor::Visit(SourceExpr);
3276 void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
3277 AddStmt(E->getBody());
3278 WL.push_back(LambdaExprParts(E, Parent));
3280 void EnqueueVisitor::VisitConceptSpecializationExpr(
3281 const ConceptSpecializationExpr *E) {
3282 WL.push_back(ConceptSpecializationExprVisit(E, Parent));
3284 void EnqueueVisitor::VisitRequiresExpr(const RequiresExpr *E) {
3285 WL.push_back(RequiresExprVisit(E, Parent));
3286 for (ParmVarDecl *VD : E->getLocalParameters())
3287 AddDecl(VD);
3289 void EnqueueVisitor::VisitCXXParenListInitExpr(const CXXParenListInitExpr *E) {
3290 EnqueueChildren(E);
3292 void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
3293 // Treat the expression like its syntactic form.
3294 ConstStmtVisitor::Visit(E->getSyntacticForm());
3297 void EnqueueVisitor::VisitOMPExecutableDirective(
3298 const OMPExecutableDirective *D) {
3299 EnqueueChildren(D);
3300 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
3301 E = D->clauses().end();
3302 I != E; ++I)
3303 EnqueueChildren(*I);
3306 void EnqueueVisitor::VisitOMPLoopBasedDirective(
3307 const OMPLoopBasedDirective *D) {
3308 VisitOMPExecutableDirective(D);
3311 void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
3312 VisitOMPLoopBasedDirective(D);
3315 void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
3316 VisitOMPExecutableDirective(D);
3319 void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
3320 VisitOMPLoopDirective(D);
3323 void EnqueueVisitor::VisitOMPLoopTransformationDirective(
3324 const OMPLoopTransformationDirective *D) {
3325 VisitOMPLoopBasedDirective(D);
3328 void EnqueueVisitor::VisitOMPTileDirective(const OMPTileDirective *D) {
3329 VisitOMPLoopTransformationDirective(D);
3332 void EnqueueVisitor::VisitOMPUnrollDirective(const OMPUnrollDirective *D) {
3333 VisitOMPLoopTransformationDirective(D);
3336 void EnqueueVisitor::VisitOMPReverseDirective(const OMPReverseDirective *D) {
3337 VisitOMPLoopTransformationDirective(D);
3340 void EnqueueVisitor::VisitOMPInterchangeDirective(
3341 const OMPInterchangeDirective *D) {
3342 VisitOMPLoopTransformationDirective(D);
3345 void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
3346 VisitOMPLoopDirective(D);
3349 void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
3350 VisitOMPLoopDirective(D);
3353 void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
3354 VisitOMPExecutableDirective(D);
3357 void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
3358 VisitOMPExecutableDirective(D);
3361 void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
3362 VisitOMPExecutableDirective(D);
3365 void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
3366 VisitOMPExecutableDirective(D);
3369 void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
3370 VisitOMPExecutableDirective(D);
3371 AddDeclarationNameInfo(D);
3374 void EnqueueVisitor::VisitOMPParallelForDirective(
3375 const OMPParallelForDirective *D) {
3376 VisitOMPLoopDirective(D);
3379 void EnqueueVisitor::VisitOMPParallelForSimdDirective(
3380 const OMPParallelForSimdDirective *D) {
3381 VisitOMPLoopDirective(D);
3384 void EnqueueVisitor::VisitOMPParallelMasterDirective(
3385 const OMPParallelMasterDirective *D) {
3386 VisitOMPExecutableDirective(D);
3389 void EnqueueVisitor::VisitOMPParallelMaskedDirective(
3390 const OMPParallelMaskedDirective *D) {
3391 VisitOMPExecutableDirective(D);
3394 void EnqueueVisitor::VisitOMPParallelSectionsDirective(
3395 const OMPParallelSectionsDirective *D) {
3396 VisitOMPExecutableDirective(D);
3399 void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
3400 VisitOMPExecutableDirective(D);
3403 void EnqueueVisitor::VisitOMPTaskyieldDirective(
3404 const OMPTaskyieldDirective *D) {
3405 VisitOMPExecutableDirective(D);
3408 void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
3409 VisitOMPExecutableDirective(D);
3412 void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
3413 VisitOMPExecutableDirective(D);
3416 void EnqueueVisitor::VisitOMPAssumeDirective(const OMPAssumeDirective *D) {
3417 VisitOMPExecutableDirective(D);
3420 void EnqueueVisitor::VisitOMPErrorDirective(const OMPErrorDirective *D) {
3421 VisitOMPExecutableDirective(D);
3424 void EnqueueVisitor::VisitOMPTaskgroupDirective(
3425 const OMPTaskgroupDirective *D) {
3426 VisitOMPExecutableDirective(D);
3427 if (const Expr *E = D->getReductionRef())
3428 VisitStmt(E);
3431 void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
3432 VisitOMPExecutableDirective(D);
3435 void EnqueueVisitor::VisitOMPDepobjDirective(const OMPDepobjDirective *D) {
3436 VisitOMPExecutableDirective(D);
3439 void EnqueueVisitor::VisitOMPScanDirective(const OMPScanDirective *D) {
3440 VisitOMPExecutableDirective(D);
3443 void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
3444 VisitOMPExecutableDirective(D);
3447 void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
3448 VisitOMPExecutableDirective(D);
3451 void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
3452 VisitOMPExecutableDirective(D);
3455 void EnqueueVisitor::VisitOMPTargetDataDirective(
3456 const OMPTargetDataDirective *D) {
3457 VisitOMPExecutableDirective(D);
3460 void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
3461 const OMPTargetEnterDataDirective *D) {
3462 VisitOMPExecutableDirective(D);
3465 void EnqueueVisitor::VisitOMPTargetExitDataDirective(
3466 const OMPTargetExitDataDirective *D) {
3467 VisitOMPExecutableDirective(D);
3470 void EnqueueVisitor::VisitOMPTargetParallelDirective(
3471 const OMPTargetParallelDirective *D) {
3472 VisitOMPExecutableDirective(D);
3475 void EnqueueVisitor::VisitOMPTargetParallelForDirective(
3476 const OMPTargetParallelForDirective *D) {
3477 VisitOMPLoopDirective(D);
3480 void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
3481 VisitOMPExecutableDirective(D);
3484 void EnqueueVisitor::VisitOMPCancellationPointDirective(
3485 const OMPCancellationPointDirective *D) {
3486 VisitOMPExecutableDirective(D);
3489 void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
3490 VisitOMPExecutableDirective(D);
3493 void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
3494 VisitOMPLoopDirective(D);
3497 void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
3498 const OMPTaskLoopSimdDirective *D) {
3499 VisitOMPLoopDirective(D);
3502 void EnqueueVisitor::VisitOMPMasterTaskLoopDirective(
3503 const OMPMasterTaskLoopDirective *D) {
3504 VisitOMPLoopDirective(D);
3507 void EnqueueVisitor::VisitOMPMaskedTaskLoopDirective(
3508 const OMPMaskedTaskLoopDirective *D) {
3509 VisitOMPLoopDirective(D);
3512 void EnqueueVisitor::VisitOMPMasterTaskLoopSimdDirective(
3513 const OMPMasterTaskLoopSimdDirective *D) {
3514 VisitOMPLoopDirective(D);
3517 void EnqueueVisitor::VisitOMPMaskedTaskLoopSimdDirective(
3518 const OMPMaskedTaskLoopSimdDirective *D) {
3519 VisitOMPLoopDirective(D);
3522 void EnqueueVisitor::VisitOMPParallelMasterTaskLoopDirective(
3523 const OMPParallelMasterTaskLoopDirective *D) {
3524 VisitOMPLoopDirective(D);
3527 void EnqueueVisitor::VisitOMPParallelMaskedTaskLoopDirective(
3528 const OMPParallelMaskedTaskLoopDirective *D) {
3529 VisitOMPLoopDirective(D);
3532 void EnqueueVisitor::VisitOMPParallelMasterTaskLoopSimdDirective(
3533 const OMPParallelMasterTaskLoopSimdDirective *D) {
3534 VisitOMPLoopDirective(D);
3537 void EnqueueVisitor::VisitOMPParallelMaskedTaskLoopSimdDirective(
3538 const OMPParallelMaskedTaskLoopSimdDirective *D) {
3539 VisitOMPLoopDirective(D);
3542 void EnqueueVisitor::VisitOMPDistributeDirective(
3543 const OMPDistributeDirective *D) {
3544 VisitOMPLoopDirective(D);
3547 void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
3548 const OMPDistributeParallelForDirective *D) {
3549 VisitOMPLoopDirective(D);
3552 void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
3553 const OMPDistributeParallelForSimdDirective *D) {
3554 VisitOMPLoopDirective(D);
3557 void EnqueueVisitor::VisitOMPDistributeSimdDirective(
3558 const OMPDistributeSimdDirective *D) {
3559 VisitOMPLoopDirective(D);
3562 void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
3563 const OMPTargetParallelForSimdDirective *D) {
3564 VisitOMPLoopDirective(D);
3567 void EnqueueVisitor::VisitOMPTargetSimdDirective(
3568 const OMPTargetSimdDirective *D) {
3569 VisitOMPLoopDirective(D);
3572 void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
3573 const OMPTeamsDistributeDirective *D) {
3574 VisitOMPLoopDirective(D);
3577 void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
3578 const OMPTeamsDistributeSimdDirective *D) {
3579 VisitOMPLoopDirective(D);
3582 void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
3583 const OMPTeamsDistributeParallelForSimdDirective *D) {
3584 VisitOMPLoopDirective(D);
3587 void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
3588 const OMPTeamsDistributeParallelForDirective *D) {
3589 VisitOMPLoopDirective(D);
3592 void EnqueueVisitor::VisitOMPTargetTeamsDirective(
3593 const OMPTargetTeamsDirective *D) {
3594 VisitOMPExecutableDirective(D);
3597 void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
3598 const OMPTargetTeamsDistributeDirective *D) {
3599 VisitOMPLoopDirective(D);
3602 void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
3603 const OMPTargetTeamsDistributeParallelForDirective *D) {
3604 VisitOMPLoopDirective(D);
3607 void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
3608 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
3609 VisitOMPLoopDirective(D);
3612 void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
3613 const OMPTargetTeamsDistributeSimdDirective *D) {
3614 VisitOMPLoopDirective(D);
3617 void EnqueueVisitor::VisitOpenACCComputeConstruct(
3618 const OpenACCComputeConstruct *C) {
3619 EnqueueChildren(C);
3620 for (auto *Clause : C->clauses())
3621 EnqueueChildren(Clause);
3624 void EnqueueVisitor::VisitOpenACCLoopConstruct(const OpenACCLoopConstruct *C) {
3625 EnqueueChildren(C);
3626 for (auto *Clause : C->clauses())
3627 EnqueueChildren(Clause);
3630 void EnqueueVisitor::VisitOpenACCCombinedConstruct(
3631 const OpenACCCombinedConstruct *C) {
3632 EnqueueChildren(C);
3633 for (auto *Clause : C->clauses())
3634 EnqueueChildren(Clause);
3636 void EnqueueVisitor::VisitOpenACCDataConstruct(const OpenACCDataConstruct *C) {
3637 EnqueueChildren(C);
3638 for (auto *Clause : C->clauses())
3639 EnqueueChildren(Clause);
3641 void EnqueueVisitor::VisitOpenACCEnterDataConstruct(
3642 const OpenACCEnterDataConstruct *C) {
3643 EnqueueChildren(C);
3644 for (auto *Clause : C->clauses())
3645 EnqueueChildren(Clause);
3647 void EnqueueVisitor::VisitOpenACCExitDataConstruct(
3648 const OpenACCExitDataConstruct *C) {
3649 EnqueueChildren(C);
3650 for (auto *Clause : C->clauses())
3651 EnqueueChildren(Clause);
3653 void EnqueueVisitor::VisitOpenACCHostDataConstruct(
3654 const OpenACCHostDataConstruct *C) {
3655 EnqueueChildren(C);
3656 for (auto *Clause : C->clauses())
3657 EnqueueChildren(Clause);
3660 void EnqueueVisitor::VisitOpenACCWaitConstruct(const OpenACCWaitConstruct *C) {
3661 EnqueueChildren(C);
3662 for (auto *Clause : C->clauses())
3663 EnqueueChildren(Clause);
3666 void EnqueueVisitor::VisitOpenACCInitConstruct(const OpenACCInitConstruct *C) {
3667 EnqueueChildren(C);
3668 for (auto *Clause : C->clauses())
3669 EnqueueChildren(Clause);
3672 void EnqueueVisitor::VisitOpenACCShutdownConstruct(
3673 const OpenACCShutdownConstruct *C) {
3674 EnqueueChildren(C);
3675 for (auto *Clause : C->clauses())
3676 EnqueueChildren(Clause);
3679 void EnqueueVisitor::VisitOpenACCSetConstruct(const OpenACCSetConstruct *C) {
3680 EnqueueChildren(C);
3681 for (auto *Clause : C->clauses())
3682 EnqueueChildren(Clause);
3685 void EnqueueVisitor::VisitAnnotateAttr(const AnnotateAttr *A) {
3686 EnqueueChildren(A);
3689 void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
3690 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU, RegionOfInterest))
3691 .ConstStmtVisitor::Visit(S);
3694 void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Attr *A) {
3695 // Parent is the attribute itself when this is indirectly called from
3696 // VisitChildren. Because we need to make a CXCursor for A, we need *its*
3697 // parent.
3698 auto AttrCursor = Parent;
3700 // Get the attribute's parent as stored in
3701 // cxcursor::MakeCXCursor(const Attr *A, const Decl *Parent, CXTranslationUnit
3702 // TU)
3703 const Decl *AttrParent = static_cast<const Decl *>(AttrCursor.data[1]);
3705 EnqueueVisitor(WL, MakeCXCursor(A, AttrParent, TU))
3706 .ConstAttrVisitor::Visit(A);
3709 bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
3710 if (RegionOfInterest.isValid()) {
3711 SourceRange Range = getRawCursorExtent(C);
3712 if (Range.isInvalid() || CompareRegionOfInterest(Range))
3713 return false;
3715 return true;
3718 bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
3719 while (!WL.empty()) {
3720 // Dequeue the worklist item.
3721 VisitorJob LI = WL.pop_back_val();
3723 // Set the Parent field, then back to its old value once we're done.
3724 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
3726 switch (LI.getKind()) {
3727 case VisitorJob::DeclVisitKind: {
3728 const Decl *D = cast<DeclVisit>(&LI)->get();
3729 if (!D)
3730 continue;
3732 // For now, perform default visitation for Decls.
3733 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
3734 cast<DeclVisit>(&LI)->isFirst())))
3735 return true;
3737 continue;
3739 case VisitorJob::ExplicitTemplateArgsVisitKind: {
3740 for (const TemplateArgumentLoc &Arg :
3741 *cast<ExplicitTemplateArgsVisit>(&LI)) {
3742 if (VisitTemplateArgumentLoc(Arg))
3743 return true;
3745 continue;
3747 case VisitorJob::TypeLocVisitKind: {
3748 // Perform default visitation for TypeLocs.
3749 if (Visit(cast<TypeLocVisit>(&LI)->get()))
3750 return true;
3751 continue;
3753 case VisitorJob::LabelRefVisitKind: {
3754 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
3755 if (LabelStmt *stmt = LS->getStmt()) {
3756 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3757 TU))) {
3758 return true;
3761 continue;
3764 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3765 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3766 if (VisitNestedNameSpecifierLoc(V->get()))
3767 return true;
3768 continue;
3771 case VisitorJob::DeclarationNameInfoVisitKind: {
3772 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)->get()))
3773 return true;
3774 continue;
3776 case VisitorJob::MemberRefVisitKind: {
3777 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3778 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3779 return true;
3780 continue;
3782 case VisitorJob::StmtVisitKind: {
3783 const Stmt *S = cast<StmtVisit>(&LI)->get();
3784 if (!S)
3785 continue;
3787 // Update the current cursor.
3788 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3789 if (!IsInRegionOfInterest(Cursor))
3790 continue;
3791 switch (Visitor(Cursor, Parent, ClientData)) {
3792 case CXChildVisit_Break:
3793 return true;
3794 case CXChildVisit_Continue:
3795 break;
3796 case CXChildVisit_Recurse:
3797 if (PostChildrenVisitor)
3798 WL.push_back(PostChildrenVisit(nullptr, Cursor));
3799 EnqueueWorkList(WL, S);
3800 break;
3802 continue;
3804 case VisitorJob::MemberExprPartsKind: {
3805 // Handle the other pieces in the MemberExpr besides the base.
3806 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
3808 // Visit the nested-name-specifier
3809 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3810 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3811 return true;
3813 // Visit the declaration name.
3814 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3815 return true;
3817 // Visit the explicitly-specified template arguments, if any.
3818 if (M->hasExplicitTemplateArgs()) {
3819 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3820 *ArgEnd = Arg + M->getNumTemplateArgs();
3821 Arg != ArgEnd; ++Arg) {
3822 if (VisitTemplateArgumentLoc(*Arg))
3823 return true;
3826 continue;
3828 case VisitorJob::DeclRefExprPartsKind: {
3829 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
3830 // Visit nested-name-specifier, if present.
3831 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3832 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3833 return true;
3834 // Visit declaration name.
3835 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3836 return true;
3837 continue;
3839 case VisitorJob::OverloadExprPartsKind: {
3840 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
3841 // Visit the nested-name-specifier.
3842 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3843 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3844 return true;
3845 // Visit the declaration name.
3846 if (VisitDeclarationNameInfo(O->getNameInfo()))
3847 return true;
3848 // Visit the overloaded declaration reference.
3849 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3850 return true;
3851 continue;
3853 case VisitorJob::SizeOfPackExprPartsKind: {
3854 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
3855 NamedDecl *Pack = E->getPack();
3856 if (isa<TemplateTypeParmDecl>(Pack)) {
3857 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3858 E->getPackLoc(), TU)))
3859 return true;
3861 continue;
3864 if (isa<TemplateTemplateParmDecl>(Pack)) {
3865 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3866 E->getPackLoc(), TU)))
3867 return true;
3869 continue;
3872 // Non-type template parameter packs and function parameter packs are
3873 // treated like DeclRefExpr cursors.
3874 continue;
3877 case VisitorJob::LambdaExprPartsKind: {
3878 // Visit non-init captures.
3879 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
3880 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3881 CEnd = E->explicit_capture_end();
3882 C != CEnd; ++C) {
3883 if (!C->capturesVariable())
3884 continue;
3885 // TODO: handle structured bindings here ?
3886 if (!isa<VarDecl>(C->getCapturedVar()))
3887 continue;
3888 if (Visit(MakeCursorVariableRef(cast<VarDecl>(C->getCapturedVar()),
3889 C->getLocation(), TU)))
3890 return true;
3892 // Visit init captures
3893 for (auto InitExpr : E->capture_inits()) {
3894 if (InitExpr && Visit(InitExpr))
3895 return true;
3898 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3899 // Visit parameters and return type, if present.
3900 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3901 if (E->hasExplicitParameters()) {
3902 // Visit parameters.
3903 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3904 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
3905 return true;
3907 if (E->hasExplicitResultType()) {
3908 // Visit result type.
3909 if (Visit(Proto.getReturnLoc()))
3910 return true;
3913 break;
3916 case VisitorJob::ConceptSpecializationExprVisitKind: {
3917 const ConceptSpecializationExpr *E =
3918 cast<ConceptSpecializationExprVisit>(&LI)->get();
3919 if (NestedNameSpecifierLoc QualifierLoc =
3920 E->getNestedNameSpecifierLoc()) {
3921 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3922 return true;
3925 if (E->getNamedConcept() &&
3926 Visit(MakeCursorTemplateRef(E->getNamedConcept(),
3927 E->getConceptNameLoc(), TU)))
3928 return true;
3930 if (auto Args = E->getTemplateArgsAsWritten()) {
3931 for (const auto &Arg : Args->arguments()) {
3932 if (VisitTemplateArgumentLoc(Arg))
3933 return true;
3936 break;
3939 case VisitorJob::RequiresExprVisitKind: {
3940 const RequiresExpr *E = cast<RequiresExprVisit>(&LI)->get();
3941 for (const concepts::Requirement *R : E->getRequirements())
3942 VisitConceptRequirement(*R);
3943 break;
3946 case VisitorJob::PostChildrenVisitKind:
3947 if (PostChildrenVisitor(Parent, ClientData))
3948 return true;
3949 break;
3952 return false;
3955 bool CursorVisitor::Visit(const Stmt *S) {
3956 VisitorWorkList *WL = nullptr;
3957 if (!WorkListFreeList.empty()) {
3958 WL = WorkListFreeList.back();
3959 WL->clear();
3960 WorkListFreeList.pop_back();
3961 } else {
3962 WL = new VisitorWorkList();
3963 WorkListCache.push_back(WL);
3965 EnqueueWorkList(*WL, S);
3966 bool result = RunVisitorWorkList(*WL);
3967 WorkListFreeList.push_back(WL);
3968 return result;
3971 bool CursorVisitor::Visit(const Attr *A) {
3972 VisitorWorkList *WL = nullptr;
3973 if (!WorkListFreeList.empty()) {
3974 WL = WorkListFreeList.back();
3975 WL->clear();
3976 WorkListFreeList.pop_back();
3977 } else {
3978 WL = new VisitorWorkList();
3979 WorkListCache.push_back(WL);
3981 EnqueueWorkList(*WL, A);
3982 bool result = RunVisitorWorkList(*WL);
3983 WorkListFreeList.push_back(WL);
3984 return result;
3987 namespace {
3988 typedef SmallVector<SourceRange, 4> RefNamePieces;
3989 RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3990 const DeclarationNameInfo &NI, SourceRange QLoc,
3991 const SourceRange *TemplateArgsLoc = nullptr) {
3992 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3993 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3994 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3996 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3998 RefNamePieces Pieces;
4000 if (WantQualifier && QLoc.isValid())
4001 Pieces.push_back(QLoc);
4003 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
4004 Pieces.push_back(NI.getLoc());
4006 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
4007 Pieces.push_back(*TemplateArgsLoc);
4009 if (Kind == DeclarationName::CXXOperatorName) {
4010 Pieces.push_back(NI.getInfo().getCXXOperatorNameBeginLoc());
4011 Pieces.push_back(NI.getInfo().getCXXOperatorNameEndLoc());
4014 if (WantSinglePiece) {
4015 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
4016 Pieces.clear();
4017 Pieces.push_back(R);
4020 return Pieces;
4022 } // namespace
4024 //===----------------------------------------------------------------------===//
4025 // Misc. API hooks.
4026 //===----------------------------------------------------------------------===//
4028 namespace {
4029 struct RegisterFatalErrorHandler {
4030 RegisterFatalErrorHandler() {
4031 clang_install_aborting_llvm_fatal_error_handler();
4034 } // namespace
4036 static llvm::ManagedStatic<RegisterFatalErrorHandler>
4037 RegisterFatalErrorHandlerOnce;
4039 static CIndexer *clang_createIndex_Impl(
4040 int excludeDeclarationsFromPCH, int displayDiagnostics,
4041 unsigned char threadBackgroundPriorityForIndexing = CXChoice_Default,
4042 unsigned char threadBackgroundPriorityForEditing = CXChoice_Default) {
4043 // We use crash recovery to make some of our APIs more reliable, implicitly
4044 // enable it.
4045 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
4046 llvm::CrashRecoveryContext::Enable();
4048 // Look through the managed static to trigger construction of the managed
4049 // static which registers our fatal error handler. This ensures it is only
4050 // registered once.
4051 (void)*RegisterFatalErrorHandlerOnce;
4053 // Initialize targets for clang module support.
4054 llvm::InitializeAllTargets();
4055 llvm::InitializeAllTargetMCs();
4056 llvm::InitializeAllAsmPrinters();
4057 llvm::InitializeAllAsmParsers();
4059 CIndexer *CIdxr = new CIndexer();
4061 if (excludeDeclarationsFromPCH)
4062 CIdxr->setOnlyLocalDecls();
4063 if (displayDiagnostics)
4064 CIdxr->setDisplayDiagnostics();
4066 unsigned GlobalOptions = CIdxr->getCXGlobalOptFlags();
4067 const auto updateGlobalOption =
4068 [&GlobalOptions](unsigned char Policy, CXGlobalOptFlags Flag,
4069 const char *EnvironmentVariableName) {
4070 switch (Policy) {
4071 case CXChoice_Enabled:
4072 GlobalOptions |= Flag;
4073 break;
4074 case CXChoice_Disabled:
4075 GlobalOptions &= ~Flag;
4076 break;
4077 case CXChoice_Default:
4078 default: // Fall back to default behavior if Policy is unsupported.
4079 if (getenv(EnvironmentVariableName))
4080 GlobalOptions |= Flag;
4083 updateGlobalOption(threadBackgroundPriorityForIndexing,
4084 CXGlobalOpt_ThreadBackgroundPriorityForIndexing,
4085 "LIBCLANG_BGPRIO_INDEX");
4086 updateGlobalOption(threadBackgroundPriorityForEditing,
4087 CXGlobalOpt_ThreadBackgroundPriorityForEditing,
4088 "LIBCLANG_BGPRIO_EDIT");
4089 CIdxr->setCXGlobalOptFlags(GlobalOptions);
4091 return CIdxr;
4094 CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
4095 int displayDiagnostics) {
4096 return clang_createIndex_Impl(excludeDeclarationsFromPCH, displayDiagnostics);
4099 void clang_disposeIndex(CXIndex CIdx) {
4100 if (CIdx)
4101 delete static_cast<CIndexer *>(CIdx);
4104 CXIndex clang_createIndexWithOptions(const CXIndexOptions *options) {
4105 // Adding new options to struct CXIndexOptions:
4106 // 1. If no other new option has been added in the same libclang version,
4107 // sizeof(CXIndexOptions) must increase for versioning purposes.
4108 // 2. Options should be added at the end of the struct in order to seamlessly
4109 // support older struct versions. If options->Size < sizeof(CXIndexOptions),
4110 // don't attempt to read the missing options and rely on the default values of
4111 // recently added options being reasonable. For example:
4112 // if (options->Size >= offsetof(CXIndexOptions, RecentlyAddedMember))
4113 // do_something(options->RecentlyAddedMember);
4115 // An exception: if a new option is small enough, it can be squeezed into the
4116 // /*Reserved*/ bits in CXIndexOptions. Since the default value of each option
4117 // is guaranteed to be 0 and the callers are advised to zero out the struct,
4118 // programs built against older libclang versions would implicitly set the new
4119 // options to default values, which should keep the behavior of previous
4120 // libclang versions and thus be backward-compatible.
4122 // If options->Size > sizeof(CXIndexOptions), the user may have set an option
4123 // we can't handle, in which case we return nullptr to report failure.
4124 // Replace `!=` with `>` here to support older struct versions. `!=` has the
4125 // advantage of catching more usage bugs and no disadvantages while there is a
4126 // single supported struct version (the initial version).
4127 if (options->Size != sizeof(CXIndexOptions))
4128 return nullptr;
4129 CIndexer *const CIdxr = clang_createIndex_Impl(
4130 options->ExcludeDeclarationsFromPCH, options->DisplayDiagnostics,
4131 options->ThreadBackgroundPriorityForIndexing,
4132 options->ThreadBackgroundPriorityForEditing);
4133 CIdxr->setStorePreamblesInMemory(options->StorePreamblesInMemory);
4134 CIdxr->setPreambleStoragePath(options->PreambleStoragePath);
4135 CIdxr->setInvocationEmissionPath(options->InvocationEmissionPath);
4136 return CIdxr;
4139 void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
4140 if (CIdx)
4141 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
4144 unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
4145 if (CIdx)
4146 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
4147 return 0;
4150 void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
4151 const char *Path) {
4152 if (CIdx)
4153 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
4156 void clang_toggleCrashRecovery(unsigned isEnabled) {
4157 if (isEnabled)
4158 llvm::CrashRecoveryContext::Enable();
4159 else
4160 llvm::CrashRecoveryContext::Disable();
4163 CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
4164 const char *ast_filename) {
4165 CXTranslationUnit TU;
4166 enum CXErrorCode Result =
4167 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
4168 (void)Result;
4169 assert((TU && Result == CXError_Success) ||
4170 (!TU && Result != CXError_Success));
4171 return TU;
4174 enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
4175 const char *ast_filename,
4176 CXTranslationUnit *out_TU) {
4177 if (out_TU)
4178 *out_TU = nullptr;
4180 if (!CIdx || !ast_filename || !out_TU)
4181 return CXError_InvalidArguments;
4183 LOG_FUNC_SECTION { *Log << ast_filename; }
4185 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
4186 FileSystemOptions FileSystemOpts;
4187 auto HSOpts = std::make_shared<HeaderSearchOptions>();
4189 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
4190 CompilerInstance::createDiagnostics(*llvm::vfs::getRealFileSystem(),
4191 new DiagnosticOptions());
4192 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
4193 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
4194 ASTUnit::LoadEverything, Diags, FileSystemOpts, HSOpts,
4195 /*LangOpts=*/nullptr, CXXIdx->getOnlyLocalDecls(), CaptureDiagsKind::All,
4196 /*AllowASTWithCompilerErrors=*/true,
4197 /*UserFilesAreVolatile=*/true);
4198 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
4199 return *out_TU ? CXError_Success : CXError_Failure;
4202 unsigned clang_defaultEditingTranslationUnitOptions() {
4203 return CXTranslationUnit_PrecompiledPreamble |
4204 CXTranslationUnit_CacheCompletionResults;
4207 CXTranslationUnit clang_createTranslationUnitFromSourceFile(
4208 CXIndex CIdx, const char *source_filename, int num_command_line_args,
4209 const char *const *command_line_args, unsigned num_unsaved_files,
4210 struct CXUnsavedFile *unsaved_files) {
4211 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
4212 return clang_parseTranslationUnit(CIdx, source_filename, command_line_args,
4213 num_command_line_args, unsaved_files,
4214 num_unsaved_files, Options);
4217 static CXErrorCode
4218 clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
4219 const char *const *command_line_args,
4220 int num_command_line_args,
4221 ArrayRef<CXUnsavedFile> unsaved_files,
4222 unsigned options, CXTranslationUnit *out_TU) {
4223 // Set up the initial return values.
4224 if (out_TU)
4225 *out_TU = nullptr;
4227 // Check arguments.
4228 if (!CIdx || !out_TU)
4229 return CXError_InvalidArguments;
4231 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
4233 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
4234 setThreadBackgroundPriority();
4236 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
4237 bool CreatePreambleOnFirstParse =
4238 options & CXTranslationUnit_CreatePreambleOnFirstParse;
4239 // FIXME: Add a flag for modules.
4240 TranslationUnitKind TUKind = (options & (CXTranslationUnit_Incomplete |
4241 CXTranslationUnit_SingleFileParse))
4242 ? TU_Prefix
4243 : TU_Complete;
4244 bool CacheCodeCompletionResults =
4245 options & CXTranslationUnit_CacheCompletionResults;
4246 bool IncludeBriefCommentsInCodeCompletion =
4247 options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
4248 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
4249 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
4250 bool RetainExcludedCB =
4251 options & CXTranslationUnit_RetainExcludedConditionalBlocks;
4252 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
4253 if (options & CXTranslationUnit_SkipFunctionBodies) {
4254 SkipFunctionBodies =
4255 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
4256 ? SkipFunctionBodiesScope::Preamble
4257 : SkipFunctionBodiesScope::PreambleAndMainFile;
4260 // Configure the diagnostics.
4261 std::unique_ptr<DiagnosticOptions> DiagOpts = CreateAndPopulateDiagOpts(
4262 llvm::ArrayRef(command_line_args, num_command_line_args));
4263 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
4264 CompilerInstance::createDiagnostics(*llvm::vfs::getRealFileSystem(),
4265 DiagOpts.release()));
4267 if (options & CXTranslationUnit_KeepGoing)
4268 Diags->setFatalsAsError(true);
4270 CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::All;
4271 if (options & CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles)
4272 CaptureDiagnostics = CaptureDiagsKind::AllWithoutNonErrorsFromIncludes;
4274 // Recover resources if we crash before exiting this function.
4275 llvm::CrashRecoveryContextCleanupRegistrar<
4276 DiagnosticsEngine,
4277 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
4278 DiagCleanup(Diags.get());
4280 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4281 new std::vector<ASTUnit::RemappedFile>());
4283 // Recover resources if we crash before exiting this function.
4284 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<ASTUnit::RemappedFile>>
4285 RemappedCleanup(RemappedFiles.get());
4287 for (auto &UF : unsaved_files) {
4288 std::unique_ptr<llvm::MemoryBuffer> MB =
4289 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
4290 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
4293 std::unique_ptr<std::vector<const char *>> Args(
4294 new std::vector<const char *>());
4296 // Recover resources if we crash before exiting this method.
4297 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char *>>
4298 ArgsCleanup(Args.get());
4300 // Since the Clang C library is primarily used by batch tools dealing with
4301 // (often very broken) source code, where spell-checking can have a
4302 // significant negative impact on performance (particularly when
4303 // precompiled headers are involved), we disable it by default.
4304 // Only do this if we haven't found a spell-checking-related argument.
4305 bool FoundSpellCheckingArgument = false;
4306 for (int I = 0; I != num_command_line_args; ++I) {
4307 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
4308 strcmp(command_line_args[I], "-fspell-checking") == 0) {
4309 FoundSpellCheckingArgument = true;
4310 break;
4313 Args->insert(Args->end(), command_line_args,
4314 command_line_args + num_command_line_args);
4316 if (!FoundSpellCheckingArgument)
4317 Args->insert(Args->begin() + 1, "-fno-spell-checking");
4319 // The 'source_filename' argument is optional. If the caller does not
4320 // specify it then it is assumed that the source file is specified
4321 // in the actual argument list.
4322 // Put the source file after command_line_args otherwise if '-x' flag is
4323 // present it will be unused.
4324 if (source_filename)
4325 Args->push_back(source_filename);
4327 // Do we need the detailed preprocessing record?
4328 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
4329 Args->push_back("-Xclang");
4330 Args->push_back("-detailed-preprocessing-record");
4333 // Suppress any editor placeholder diagnostics.
4334 Args->push_back("-fallow-editor-placeholders");
4336 unsigned NumErrors = Diags->getClient()->getNumErrors();
4337 std::unique_ptr<ASTUnit> ErrUnit;
4338 // Unless the user specified that they want the preamble on the first parse
4339 // set it up to be created on the first reparse. This makes the first parse
4340 // faster, trading for a slower (first) reparse.
4341 unsigned PrecompilePreambleAfterNParses =
4342 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
4344 LibclangInvocationReporter InvocationReporter(
4345 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
4346 options, llvm::ArrayRef(*Args), /*InvocationArgs=*/{}, unsaved_files);
4347 std::unique_ptr<ASTUnit> Unit = ASTUnit::LoadFromCommandLine(
4348 Args->data(), Args->data() + Args->size(),
4349 CXXIdx->getPCHContainerOperations(), Diags,
4350 CXXIdx->getClangResourcesPath(), CXXIdx->getStorePreamblesInMemory(),
4351 CXXIdx->getPreambleStoragePath(), CXXIdx->getOnlyLocalDecls(),
4352 CaptureDiagnostics, *RemappedFiles.get(),
4353 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
4354 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
4355 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
4356 /*UserFilesAreVolatile=*/true, ForSerialization, RetainExcludedCB,
4357 CXXIdx->getPCHContainerOperations()->getRawReader().getFormats().front(),
4358 &ErrUnit);
4360 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
4361 if (!Unit && !ErrUnit)
4362 return CXError_ASTReadError;
4364 if (NumErrors != Diags->getClient()->getNumErrors()) {
4365 // Make sure to check that 'Unit' is non-NULL.
4366 if (CXXIdx->getDisplayDiagnostics())
4367 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
4370 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
4371 return CXError_ASTReadError;
4373 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
4374 if (CXTranslationUnitImpl *TU = *out_TU) {
4375 TU->ParsingOptions = options;
4376 TU->Arguments.reserve(Args->size());
4377 for (const char *Arg : *Args)
4378 TU->Arguments.push_back(Arg);
4379 return CXError_Success;
4381 return CXError_Failure;
4384 CXTranslationUnit
4385 clang_parseTranslationUnit(CXIndex CIdx, const char *source_filename,
4386 const char *const *command_line_args,
4387 int num_command_line_args,
4388 struct CXUnsavedFile *unsaved_files,
4389 unsigned num_unsaved_files, unsigned options) {
4390 CXTranslationUnit TU;
4391 enum CXErrorCode Result = clang_parseTranslationUnit2(
4392 CIdx, source_filename, command_line_args, num_command_line_args,
4393 unsaved_files, num_unsaved_files, options, &TU);
4394 (void)Result;
4395 assert((TU && Result == CXError_Success) ||
4396 (!TU && Result != CXError_Success));
4397 return TU;
4400 enum CXErrorCode clang_parseTranslationUnit2(
4401 CXIndex CIdx, const char *source_filename,
4402 const char *const *command_line_args, int num_command_line_args,
4403 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
4404 unsigned options, CXTranslationUnit *out_TU) {
4405 noteBottomOfStack();
4406 SmallVector<const char *, 4> Args;
4407 Args.push_back("clang");
4408 Args.append(command_line_args, command_line_args + num_command_line_args);
4409 return clang_parseTranslationUnit2FullArgv(
4410 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
4411 num_unsaved_files, options, out_TU);
4414 enum CXErrorCode clang_parseTranslationUnit2FullArgv(
4415 CXIndex CIdx, const char *source_filename,
4416 const char *const *command_line_args, int num_command_line_args,
4417 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
4418 unsigned options, CXTranslationUnit *out_TU) {
4419 LOG_FUNC_SECTION {
4420 *Log << source_filename << ": ";
4421 for (int i = 0; i != num_command_line_args; ++i)
4422 *Log << command_line_args[i] << " ";
4425 if (num_unsaved_files && !unsaved_files)
4426 return CXError_InvalidArguments;
4428 CXErrorCode result = CXError_Failure;
4429 auto ParseTranslationUnitImpl = [=, &result] {
4430 noteBottomOfStack();
4431 result = clang_parseTranslationUnit_Impl(
4432 CIdx, source_filename, command_line_args, num_command_line_args,
4433 llvm::ArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
4436 llvm::CrashRecoveryContext CRC;
4438 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
4439 fprintf(stderr, "libclang: crash detected during parsing: {\n");
4440 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
4441 fprintf(stderr, " 'command_line_args' : [");
4442 for (int i = 0; i != num_command_line_args; ++i) {
4443 if (i)
4444 fprintf(stderr, ", ");
4445 fprintf(stderr, "'%s'", command_line_args[i]);
4447 fprintf(stderr, "],\n");
4448 fprintf(stderr, " 'unsaved_files' : [");
4449 for (unsigned i = 0; i != num_unsaved_files; ++i) {
4450 if (i)
4451 fprintf(stderr, ", ");
4452 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
4453 unsaved_files[i].Length);
4455 fprintf(stderr, "],\n");
4456 fprintf(stderr, " 'options' : %d,\n", options);
4457 fprintf(stderr, "}\n");
4459 return CXError_Crashed;
4460 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4461 if (CXTranslationUnit *TU = out_TU)
4462 PrintLibclangResourceUsage(*TU);
4465 return result;
4468 CXString clang_Type_getObjCEncoding(CXType CT) {
4469 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
4470 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
4471 std::string encoding;
4472 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]), encoding);
4474 return cxstring::createDup(encoding);
4477 static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
4478 if (C.kind == CXCursor_MacroDefinition) {
4479 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
4480 return MDR->getName();
4481 } else if (C.kind == CXCursor_MacroExpansion) {
4482 MacroExpansionCursor ME = getCursorMacroExpansion(C);
4483 return ME.getName();
4485 return nullptr;
4488 unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
4489 const IdentifierInfo *II = getMacroIdentifier(C);
4490 if (!II) {
4491 return false;
4493 ASTUnit *ASTU = getCursorASTUnit(C);
4494 Preprocessor &PP = ASTU->getPreprocessor();
4495 if (const MacroInfo *MI = PP.getMacroInfo(II))
4496 return MI->isFunctionLike();
4497 return false;
4500 unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
4501 const IdentifierInfo *II = getMacroIdentifier(C);
4502 if (!II) {
4503 return false;
4505 ASTUnit *ASTU = getCursorASTUnit(C);
4506 Preprocessor &PP = ASTU->getPreprocessor();
4507 if (const MacroInfo *MI = PP.getMacroInfo(II))
4508 return MI->isBuiltinMacro();
4509 return false;
4512 unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
4513 const Decl *D = getCursorDecl(C);
4514 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
4515 if (!FD) {
4516 return false;
4518 return FD->isInlined();
4521 static StringLiteral *getCFSTR_value(CallExpr *callExpr) {
4522 if (callExpr->getNumArgs() != 1) {
4523 return nullptr;
4526 StringLiteral *S = nullptr;
4527 auto *arg = callExpr->getArg(0);
4528 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
4529 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
4530 auto *subExpr = I->getSubExprAsWritten();
4532 if (subExpr->getStmtClass() != Stmt::StringLiteralClass) {
4533 return nullptr;
4536 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
4537 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
4538 S = static_cast<StringLiteral *>(callExpr->getArg(0));
4539 } else {
4540 return nullptr;
4542 return S;
4545 struct ExprEvalResult {
4546 CXEvalResultKind EvalType;
4547 union {
4548 unsigned long long unsignedVal;
4549 long long intVal;
4550 double floatVal;
4551 char *stringVal;
4552 } EvalData;
4553 bool IsUnsignedInt;
4554 ~ExprEvalResult() {
4555 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
4556 EvalType != CXEval_Int) {
4557 delete[] EvalData.stringVal;
4562 void clang_EvalResult_dispose(CXEvalResult E) {
4563 delete static_cast<ExprEvalResult *>(E);
4566 CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
4567 if (!E) {
4568 return CXEval_UnExposed;
4570 return ((ExprEvalResult *)E)->EvalType;
4573 int clang_EvalResult_getAsInt(CXEvalResult E) {
4574 return clang_EvalResult_getAsLongLong(E);
4577 long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
4578 if (!E) {
4579 return 0;
4581 ExprEvalResult *Result = (ExprEvalResult *)E;
4582 if (Result->IsUnsignedInt)
4583 return Result->EvalData.unsignedVal;
4584 return Result->EvalData.intVal;
4587 unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
4588 return ((ExprEvalResult *)E)->IsUnsignedInt;
4591 unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
4592 if (!E) {
4593 return 0;
4596 ExprEvalResult *Result = (ExprEvalResult *)E;
4597 if (Result->IsUnsignedInt)
4598 return Result->EvalData.unsignedVal;
4599 return Result->EvalData.intVal;
4602 double clang_EvalResult_getAsDouble(CXEvalResult E) {
4603 if (!E) {
4604 return 0;
4606 return ((ExprEvalResult *)E)->EvalData.floatVal;
4609 const char *clang_EvalResult_getAsStr(CXEvalResult E) {
4610 if (!E) {
4611 return nullptr;
4613 return ((ExprEvalResult *)E)->EvalData.stringVal;
4616 static const ExprEvalResult *evaluateExpr(Expr *expr, CXCursor C) {
4617 Expr::EvalResult ER;
4618 ASTContext &ctx = getCursorContext(C);
4619 if (!expr)
4620 return nullptr;
4622 expr = expr->IgnoreParens();
4623 if (expr->isValueDependent())
4624 return nullptr;
4625 if (!expr->EvaluateAsRValue(ER, ctx))
4626 return nullptr;
4628 QualType rettype;
4629 CallExpr *callExpr;
4630 auto result = std::make_unique<ExprEvalResult>();
4631 result->EvalType = CXEval_UnExposed;
4632 result->IsUnsignedInt = false;
4634 if (ER.Val.isInt()) {
4635 result->EvalType = CXEval_Int;
4637 auto &val = ER.Val.getInt();
4638 if (val.isUnsigned()) {
4639 result->IsUnsignedInt = true;
4640 result->EvalData.unsignedVal = val.getZExtValue();
4641 } else {
4642 result->EvalData.intVal = val.getExtValue();
4645 return result.release();
4648 if (ER.Val.isFloat()) {
4649 llvm::SmallVector<char, 100> Buffer;
4650 ER.Val.getFloat().toString(Buffer);
4651 std::string floatStr(Buffer.data(), Buffer.size());
4652 result->EvalType = CXEval_Float;
4653 bool ignored;
4654 llvm::APFloat apFloat = ER.Val.getFloat();
4655 apFloat.convert(llvm::APFloat::IEEEdouble(),
4656 llvm::APFloat::rmNearestTiesToEven, &ignored);
4657 result->EvalData.floatVal = apFloat.convertToDouble();
4658 return result.release();
4661 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
4662 const auto *I = cast<ImplicitCastExpr>(expr);
4663 auto *subExpr = I->getSubExprAsWritten();
4664 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
4665 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
4666 const StringLiteral *StrE = nullptr;
4667 const ObjCStringLiteral *ObjCExpr;
4668 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
4670 if (ObjCExpr) {
4671 StrE = ObjCExpr->getString();
4672 result->EvalType = CXEval_ObjCStrLiteral;
4673 } else {
4674 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
4675 result->EvalType = CXEval_StrLiteral;
4678 std::string strRef(StrE->getString().str());
4679 result->EvalData.stringVal = new char[strRef.size() + 1];
4680 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
4681 strRef.size());
4682 result->EvalData.stringVal[strRef.size()] = '\0';
4683 return result.release();
4685 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
4686 expr->getStmtClass() == Stmt::StringLiteralClass) {
4687 const StringLiteral *StrE = nullptr;
4688 const ObjCStringLiteral *ObjCExpr;
4689 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
4691 if (ObjCExpr) {
4692 StrE = ObjCExpr->getString();
4693 result->EvalType = CXEval_ObjCStrLiteral;
4694 } else {
4695 StrE = cast<StringLiteral>(expr);
4696 result->EvalType = CXEval_StrLiteral;
4699 std::string strRef(StrE->getString().str());
4700 result->EvalData.stringVal = new char[strRef.size() + 1];
4701 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
4702 result->EvalData.stringVal[strRef.size()] = '\0';
4703 return result.release();
4706 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
4707 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
4709 rettype = CC->getType();
4710 if (rettype.getAsString() == "CFStringRef" &&
4711 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
4713 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
4714 StringLiteral *S = getCFSTR_value(callExpr);
4715 if (S) {
4716 std::string strLiteral(S->getString().str());
4717 result->EvalType = CXEval_CFStr;
4719 result->EvalData.stringVal = new char[strLiteral.size() + 1];
4720 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
4721 strLiteral.size());
4722 result->EvalData.stringVal[strLiteral.size()] = '\0';
4723 return result.release();
4727 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
4728 callExpr = static_cast<CallExpr *>(expr);
4729 rettype = callExpr->getCallReturnType(ctx);
4731 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
4732 return nullptr;
4734 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
4735 if (callExpr->getNumArgs() == 1 &&
4736 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
4737 return nullptr;
4738 } else if (rettype.getAsString() == "CFStringRef") {
4740 StringLiteral *S = getCFSTR_value(callExpr);
4741 if (S) {
4742 std::string strLiteral(S->getString().str());
4743 result->EvalType = CXEval_CFStr;
4744 result->EvalData.stringVal = new char[strLiteral.size() + 1];
4745 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
4746 strLiteral.size());
4747 result->EvalData.stringVal[strLiteral.size()] = '\0';
4748 return result.release();
4751 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
4752 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
4753 ValueDecl *V = D->getDecl();
4754 if (V->getKind() == Decl::Function) {
4755 std::string strName = V->getNameAsString();
4756 result->EvalType = CXEval_Other;
4757 result->EvalData.stringVal = new char[strName.size() + 1];
4758 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
4759 result->EvalData.stringVal[strName.size()] = '\0';
4760 return result.release();
4764 return nullptr;
4767 static const Expr *evaluateDeclExpr(const Decl *D) {
4768 if (!D)
4769 return nullptr;
4770 if (auto *Var = dyn_cast<VarDecl>(D))
4771 return Var->getInit();
4772 else if (auto *Field = dyn_cast<FieldDecl>(D))
4773 return Field->getInClassInitializer();
4774 return nullptr;
4777 static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
4778 assert(CS && "invalid compound statement");
4779 for (auto *bodyIterator : CS->body()) {
4780 if (const auto *E = dyn_cast<Expr>(bodyIterator))
4781 return E;
4783 return nullptr;
4786 CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
4787 const Expr *E = nullptr;
4788 if (clang_getCursorKind(C) == CXCursor_CompoundStmt)
4789 E = evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)));
4790 else if (clang_isDeclaration(C.kind))
4791 E = evaluateDeclExpr(getCursorDecl(C));
4792 else if (clang_isExpression(C.kind))
4793 E = getCursorExpr(C);
4794 if (E)
4795 return const_cast<CXEvalResult>(
4796 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
4797 return nullptr;
4800 unsigned clang_Cursor_hasAttrs(CXCursor C) {
4801 const Decl *D = getCursorDecl(C);
4802 if (!D) {
4803 return 0;
4806 if (D->hasAttrs()) {
4807 return 1;
4810 return 0;
4812 unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
4813 return CXSaveTranslationUnit_None;
4816 static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
4817 const char *FileName,
4818 unsigned options) {
4819 CIndexer *CXXIdx = TU->CIdx;
4820 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
4821 setThreadBackgroundPriority();
4823 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
4824 return hadError ? CXSaveError_Unknown : CXSaveError_None;
4827 int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
4828 unsigned options) {
4829 LOG_FUNC_SECTION { *Log << TU << ' ' << FileName; }
4831 if (isNotUsableTU(TU)) {
4832 LOG_BAD_TU(TU);
4833 return CXSaveError_InvalidTU;
4836 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4837 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4838 if (!CXXUnit->hasSema())
4839 return CXSaveError_InvalidTU;
4841 CXSaveError result;
4842 auto SaveTranslationUnitImpl = [=, &result]() {
4843 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
4846 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
4847 SaveTranslationUnitImpl();
4849 if (getenv("LIBCLANG_RESOURCE_USAGE"))
4850 PrintLibclangResourceUsage(TU);
4852 return result;
4855 // We have an AST that has invalid nodes due to compiler errors.
4856 // Use a crash recovery thread for protection.
4858 llvm::CrashRecoveryContext CRC;
4860 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
4861 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
4862 fprintf(stderr, " 'filename' : '%s'\n", FileName);
4863 fprintf(stderr, " 'options' : %d,\n", options);
4864 fprintf(stderr, "}\n");
4866 return CXSaveError_Unknown;
4868 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4869 PrintLibclangResourceUsage(TU);
4872 return result;
4875 void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4876 if (CTUnit) {
4877 // If the translation unit has been marked as unsafe to free, just discard
4878 // it.
4879 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4880 if (Unit && Unit->isUnsafeToFree())
4881 return;
4883 delete cxtu::getASTUnit(CTUnit);
4884 delete CTUnit->StringPool;
4885 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4886 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
4887 delete CTUnit->CommentToXML;
4888 delete CTUnit;
4892 unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4893 if (CTUnit) {
4894 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4896 if (Unit && Unit->isUnsafeToFree())
4897 return false;
4899 Unit->ResetForParse();
4900 return true;
4903 return false;
4906 unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4907 return CXReparse_None;
4910 static CXErrorCode
4911 clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4912 ArrayRef<CXUnsavedFile> unsaved_files,
4913 unsigned options) {
4914 // Check arguments.
4915 if (isNotUsableTU(TU)) {
4916 LOG_BAD_TU(TU);
4917 return CXError_InvalidArguments;
4920 // Reset the associated diagnostics.
4921 delete static_cast<CXDiagnosticSetImpl *>(TU->Diagnostics);
4922 TU->Diagnostics = nullptr;
4924 CIndexer *CXXIdx = TU->CIdx;
4925 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4926 setThreadBackgroundPriority();
4928 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4929 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4931 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4932 new std::vector<ASTUnit::RemappedFile>());
4934 // Recover resources if we crash before exiting this function.
4935 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<ASTUnit::RemappedFile>>
4936 RemappedCleanup(RemappedFiles.get());
4938 for (auto &UF : unsaved_files) {
4939 std::unique_ptr<llvm::MemoryBuffer> MB =
4940 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
4941 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
4944 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4945 *RemappedFiles.get()))
4946 return CXError_Success;
4947 if (isASTReadError(CXXUnit))
4948 return CXError_ASTReadError;
4949 return CXError_Failure;
4952 int clang_reparseTranslationUnit(CXTranslationUnit TU,
4953 unsigned num_unsaved_files,
4954 struct CXUnsavedFile *unsaved_files,
4955 unsigned options) {
4956 LOG_FUNC_SECTION { *Log << TU; }
4958 if (num_unsaved_files && !unsaved_files)
4959 return CXError_InvalidArguments;
4961 CXErrorCode result;
4962 auto ReparseTranslationUnitImpl = [=, &result]() {
4963 result = clang_reparseTranslationUnit_Impl(
4964 TU, llvm::ArrayRef(unsaved_files, num_unsaved_files), options);
4967 llvm::CrashRecoveryContext CRC;
4969 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
4970 fprintf(stderr, "libclang: crash detected during reparsing\n");
4971 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
4972 return CXError_Crashed;
4973 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4974 PrintLibclangResourceUsage(TU);
4976 return result;
4979 CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
4980 if (isNotUsableTU(CTUnit)) {
4981 LOG_BAD_TU(CTUnit);
4982 return cxstring::createEmpty();
4985 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4986 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
4989 CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
4990 if (isNotUsableTU(TU)) {
4991 LOG_BAD_TU(TU);
4992 return clang_getNullCursor();
4995 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4996 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4999 CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
5000 if (isNotUsableTU(CTUnit)) {
5001 LOG_BAD_TU(CTUnit);
5002 return nullptr;
5005 CXTargetInfoImpl *impl = new CXTargetInfoImpl();
5006 impl->TranslationUnit = CTUnit;
5007 return impl;
5010 CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
5011 if (!TargetInfo)
5012 return cxstring::createEmpty();
5014 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
5015 assert(!isNotUsableTU(CTUnit) &&
5016 "Unexpected unusable translation unit in TargetInfo");
5018 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
5019 std::string Triple =
5020 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
5021 return cxstring::createDup(Triple);
5024 int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
5025 if (!TargetInfo)
5026 return -1;
5028 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
5029 assert(!isNotUsableTU(CTUnit) &&
5030 "Unexpected unusable translation unit in TargetInfo");
5032 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
5033 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
5036 void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
5037 if (!TargetInfo)
5038 return;
5040 delete TargetInfo;
5043 //===----------------------------------------------------------------------===//
5044 // CXFile Operations.
5045 //===----------------------------------------------------------------------===//
5047 CXString clang_getFileName(CXFile SFile) {
5048 if (!SFile)
5049 return cxstring::createNull();
5051 FileEntryRef FEnt = *cxfile::getFileEntryRef(SFile);
5052 return cxstring::createRef(FEnt.getName());
5055 time_t clang_getFileTime(CXFile SFile) {
5056 if (!SFile)
5057 return 0;
5059 FileEntryRef FEnt = *cxfile::getFileEntryRef(SFile);
5060 return FEnt.getModificationTime();
5063 CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
5064 if (isNotUsableTU(TU)) {
5065 LOG_BAD_TU(TU);
5066 return nullptr;
5069 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5071 FileManager &FMgr = CXXUnit->getFileManager();
5072 return cxfile::makeCXFile(FMgr.getOptionalFileRef(file_name));
5075 const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
5076 size_t *size) {
5077 if (isNotUsableTU(TU)) {
5078 LOG_BAD_TU(TU);
5079 return nullptr;
5082 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
5083 FileID fid = SM.translateFile(*cxfile::getFileEntryRef(file));
5084 std::optional<llvm::MemoryBufferRef> buf = SM.getBufferOrNone(fid);
5085 if (!buf) {
5086 if (size)
5087 *size = 0;
5088 return nullptr;
5090 if (size)
5091 *size = buf->getBufferSize();
5092 return buf->getBufferStart();
5095 unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU, CXFile file) {
5096 if (isNotUsableTU(TU)) {
5097 LOG_BAD_TU(TU);
5098 return 0;
5101 if (!file)
5102 return 0;
5104 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5105 FileEntryRef FEnt = *cxfile::getFileEntryRef(file);
5106 return CXXUnit->getPreprocessor()
5107 .getHeaderSearchInfo()
5108 .isFileMultipleIncludeGuarded(FEnt);
5111 int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
5112 if (!file || !outID)
5113 return 1;
5115 FileEntryRef FEnt = *cxfile::getFileEntryRef(file);
5116 const llvm::sys::fs::UniqueID &ID = FEnt.getUniqueID();
5117 outID->data[0] = ID.getDevice();
5118 outID->data[1] = ID.getFile();
5119 outID->data[2] = FEnt.getModificationTime();
5120 return 0;
5123 int clang_File_isEqual(CXFile file1, CXFile file2) {
5124 if (file1 == file2)
5125 return true;
5127 if (!file1 || !file2)
5128 return false;
5130 FileEntryRef FEnt1 = *cxfile::getFileEntryRef(file1);
5131 FileEntryRef FEnt2 = *cxfile::getFileEntryRef(file2);
5132 return FEnt1.getUniqueID() == FEnt2.getUniqueID();
5135 CXString clang_File_tryGetRealPathName(CXFile SFile) {
5136 if (!SFile)
5137 return cxstring::createNull();
5139 FileEntryRef FEnt = *cxfile::getFileEntryRef(SFile);
5140 return cxstring::createRef(FEnt.getFileEntry().tryGetRealPathName());
5143 //===----------------------------------------------------------------------===//
5144 // CXCursor Operations.
5145 //===----------------------------------------------------------------------===//
5147 static const Decl *getDeclFromExpr(const Stmt *E) {
5148 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
5149 return getDeclFromExpr(CE->getSubExpr());
5151 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
5152 return RefExpr->getDecl();
5153 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5154 return ME->getMemberDecl();
5155 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
5156 return RE->getDecl();
5157 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
5158 if (PRE->isExplicitProperty())
5159 return PRE->getExplicitProperty();
5160 // It could be messaging both getter and setter as in:
5161 // ++myobj.myprop;
5162 // in which case prefer to associate the setter since it is less obvious
5163 // from inspecting the source that the setter is going to get called.
5164 if (PRE->isMessagingSetter())
5165 return PRE->getImplicitPropertySetter();
5166 return PRE->getImplicitPropertyGetter();
5168 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
5169 return getDeclFromExpr(POE->getSyntacticForm());
5170 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5171 if (Expr *Src = OVE->getSourceExpr())
5172 return getDeclFromExpr(Src);
5174 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
5175 return getDeclFromExpr(CE->getCallee());
5176 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
5177 if (!CE->isElidable())
5178 return CE->getConstructor();
5179 if (const CXXInheritedCtorInitExpr *CE =
5180 dyn_cast<CXXInheritedCtorInitExpr>(E))
5181 return CE->getConstructor();
5182 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
5183 return OME->getMethodDecl();
5185 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
5186 return PE->getProtocol();
5187 if (const SubstNonTypeTemplateParmPackExpr *NTTP =
5188 dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
5189 return NTTP->getParameterPack();
5190 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
5191 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
5192 isa<ParmVarDecl>(SizeOfPack->getPack()))
5193 return SizeOfPack->getPack();
5195 return nullptr;
5198 static SourceLocation getLocationFromExpr(const Expr *E) {
5199 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
5200 return getLocationFromExpr(CE->getSubExpr());
5202 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
5203 return /*FIXME:*/ Msg->getLeftLoc();
5204 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5205 return DRE->getLocation();
5206 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
5207 return Member->getMemberLoc();
5208 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
5209 return Ivar->getLocation();
5210 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
5211 return SizeOfPack->getPackLoc();
5212 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
5213 return PropRef->getLocation();
5215 return E->getBeginLoc();
5218 extern "C" {
5220 unsigned clang_visitChildren(CXCursor parent, CXCursorVisitor visitor,
5221 CXClientData client_data) {
5222 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
5223 /*VisitPreprocessorLast=*/false);
5224 return CursorVis.VisitChildren(parent);
5227 #ifndef __has_feature
5228 #define __has_feature(x) 0
5229 #endif
5230 #if __has_feature(blocks)
5231 typedef enum CXChildVisitResult (^CXCursorVisitorBlock)(CXCursor cursor,
5232 CXCursor parent);
5234 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
5235 CXClientData client_data) {
5236 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
5237 return block(cursor, parent);
5239 #else
5240 // If we are compiled with a compiler that doesn't have native blocks support,
5241 // define and call the block manually, so the
5242 typedef struct _CXChildVisitResult {
5243 void *isa;
5244 int flags;
5245 int reserved;
5246 enum CXChildVisitResult (*invoke)(struct _CXChildVisitResult *, CXCursor,
5247 CXCursor);
5248 } * CXCursorVisitorBlock;
5250 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
5251 CXClientData client_data) {
5252 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
5253 return block->invoke(block, cursor, parent);
5255 #endif
5257 unsigned clang_visitChildrenWithBlock(CXCursor parent,
5258 CXCursorVisitorBlock block) {
5259 return clang_visitChildren(parent, visitWithBlock, block);
5262 static CXString getDeclSpelling(const Decl *D) {
5263 if (!D)
5264 return cxstring::createEmpty();
5266 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5267 if (!ND) {
5268 if (const ObjCPropertyImplDecl *PropImpl =
5269 dyn_cast<ObjCPropertyImplDecl>(D))
5270 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
5271 return cxstring::createDup(Property->getIdentifier()->getName());
5273 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
5274 if (Module *Mod = ImportD->getImportedModule())
5275 return cxstring::createDup(Mod->getFullModuleName());
5277 return cxstring::createEmpty();
5280 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
5281 return cxstring::createDup(OMD->getSelector().getAsString());
5283 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
5284 // No, this isn't the same as the code below. getIdentifier() is non-virtual
5285 // and returns different names. NamedDecl returns the class name and
5286 // ObjCCategoryImplDecl returns the category name.
5287 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
5289 if (isa<UsingDirectiveDecl>(D))
5290 return cxstring::createEmpty();
5292 SmallString<1024> S;
5293 llvm::raw_svector_ostream os(S);
5294 ND->printName(os);
5296 return cxstring::createDup(os.str());
5299 CXString clang_getCursorSpelling(CXCursor C) {
5300 if (clang_isTranslationUnit(C.kind))
5301 return clang_getTranslationUnitSpelling(getCursorTU(C));
5303 if (clang_isReference(C.kind)) {
5304 switch (C.kind) {
5305 case CXCursor_ObjCSuperClassRef: {
5306 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
5307 return cxstring::createRef(Super->getIdentifier()->getNameStart());
5309 case CXCursor_ObjCClassRef: {
5310 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
5311 return cxstring::createRef(Class->getIdentifier()->getNameStart());
5313 case CXCursor_ObjCProtocolRef: {
5314 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
5315 assert(OID && "getCursorSpelling(): Missing protocol decl");
5316 return cxstring::createRef(OID->getIdentifier()->getNameStart());
5318 case CXCursor_CXXBaseSpecifier: {
5319 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
5320 return cxstring::createDup(B->getType().getAsString());
5322 case CXCursor_TypeRef: {
5323 const TypeDecl *Type = getCursorTypeRef(C).first;
5324 assert(Type && "Missing type decl");
5326 return cxstring::createDup(
5327 getCursorContext(C).getTypeDeclType(Type).getAsString());
5329 case CXCursor_TemplateRef: {
5330 const TemplateDecl *Template = getCursorTemplateRef(C).first;
5331 assert(Template && "Missing template decl");
5333 return cxstring::createDup(Template->getNameAsString());
5336 case CXCursor_NamespaceRef: {
5337 const NamedDecl *NS = getCursorNamespaceRef(C).first;
5338 assert(NS && "Missing namespace decl");
5340 return cxstring::createDup(NS->getNameAsString());
5343 case CXCursor_MemberRef: {
5344 const FieldDecl *Field = getCursorMemberRef(C).first;
5345 assert(Field && "Missing member decl");
5347 return cxstring::createDup(Field->getNameAsString());
5350 case CXCursor_LabelRef: {
5351 const LabelStmt *Label = getCursorLabelRef(C).first;
5352 assert(Label && "Missing label");
5354 return cxstring::createRef(Label->getName());
5357 case CXCursor_OverloadedDeclRef: {
5358 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
5359 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
5360 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
5361 return cxstring::createDup(ND->getNameAsString());
5362 return cxstring::createEmpty();
5364 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
5365 return cxstring::createDup(E->getName().getAsString());
5366 OverloadedTemplateStorage *Ovl =
5367 cast<OverloadedTemplateStorage *>(Storage);
5368 if (Ovl->size() == 0)
5369 return cxstring::createEmpty();
5370 return cxstring::createDup((*Ovl->begin())->getNameAsString());
5373 case CXCursor_VariableRef: {
5374 const VarDecl *Var = getCursorVariableRef(C).first;
5375 assert(Var && "Missing variable decl");
5377 return cxstring::createDup(Var->getNameAsString());
5380 default:
5381 return cxstring::createRef("<not implemented>");
5385 if (clang_isExpression(C.kind)) {
5386 const Expr *E = getCursorExpr(C);
5388 if (C.kind == CXCursor_ObjCStringLiteral ||
5389 C.kind == CXCursor_StringLiteral) {
5390 const StringLiteral *SLit;
5391 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
5392 SLit = OSL->getString();
5393 } else {
5394 SLit = cast<StringLiteral>(E);
5396 SmallString<256> Buf;
5397 llvm::raw_svector_ostream OS(Buf);
5398 SLit->outputString(OS);
5399 return cxstring::createDup(OS.str());
5402 if (C.kind == CXCursor_BinaryOperator ||
5403 C.kind == CXCursor_CompoundAssignOperator) {
5404 return clang_Cursor_getBinaryOpcodeStr(clang_Cursor_getBinaryOpcode(C));
5407 const Decl *D = getDeclFromExpr(getCursorExpr(C));
5408 if (D)
5409 return getDeclSpelling(D);
5410 return cxstring::createEmpty();
5413 if (clang_isStatement(C.kind)) {
5414 const Stmt *S = getCursorStmt(C);
5415 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
5416 return cxstring::createRef(Label->getName());
5418 return cxstring::createEmpty();
5421 if (C.kind == CXCursor_MacroExpansion)
5422 return cxstring::createRef(
5423 getCursorMacroExpansion(C).getName()->getNameStart());
5425 if (C.kind == CXCursor_MacroDefinition)
5426 return cxstring::createRef(
5427 getCursorMacroDefinition(C)->getName()->getNameStart());
5429 if (C.kind == CXCursor_InclusionDirective)
5430 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
5432 if (clang_isDeclaration(C.kind))
5433 return getDeclSpelling(getCursorDecl(C));
5435 if (C.kind == CXCursor_AnnotateAttr) {
5436 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
5437 return cxstring::createDup(AA->getAnnotation());
5440 if (C.kind == CXCursor_AsmLabelAttr) {
5441 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
5442 return cxstring::createDup(AA->getLabel());
5445 if (C.kind == CXCursor_PackedAttr) {
5446 return cxstring::createRef("packed");
5449 if (C.kind == CXCursor_VisibilityAttr) {
5450 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
5451 switch (AA->getVisibility()) {
5452 case VisibilityAttr::VisibilityType::Default:
5453 return cxstring::createRef("default");
5454 case VisibilityAttr::VisibilityType::Hidden:
5455 return cxstring::createRef("hidden");
5456 case VisibilityAttr::VisibilityType::Protected:
5457 return cxstring::createRef("protected");
5459 llvm_unreachable("unknown visibility type");
5462 return cxstring::createEmpty();
5465 CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C, unsigned pieceIndex,
5466 unsigned options) {
5467 if (clang_Cursor_isNull(C))
5468 return clang_getNullRange();
5470 ASTContext &Ctx = getCursorContext(C);
5472 if (clang_isStatement(C.kind)) {
5473 const Stmt *S = getCursorStmt(C);
5474 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
5475 if (pieceIndex > 0)
5476 return clang_getNullRange();
5477 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
5480 return clang_getNullRange();
5483 if (C.kind == CXCursor_ObjCMessageExpr) {
5484 if (const ObjCMessageExpr *ME =
5485 dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
5486 if (pieceIndex >= ME->getNumSelectorLocs())
5487 return clang_getNullRange();
5488 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
5492 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
5493 C.kind == CXCursor_ObjCClassMethodDecl) {
5494 if (const ObjCMethodDecl *MD =
5495 dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
5496 if (pieceIndex >= MD->getNumSelectorLocs())
5497 return clang_getNullRange();
5498 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
5502 if (C.kind == CXCursor_ObjCCategoryDecl ||
5503 C.kind == CXCursor_ObjCCategoryImplDecl) {
5504 if (pieceIndex > 0)
5505 return clang_getNullRange();
5506 if (const ObjCCategoryDecl *CD =
5507 dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
5508 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
5509 if (const ObjCCategoryImplDecl *CID =
5510 dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
5511 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
5514 if (C.kind == CXCursor_ModuleImportDecl) {
5515 if (pieceIndex > 0)
5516 return clang_getNullRange();
5517 if (const ImportDecl *ImportD =
5518 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
5519 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
5520 if (!Locs.empty())
5521 return cxloc::translateSourceRange(
5522 Ctx, SourceRange(Locs.front(), Locs.back()));
5524 return clang_getNullRange();
5527 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
5528 C.kind == CXCursor_ConversionFunction ||
5529 C.kind == CXCursor_FunctionDecl) {
5530 if (pieceIndex > 0)
5531 return clang_getNullRange();
5532 if (const FunctionDecl *FD =
5533 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
5534 DeclarationNameInfo FunctionName = FD->getNameInfo();
5535 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
5537 return clang_getNullRange();
5540 // FIXME: A CXCursor_InclusionDirective should give the location of the
5541 // filename, but we don't keep track of this.
5543 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
5544 // but we don't keep track of this.
5546 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
5547 // but we don't keep track of this.
5549 // Default handling, give the location of the cursor.
5551 if (pieceIndex > 0)
5552 return clang_getNullRange();
5554 CXSourceLocation CXLoc = clang_getCursorLocation(C);
5555 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
5556 return cxloc::translateSourceRange(Ctx, Loc);
5559 CXString clang_Cursor_getMangling(CXCursor C) {
5560 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
5561 return cxstring::createEmpty();
5563 // Mangling only works for functions and variables.
5564 const Decl *D = getCursorDecl(C);
5565 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
5566 return cxstring::createEmpty();
5568 ASTContext &Ctx = D->getASTContext();
5569 ASTNameGenerator ASTNameGen(Ctx);
5570 return cxstring::createDup(ASTNameGen.getName(D));
5573 CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
5574 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
5575 return nullptr;
5577 const Decl *D = getCursorDecl(C);
5578 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
5579 return nullptr;
5581 ASTContext &Ctx = D->getASTContext();
5582 ASTNameGenerator ASTNameGen(Ctx);
5583 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
5584 return cxstring::createSet(Manglings);
5587 CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
5588 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
5589 return nullptr;
5591 const Decl *D = getCursorDecl(C);
5592 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
5593 return nullptr;
5595 ASTContext &Ctx = D->getASTContext();
5596 ASTNameGenerator ASTNameGen(Ctx);
5597 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
5598 return cxstring::createSet(Manglings);
5601 CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
5602 if (clang_Cursor_isNull(C))
5603 return nullptr;
5604 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
5607 void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
5608 if (Policy)
5609 delete static_cast<PrintingPolicy *>(Policy);
5612 unsigned
5613 clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
5614 enum CXPrintingPolicyProperty Property) {
5615 if (!Policy)
5616 return 0;
5618 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
5619 switch (Property) {
5620 case CXPrintingPolicy_Indentation:
5621 return P->Indentation;
5622 case CXPrintingPolicy_SuppressSpecifiers:
5623 return P->SuppressSpecifiers;
5624 case CXPrintingPolicy_SuppressTagKeyword:
5625 return P->SuppressTagKeyword;
5626 case CXPrintingPolicy_IncludeTagDefinition:
5627 return P->IncludeTagDefinition;
5628 case CXPrintingPolicy_SuppressScope:
5629 return P->SuppressScope;
5630 case CXPrintingPolicy_SuppressUnwrittenScope:
5631 return P->SuppressUnwrittenScope;
5632 case CXPrintingPolicy_SuppressInitializers:
5633 return P->SuppressInitializers;
5634 case CXPrintingPolicy_ConstantArraySizeAsWritten:
5635 return P->ConstantArraySizeAsWritten;
5636 case CXPrintingPolicy_AnonymousTagLocations:
5637 return P->AnonymousTagLocations;
5638 case CXPrintingPolicy_SuppressStrongLifetime:
5639 return P->SuppressStrongLifetime;
5640 case CXPrintingPolicy_SuppressLifetimeQualifiers:
5641 return P->SuppressLifetimeQualifiers;
5642 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
5643 return P->SuppressTemplateArgsInCXXConstructors;
5644 case CXPrintingPolicy_Bool:
5645 return P->Bool;
5646 case CXPrintingPolicy_Restrict:
5647 return P->Restrict;
5648 case CXPrintingPolicy_Alignof:
5649 return P->Alignof;
5650 case CXPrintingPolicy_UnderscoreAlignof:
5651 return P->UnderscoreAlignof;
5652 case CXPrintingPolicy_UseVoidForZeroParams:
5653 return P->UseVoidForZeroParams;
5654 case CXPrintingPolicy_TerseOutput:
5655 return P->TerseOutput;
5656 case CXPrintingPolicy_PolishForDeclaration:
5657 return P->PolishForDeclaration;
5658 case CXPrintingPolicy_Half:
5659 return P->Half;
5660 case CXPrintingPolicy_MSWChar:
5661 return P->MSWChar;
5662 case CXPrintingPolicy_IncludeNewlines:
5663 return P->IncludeNewlines;
5664 case CXPrintingPolicy_MSVCFormatting:
5665 return P->MSVCFormatting;
5666 case CXPrintingPolicy_ConstantsAsWritten:
5667 return P->ConstantsAsWritten;
5668 case CXPrintingPolicy_SuppressImplicitBase:
5669 return P->SuppressImplicitBase;
5670 case CXPrintingPolicy_FullyQualifiedName:
5671 return P->FullyQualifiedName;
5674 assert(false && "Invalid CXPrintingPolicyProperty");
5675 return 0;
5678 void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
5679 enum CXPrintingPolicyProperty Property,
5680 unsigned Value) {
5681 if (!Policy)
5682 return;
5684 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
5685 switch (Property) {
5686 case CXPrintingPolicy_Indentation:
5687 P->Indentation = Value;
5688 return;
5689 case CXPrintingPolicy_SuppressSpecifiers:
5690 P->SuppressSpecifiers = Value;
5691 return;
5692 case CXPrintingPolicy_SuppressTagKeyword:
5693 P->SuppressTagKeyword = Value;
5694 return;
5695 case CXPrintingPolicy_IncludeTagDefinition:
5696 P->IncludeTagDefinition = Value;
5697 return;
5698 case CXPrintingPolicy_SuppressScope:
5699 P->SuppressScope = Value;
5700 return;
5701 case CXPrintingPolicy_SuppressUnwrittenScope:
5702 P->SuppressUnwrittenScope = Value;
5703 return;
5704 case CXPrintingPolicy_SuppressInitializers:
5705 P->SuppressInitializers = Value;
5706 return;
5707 case CXPrintingPolicy_ConstantArraySizeAsWritten:
5708 P->ConstantArraySizeAsWritten = Value;
5709 return;
5710 case CXPrintingPolicy_AnonymousTagLocations:
5711 P->AnonymousTagLocations = Value;
5712 return;
5713 case CXPrintingPolicy_SuppressStrongLifetime:
5714 P->SuppressStrongLifetime = Value;
5715 return;
5716 case CXPrintingPolicy_SuppressLifetimeQualifiers:
5717 P->SuppressLifetimeQualifiers = Value;
5718 return;
5719 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
5720 P->SuppressTemplateArgsInCXXConstructors = Value;
5721 return;
5722 case CXPrintingPolicy_Bool:
5723 P->Bool = Value;
5724 return;
5725 case CXPrintingPolicy_Restrict:
5726 P->Restrict = Value;
5727 return;
5728 case CXPrintingPolicy_Alignof:
5729 P->Alignof = Value;
5730 return;
5731 case CXPrintingPolicy_UnderscoreAlignof:
5732 P->UnderscoreAlignof = Value;
5733 return;
5734 case CXPrintingPolicy_UseVoidForZeroParams:
5735 P->UseVoidForZeroParams = Value;
5736 return;
5737 case CXPrintingPolicy_TerseOutput:
5738 P->TerseOutput = Value;
5739 return;
5740 case CXPrintingPolicy_PolishForDeclaration:
5741 P->PolishForDeclaration = Value;
5742 return;
5743 case CXPrintingPolicy_Half:
5744 P->Half = Value;
5745 return;
5746 case CXPrintingPolicy_MSWChar:
5747 P->MSWChar = Value;
5748 return;
5749 case CXPrintingPolicy_IncludeNewlines:
5750 P->IncludeNewlines = Value;
5751 return;
5752 case CXPrintingPolicy_MSVCFormatting:
5753 P->MSVCFormatting = Value;
5754 return;
5755 case CXPrintingPolicy_ConstantsAsWritten:
5756 P->ConstantsAsWritten = Value;
5757 return;
5758 case CXPrintingPolicy_SuppressImplicitBase:
5759 P->SuppressImplicitBase = Value;
5760 return;
5761 case CXPrintingPolicy_FullyQualifiedName:
5762 P->FullyQualifiedName = Value;
5763 return;
5766 assert(false && "Invalid CXPrintingPolicyProperty");
5769 CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
5770 if (clang_Cursor_isNull(C))
5771 return cxstring::createEmpty();
5773 if (clang_isDeclaration(C.kind)) {
5774 const Decl *D = getCursorDecl(C);
5775 if (!D)
5776 return cxstring::createEmpty();
5778 SmallString<128> Str;
5779 llvm::raw_svector_ostream OS(Str);
5780 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
5781 D->print(OS, UserPolicy ? *UserPolicy
5782 : getCursorContext(C).getPrintingPolicy());
5784 return cxstring::createDup(OS.str());
5787 return cxstring::createEmpty();
5790 CXString clang_getCursorDisplayName(CXCursor C) {
5791 if (!clang_isDeclaration(C.kind))
5792 return clang_getCursorSpelling(C);
5794 const Decl *D = getCursorDecl(C);
5795 if (!D)
5796 return cxstring::createEmpty();
5798 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
5799 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
5800 D = FunTmpl->getTemplatedDecl();
5802 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
5803 SmallString<64> Str;
5804 llvm::raw_svector_ostream OS(Str);
5805 OS << *Function;
5806 if (Function->getPrimaryTemplate())
5807 OS << "<>";
5808 OS << "(";
5809 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
5810 if (I)
5811 OS << ", ";
5812 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
5815 if (Function->isVariadic()) {
5816 if (Function->getNumParams())
5817 OS << ", ";
5818 OS << "...";
5820 OS << ")";
5821 return cxstring::createDup(OS.str());
5824 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
5825 SmallString<64> Str;
5826 llvm::raw_svector_ostream OS(Str);
5827 OS << *ClassTemplate;
5828 OS << "<";
5829 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
5830 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
5831 if (I)
5832 OS << ", ";
5834 NamedDecl *Param = Params->getParam(I);
5835 if (Param->getIdentifier()) {
5836 OS << Param->getIdentifier()->getName();
5837 continue;
5840 // There is no parameter name, which makes this tricky. Try to come up
5841 // with something useful that isn't too long.
5842 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5843 if (const auto *TC = TTP->getTypeConstraint()) {
5844 TC->getConceptNameInfo().printName(OS, Policy);
5845 if (TC->hasExplicitTemplateArgs())
5846 OS << "<...>";
5847 } else
5848 OS << (TTP->wasDeclaredWithTypename() ? "typename" : "class");
5849 else if (NonTypeTemplateParmDecl *NTTP =
5850 dyn_cast<NonTypeTemplateParmDecl>(Param))
5851 OS << NTTP->getType().getAsString(Policy);
5852 else
5853 OS << "template<...> class";
5856 OS << ">";
5857 return cxstring::createDup(OS.str());
5860 if (const ClassTemplateSpecializationDecl *ClassSpec =
5861 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
5862 SmallString<128> Str;
5863 llvm::raw_svector_ostream OS(Str);
5864 OS << *ClassSpec;
5865 // If the template arguments were written explicitly, use them..
5866 if (const auto *ArgsWritten = ClassSpec->getTemplateArgsAsWritten()) {
5867 printTemplateArgumentList(
5868 OS, ArgsWritten->arguments(), Policy,
5869 ClassSpec->getSpecializedTemplate()->getTemplateParameters());
5870 } else {
5871 printTemplateArgumentList(
5872 OS, ClassSpec->getTemplateArgs().asArray(), Policy,
5873 ClassSpec->getSpecializedTemplate()->getTemplateParameters());
5875 return cxstring::createDup(OS.str());
5878 return clang_getCursorSpelling(C);
5881 CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5882 switch (Kind) {
5883 case CXCursor_FunctionDecl:
5884 return cxstring::createRef("FunctionDecl");
5885 case CXCursor_TypedefDecl:
5886 return cxstring::createRef("TypedefDecl");
5887 case CXCursor_EnumDecl:
5888 return cxstring::createRef("EnumDecl");
5889 case CXCursor_EnumConstantDecl:
5890 return cxstring::createRef("EnumConstantDecl");
5891 case CXCursor_StructDecl:
5892 return cxstring::createRef("StructDecl");
5893 case CXCursor_UnionDecl:
5894 return cxstring::createRef("UnionDecl");
5895 case CXCursor_ClassDecl:
5896 return cxstring::createRef("ClassDecl");
5897 case CXCursor_FieldDecl:
5898 return cxstring::createRef("FieldDecl");
5899 case CXCursor_VarDecl:
5900 return cxstring::createRef("VarDecl");
5901 case CXCursor_ParmDecl:
5902 return cxstring::createRef("ParmDecl");
5903 case CXCursor_ObjCInterfaceDecl:
5904 return cxstring::createRef("ObjCInterfaceDecl");
5905 case CXCursor_ObjCCategoryDecl:
5906 return cxstring::createRef("ObjCCategoryDecl");
5907 case CXCursor_ObjCProtocolDecl:
5908 return cxstring::createRef("ObjCProtocolDecl");
5909 case CXCursor_ObjCPropertyDecl:
5910 return cxstring::createRef("ObjCPropertyDecl");
5911 case CXCursor_ObjCIvarDecl:
5912 return cxstring::createRef("ObjCIvarDecl");
5913 case CXCursor_ObjCInstanceMethodDecl:
5914 return cxstring::createRef("ObjCInstanceMethodDecl");
5915 case CXCursor_ObjCClassMethodDecl:
5916 return cxstring::createRef("ObjCClassMethodDecl");
5917 case CXCursor_ObjCImplementationDecl:
5918 return cxstring::createRef("ObjCImplementationDecl");
5919 case CXCursor_ObjCCategoryImplDecl:
5920 return cxstring::createRef("ObjCCategoryImplDecl");
5921 case CXCursor_CXXMethod:
5922 return cxstring::createRef("CXXMethod");
5923 case CXCursor_UnexposedDecl:
5924 return cxstring::createRef("UnexposedDecl");
5925 case CXCursor_ObjCSuperClassRef:
5926 return cxstring::createRef("ObjCSuperClassRef");
5927 case CXCursor_ObjCProtocolRef:
5928 return cxstring::createRef("ObjCProtocolRef");
5929 case CXCursor_ObjCClassRef:
5930 return cxstring::createRef("ObjCClassRef");
5931 case CXCursor_TypeRef:
5932 return cxstring::createRef("TypeRef");
5933 case CXCursor_TemplateRef:
5934 return cxstring::createRef("TemplateRef");
5935 case CXCursor_NamespaceRef:
5936 return cxstring::createRef("NamespaceRef");
5937 case CXCursor_MemberRef:
5938 return cxstring::createRef("MemberRef");
5939 case CXCursor_LabelRef:
5940 return cxstring::createRef("LabelRef");
5941 case CXCursor_OverloadedDeclRef:
5942 return cxstring::createRef("OverloadedDeclRef");
5943 case CXCursor_VariableRef:
5944 return cxstring::createRef("VariableRef");
5945 case CXCursor_IntegerLiteral:
5946 return cxstring::createRef("IntegerLiteral");
5947 case CXCursor_FixedPointLiteral:
5948 return cxstring::createRef("FixedPointLiteral");
5949 case CXCursor_FloatingLiteral:
5950 return cxstring::createRef("FloatingLiteral");
5951 case CXCursor_ImaginaryLiteral:
5952 return cxstring::createRef("ImaginaryLiteral");
5953 case CXCursor_StringLiteral:
5954 return cxstring::createRef("StringLiteral");
5955 case CXCursor_CharacterLiteral:
5956 return cxstring::createRef("CharacterLiteral");
5957 case CXCursor_ParenExpr:
5958 return cxstring::createRef("ParenExpr");
5959 case CXCursor_UnaryOperator:
5960 return cxstring::createRef("UnaryOperator");
5961 case CXCursor_ArraySubscriptExpr:
5962 return cxstring::createRef("ArraySubscriptExpr");
5963 case CXCursor_ArraySectionExpr:
5964 return cxstring::createRef("ArraySectionExpr");
5965 case CXCursor_OMPArrayShapingExpr:
5966 return cxstring::createRef("OMPArrayShapingExpr");
5967 case CXCursor_OMPIteratorExpr:
5968 return cxstring::createRef("OMPIteratorExpr");
5969 case CXCursor_BinaryOperator:
5970 return cxstring::createRef("BinaryOperator");
5971 case CXCursor_CompoundAssignOperator:
5972 return cxstring::createRef("CompoundAssignOperator");
5973 case CXCursor_ConditionalOperator:
5974 return cxstring::createRef("ConditionalOperator");
5975 case CXCursor_CStyleCastExpr:
5976 return cxstring::createRef("CStyleCastExpr");
5977 case CXCursor_CompoundLiteralExpr:
5978 return cxstring::createRef("CompoundLiteralExpr");
5979 case CXCursor_InitListExpr:
5980 return cxstring::createRef("InitListExpr");
5981 case CXCursor_AddrLabelExpr:
5982 return cxstring::createRef("AddrLabelExpr");
5983 case CXCursor_StmtExpr:
5984 return cxstring::createRef("StmtExpr");
5985 case CXCursor_GenericSelectionExpr:
5986 return cxstring::createRef("GenericSelectionExpr");
5987 case CXCursor_GNUNullExpr:
5988 return cxstring::createRef("GNUNullExpr");
5989 case CXCursor_CXXStaticCastExpr:
5990 return cxstring::createRef("CXXStaticCastExpr");
5991 case CXCursor_CXXDynamicCastExpr:
5992 return cxstring::createRef("CXXDynamicCastExpr");
5993 case CXCursor_CXXReinterpretCastExpr:
5994 return cxstring::createRef("CXXReinterpretCastExpr");
5995 case CXCursor_CXXConstCastExpr:
5996 return cxstring::createRef("CXXConstCastExpr");
5997 case CXCursor_CXXFunctionalCastExpr:
5998 return cxstring::createRef("CXXFunctionalCastExpr");
5999 case CXCursor_CXXAddrspaceCastExpr:
6000 return cxstring::createRef("CXXAddrspaceCastExpr");
6001 case CXCursor_CXXTypeidExpr:
6002 return cxstring::createRef("CXXTypeidExpr");
6003 case CXCursor_CXXBoolLiteralExpr:
6004 return cxstring::createRef("CXXBoolLiteralExpr");
6005 case CXCursor_CXXNullPtrLiteralExpr:
6006 return cxstring::createRef("CXXNullPtrLiteralExpr");
6007 case CXCursor_CXXThisExpr:
6008 return cxstring::createRef("CXXThisExpr");
6009 case CXCursor_CXXThrowExpr:
6010 return cxstring::createRef("CXXThrowExpr");
6011 case CXCursor_CXXNewExpr:
6012 return cxstring::createRef("CXXNewExpr");
6013 case CXCursor_CXXDeleteExpr:
6014 return cxstring::createRef("CXXDeleteExpr");
6015 case CXCursor_UnaryExpr:
6016 return cxstring::createRef("UnaryExpr");
6017 case CXCursor_ObjCStringLiteral:
6018 return cxstring::createRef("ObjCStringLiteral");
6019 case CXCursor_ObjCBoolLiteralExpr:
6020 return cxstring::createRef("ObjCBoolLiteralExpr");
6021 case CXCursor_ObjCAvailabilityCheckExpr:
6022 return cxstring::createRef("ObjCAvailabilityCheckExpr");
6023 case CXCursor_ObjCSelfExpr:
6024 return cxstring::createRef("ObjCSelfExpr");
6025 case CXCursor_ObjCEncodeExpr:
6026 return cxstring::createRef("ObjCEncodeExpr");
6027 case CXCursor_ObjCSelectorExpr:
6028 return cxstring::createRef("ObjCSelectorExpr");
6029 case CXCursor_ObjCProtocolExpr:
6030 return cxstring::createRef("ObjCProtocolExpr");
6031 case CXCursor_ObjCBridgedCastExpr:
6032 return cxstring::createRef("ObjCBridgedCastExpr");
6033 case CXCursor_BlockExpr:
6034 return cxstring::createRef("BlockExpr");
6035 case CXCursor_PackExpansionExpr:
6036 return cxstring::createRef("PackExpansionExpr");
6037 case CXCursor_SizeOfPackExpr:
6038 return cxstring::createRef("SizeOfPackExpr");
6039 case CXCursor_PackIndexingExpr:
6040 return cxstring::createRef("PackIndexingExpr");
6041 case CXCursor_LambdaExpr:
6042 return cxstring::createRef("LambdaExpr");
6043 case CXCursor_UnexposedExpr:
6044 return cxstring::createRef("UnexposedExpr");
6045 case CXCursor_DeclRefExpr:
6046 return cxstring::createRef("DeclRefExpr");
6047 case CXCursor_MemberRefExpr:
6048 return cxstring::createRef("MemberRefExpr");
6049 case CXCursor_CallExpr:
6050 return cxstring::createRef("CallExpr");
6051 case CXCursor_ObjCMessageExpr:
6052 return cxstring::createRef("ObjCMessageExpr");
6053 case CXCursor_BuiltinBitCastExpr:
6054 return cxstring::createRef("BuiltinBitCastExpr");
6055 case CXCursor_ConceptSpecializationExpr:
6056 return cxstring::createRef("ConceptSpecializationExpr");
6057 case CXCursor_RequiresExpr:
6058 return cxstring::createRef("RequiresExpr");
6059 case CXCursor_CXXParenListInitExpr:
6060 return cxstring::createRef("CXXParenListInitExpr");
6061 case CXCursor_UnexposedStmt:
6062 return cxstring::createRef("UnexposedStmt");
6063 case CXCursor_DeclStmt:
6064 return cxstring::createRef("DeclStmt");
6065 case CXCursor_LabelStmt:
6066 return cxstring::createRef("LabelStmt");
6067 case CXCursor_CompoundStmt:
6068 return cxstring::createRef("CompoundStmt");
6069 case CXCursor_CaseStmt:
6070 return cxstring::createRef("CaseStmt");
6071 case CXCursor_DefaultStmt:
6072 return cxstring::createRef("DefaultStmt");
6073 case CXCursor_IfStmt:
6074 return cxstring::createRef("IfStmt");
6075 case CXCursor_SwitchStmt:
6076 return cxstring::createRef("SwitchStmt");
6077 case CXCursor_WhileStmt:
6078 return cxstring::createRef("WhileStmt");
6079 case CXCursor_DoStmt:
6080 return cxstring::createRef("DoStmt");
6081 case CXCursor_ForStmt:
6082 return cxstring::createRef("ForStmt");
6083 case CXCursor_GotoStmt:
6084 return cxstring::createRef("GotoStmt");
6085 case CXCursor_IndirectGotoStmt:
6086 return cxstring::createRef("IndirectGotoStmt");
6087 case CXCursor_ContinueStmt:
6088 return cxstring::createRef("ContinueStmt");
6089 case CXCursor_BreakStmt:
6090 return cxstring::createRef("BreakStmt");
6091 case CXCursor_ReturnStmt:
6092 return cxstring::createRef("ReturnStmt");
6093 case CXCursor_GCCAsmStmt:
6094 return cxstring::createRef("GCCAsmStmt");
6095 case CXCursor_MSAsmStmt:
6096 return cxstring::createRef("MSAsmStmt");
6097 case CXCursor_ObjCAtTryStmt:
6098 return cxstring::createRef("ObjCAtTryStmt");
6099 case CXCursor_ObjCAtCatchStmt:
6100 return cxstring::createRef("ObjCAtCatchStmt");
6101 case CXCursor_ObjCAtFinallyStmt:
6102 return cxstring::createRef("ObjCAtFinallyStmt");
6103 case CXCursor_ObjCAtThrowStmt:
6104 return cxstring::createRef("ObjCAtThrowStmt");
6105 case CXCursor_ObjCAtSynchronizedStmt:
6106 return cxstring::createRef("ObjCAtSynchronizedStmt");
6107 case CXCursor_ObjCAutoreleasePoolStmt:
6108 return cxstring::createRef("ObjCAutoreleasePoolStmt");
6109 case CXCursor_ObjCForCollectionStmt:
6110 return cxstring::createRef("ObjCForCollectionStmt");
6111 case CXCursor_CXXCatchStmt:
6112 return cxstring::createRef("CXXCatchStmt");
6113 case CXCursor_CXXTryStmt:
6114 return cxstring::createRef("CXXTryStmt");
6115 case CXCursor_CXXForRangeStmt:
6116 return cxstring::createRef("CXXForRangeStmt");
6117 case CXCursor_SEHTryStmt:
6118 return cxstring::createRef("SEHTryStmt");
6119 case CXCursor_SEHExceptStmt:
6120 return cxstring::createRef("SEHExceptStmt");
6121 case CXCursor_SEHFinallyStmt:
6122 return cxstring::createRef("SEHFinallyStmt");
6123 case CXCursor_SEHLeaveStmt:
6124 return cxstring::createRef("SEHLeaveStmt");
6125 case CXCursor_NullStmt:
6126 return cxstring::createRef("NullStmt");
6127 case CXCursor_InvalidFile:
6128 return cxstring::createRef("InvalidFile");
6129 case CXCursor_InvalidCode:
6130 return cxstring::createRef("InvalidCode");
6131 case CXCursor_NoDeclFound:
6132 return cxstring::createRef("NoDeclFound");
6133 case CXCursor_NotImplemented:
6134 return cxstring::createRef("NotImplemented");
6135 case CXCursor_TranslationUnit:
6136 return cxstring::createRef("TranslationUnit");
6137 case CXCursor_UnexposedAttr:
6138 return cxstring::createRef("UnexposedAttr");
6139 case CXCursor_IBActionAttr:
6140 return cxstring::createRef("attribute(ibaction)");
6141 case CXCursor_IBOutletAttr:
6142 return cxstring::createRef("attribute(iboutlet)");
6143 case CXCursor_IBOutletCollectionAttr:
6144 return cxstring::createRef("attribute(iboutletcollection)");
6145 case CXCursor_CXXFinalAttr:
6146 return cxstring::createRef("attribute(final)");
6147 case CXCursor_CXXOverrideAttr:
6148 return cxstring::createRef("attribute(override)");
6149 case CXCursor_AnnotateAttr:
6150 return cxstring::createRef("attribute(annotate)");
6151 case CXCursor_AsmLabelAttr:
6152 return cxstring::createRef("asm label");
6153 case CXCursor_PackedAttr:
6154 return cxstring::createRef("attribute(packed)");
6155 case CXCursor_PureAttr:
6156 return cxstring::createRef("attribute(pure)");
6157 case CXCursor_ConstAttr:
6158 return cxstring::createRef("attribute(const)");
6159 case CXCursor_NoDuplicateAttr:
6160 return cxstring::createRef("attribute(noduplicate)");
6161 case CXCursor_CUDAConstantAttr:
6162 return cxstring::createRef("attribute(constant)");
6163 case CXCursor_CUDADeviceAttr:
6164 return cxstring::createRef("attribute(device)");
6165 case CXCursor_CUDAGlobalAttr:
6166 return cxstring::createRef("attribute(global)");
6167 case CXCursor_CUDAHostAttr:
6168 return cxstring::createRef("attribute(host)");
6169 case CXCursor_CUDASharedAttr:
6170 return cxstring::createRef("attribute(shared)");
6171 case CXCursor_VisibilityAttr:
6172 return cxstring::createRef("attribute(visibility)");
6173 case CXCursor_DLLExport:
6174 return cxstring::createRef("attribute(dllexport)");
6175 case CXCursor_DLLImport:
6176 return cxstring::createRef("attribute(dllimport)");
6177 case CXCursor_NSReturnsRetained:
6178 return cxstring::createRef("attribute(ns_returns_retained)");
6179 case CXCursor_NSReturnsNotRetained:
6180 return cxstring::createRef("attribute(ns_returns_not_retained)");
6181 case CXCursor_NSReturnsAutoreleased:
6182 return cxstring::createRef("attribute(ns_returns_autoreleased)");
6183 case CXCursor_NSConsumesSelf:
6184 return cxstring::createRef("attribute(ns_consumes_self)");
6185 case CXCursor_NSConsumed:
6186 return cxstring::createRef("attribute(ns_consumed)");
6187 case CXCursor_ObjCException:
6188 return cxstring::createRef("attribute(objc_exception)");
6189 case CXCursor_ObjCNSObject:
6190 return cxstring::createRef("attribute(NSObject)");
6191 case CXCursor_ObjCIndependentClass:
6192 return cxstring::createRef("attribute(objc_independent_class)");
6193 case CXCursor_ObjCPreciseLifetime:
6194 return cxstring::createRef("attribute(objc_precise_lifetime)");
6195 case CXCursor_ObjCReturnsInnerPointer:
6196 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
6197 case CXCursor_ObjCRequiresSuper:
6198 return cxstring::createRef("attribute(objc_requires_super)");
6199 case CXCursor_ObjCRootClass:
6200 return cxstring::createRef("attribute(objc_root_class)");
6201 case CXCursor_ObjCSubclassingRestricted:
6202 return cxstring::createRef("attribute(objc_subclassing_restricted)");
6203 case CXCursor_ObjCExplicitProtocolImpl:
6204 return cxstring::createRef(
6205 "attribute(objc_protocol_requires_explicit_implementation)");
6206 case CXCursor_ObjCDesignatedInitializer:
6207 return cxstring::createRef("attribute(objc_designated_initializer)");
6208 case CXCursor_ObjCRuntimeVisible:
6209 return cxstring::createRef("attribute(objc_runtime_visible)");
6210 case CXCursor_ObjCBoxable:
6211 return cxstring::createRef("attribute(objc_boxable)");
6212 case CXCursor_FlagEnum:
6213 return cxstring::createRef("attribute(flag_enum)");
6214 case CXCursor_PreprocessingDirective:
6215 return cxstring::createRef("preprocessing directive");
6216 case CXCursor_MacroDefinition:
6217 return cxstring::createRef("macro definition");
6218 case CXCursor_MacroExpansion:
6219 return cxstring::createRef("macro expansion");
6220 case CXCursor_InclusionDirective:
6221 return cxstring::createRef("inclusion directive");
6222 case CXCursor_Namespace:
6223 return cxstring::createRef("Namespace");
6224 case CXCursor_LinkageSpec:
6225 return cxstring::createRef("LinkageSpec");
6226 case CXCursor_CXXBaseSpecifier:
6227 return cxstring::createRef("C++ base class specifier");
6228 case CXCursor_Constructor:
6229 return cxstring::createRef("CXXConstructor");
6230 case CXCursor_Destructor:
6231 return cxstring::createRef("CXXDestructor");
6232 case CXCursor_ConversionFunction:
6233 return cxstring::createRef("CXXConversion");
6234 case CXCursor_TemplateTypeParameter:
6235 return cxstring::createRef("TemplateTypeParameter");
6236 case CXCursor_NonTypeTemplateParameter:
6237 return cxstring::createRef("NonTypeTemplateParameter");
6238 case CXCursor_TemplateTemplateParameter:
6239 return cxstring::createRef("TemplateTemplateParameter");
6240 case CXCursor_FunctionTemplate:
6241 return cxstring::createRef("FunctionTemplate");
6242 case CXCursor_ClassTemplate:
6243 return cxstring::createRef("ClassTemplate");
6244 case CXCursor_ClassTemplatePartialSpecialization:
6245 return cxstring::createRef("ClassTemplatePartialSpecialization");
6246 case CXCursor_NamespaceAlias:
6247 return cxstring::createRef("NamespaceAlias");
6248 case CXCursor_UsingDirective:
6249 return cxstring::createRef("UsingDirective");
6250 case CXCursor_UsingDeclaration:
6251 return cxstring::createRef("UsingDeclaration");
6252 case CXCursor_TypeAliasDecl:
6253 return cxstring::createRef("TypeAliasDecl");
6254 case CXCursor_ObjCSynthesizeDecl:
6255 return cxstring::createRef("ObjCSynthesizeDecl");
6256 case CXCursor_ObjCDynamicDecl:
6257 return cxstring::createRef("ObjCDynamicDecl");
6258 case CXCursor_CXXAccessSpecifier:
6259 return cxstring::createRef("CXXAccessSpecifier");
6260 case CXCursor_ModuleImportDecl:
6261 return cxstring::createRef("ModuleImport");
6262 case CXCursor_OMPCanonicalLoop:
6263 return cxstring::createRef("OMPCanonicalLoop");
6264 case CXCursor_OMPMetaDirective:
6265 return cxstring::createRef("OMPMetaDirective");
6266 case CXCursor_OMPParallelDirective:
6267 return cxstring::createRef("OMPParallelDirective");
6268 case CXCursor_OMPSimdDirective:
6269 return cxstring::createRef("OMPSimdDirective");
6270 case CXCursor_OMPTileDirective:
6271 return cxstring::createRef("OMPTileDirective");
6272 case CXCursor_OMPUnrollDirective:
6273 return cxstring::createRef("OMPUnrollDirective");
6274 case CXCursor_OMPReverseDirective:
6275 return cxstring::createRef("OMPReverseDirective");
6276 case CXCursor_OMPInterchangeDirective:
6277 return cxstring::createRef("OMPInterchangeDirective");
6278 case CXCursor_OMPForDirective:
6279 return cxstring::createRef("OMPForDirective");
6280 case CXCursor_OMPForSimdDirective:
6281 return cxstring::createRef("OMPForSimdDirective");
6282 case CXCursor_OMPSectionsDirective:
6283 return cxstring::createRef("OMPSectionsDirective");
6284 case CXCursor_OMPSectionDirective:
6285 return cxstring::createRef("OMPSectionDirective");
6286 case CXCursor_OMPScopeDirective:
6287 return cxstring::createRef("OMPScopeDirective");
6288 case CXCursor_OMPSingleDirective:
6289 return cxstring::createRef("OMPSingleDirective");
6290 case CXCursor_OMPMasterDirective:
6291 return cxstring::createRef("OMPMasterDirective");
6292 case CXCursor_OMPCriticalDirective:
6293 return cxstring::createRef("OMPCriticalDirective");
6294 case CXCursor_OMPParallelForDirective:
6295 return cxstring::createRef("OMPParallelForDirective");
6296 case CXCursor_OMPParallelForSimdDirective:
6297 return cxstring::createRef("OMPParallelForSimdDirective");
6298 case CXCursor_OMPParallelMasterDirective:
6299 return cxstring::createRef("OMPParallelMasterDirective");
6300 case CXCursor_OMPParallelMaskedDirective:
6301 return cxstring::createRef("OMPParallelMaskedDirective");
6302 case CXCursor_OMPParallelSectionsDirective:
6303 return cxstring::createRef("OMPParallelSectionsDirective");
6304 case CXCursor_OMPTaskDirective:
6305 return cxstring::createRef("OMPTaskDirective");
6306 case CXCursor_OMPTaskyieldDirective:
6307 return cxstring::createRef("OMPTaskyieldDirective");
6308 case CXCursor_OMPBarrierDirective:
6309 return cxstring::createRef("OMPBarrierDirective");
6310 case CXCursor_OMPTaskwaitDirective:
6311 return cxstring::createRef("OMPTaskwaitDirective");
6312 case CXCursor_OMPAssumeDirective:
6313 return cxstring::createRef("OMPAssumeDirective");
6314 case CXCursor_OMPErrorDirective:
6315 return cxstring::createRef("OMPErrorDirective");
6316 case CXCursor_OMPTaskgroupDirective:
6317 return cxstring::createRef("OMPTaskgroupDirective");
6318 case CXCursor_OMPFlushDirective:
6319 return cxstring::createRef("OMPFlushDirective");
6320 case CXCursor_OMPDepobjDirective:
6321 return cxstring::createRef("OMPDepobjDirective");
6322 case CXCursor_OMPScanDirective:
6323 return cxstring::createRef("OMPScanDirective");
6324 case CXCursor_OMPOrderedDirective:
6325 return cxstring::createRef("OMPOrderedDirective");
6326 case CXCursor_OMPAtomicDirective:
6327 return cxstring::createRef("OMPAtomicDirective");
6328 case CXCursor_OMPTargetDirective:
6329 return cxstring::createRef("OMPTargetDirective");
6330 case CXCursor_OMPTargetDataDirective:
6331 return cxstring::createRef("OMPTargetDataDirective");
6332 case CXCursor_OMPTargetEnterDataDirective:
6333 return cxstring::createRef("OMPTargetEnterDataDirective");
6334 case CXCursor_OMPTargetExitDataDirective:
6335 return cxstring::createRef("OMPTargetExitDataDirective");
6336 case CXCursor_OMPTargetParallelDirective:
6337 return cxstring::createRef("OMPTargetParallelDirective");
6338 case CXCursor_OMPTargetParallelForDirective:
6339 return cxstring::createRef("OMPTargetParallelForDirective");
6340 case CXCursor_OMPTargetUpdateDirective:
6341 return cxstring::createRef("OMPTargetUpdateDirective");
6342 case CXCursor_OMPTeamsDirective:
6343 return cxstring::createRef("OMPTeamsDirective");
6344 case CXCursor_OMPCancellationPointDirective:
6345 return cxstring::createRef("OMPCancellationPointDirective");
6346 case CXCursor_OMPCancelDirective:
6347 return cxstring::createRef("OMPCancelDirective");
6348 case CXCursor_OMPTaskLoopDirective:
6349 return cxstring::createRef("OMPTaskLoopDirective");
6350 case CXCursor_OMPTaskLoopSimdDirective:
6351 return cxstring::createRef("OMPTaskLoopSimdDirective");
6352 case CXCursor_OMPMasterTaskLoopDirective:
6353 return cxstring::createRef("OMPMasterTaskLoopDirective");
6354 case CXCursor_OMPMaskedTaskLoopDirective:
6355 return cxstring::createRef("OMPMaskedTaskLoopDirective");
6356 case CXCursor_OMPMasterTaskLoopSimdDirective:
6357 return cxstring::createRef("OMPMasterTaskLoopSimdDirective");
6358 case CXCursor_OMPMaskedTaskLoopSimdDirective:
6359 return cxstring::createRef("OMPMaskedTaskLoopSimdDirective");
6360 case CXCursor_OMPParallelMasterTaskLoopDirective:
6361 return cxstring::createRef("OMPParallelMasterTaskLoopDirective");
6362 case CXCursor_OMPParallelMaskedTaskLoopDirective:
6363 return cxstring::createRef("OMPParallelMaskedTaskLoopDirective");
6364 case CXCursor_OMPParallelMasterTaskLoopSimdDirective:
6365 return cxstring::createRef("OMPParallelMasterTaskLoopSimdDirective");
6366 case CXCursor_OMPParallelMaskedTaskLoopSimdDirective:
6367 return cxstring::createRef("OMPParallelMaskedTaskLoopSimdDirective");
6368 case CXCursor_OMPDistributeDirective:
6369 return cxstring::createRef("OMPDistributeDirective");
6370 case CXCursor_OMPDistributeParallelForDirective:
6371 return cxstring::createRef("OMPDistributeParallelForDirective");
6372 case CXCursor_OMPDistributeParallelForSimdDirective:
6373 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
6374 case CXCursor_OMPDistributeSimdDirective:
6375 return cxstring::createRef("OMPDistributeSimdDirective");
6376 case CXCursor_OMPTargetParallelForSimdDirective:
6377 return cxstring::createRef("OMPTargetParallelForSimdDirective");
6378 case CXCursor_OMPTargetSimdDirective:
6379 return cxstring::createRef("OMPTargetSimdDirective");
6380 case CXCursor_OMPTeamsDistributeDirective:
6381 return cxstring::createRef("OMPTeamsDistributeDirective");
6382 case CXCursor_OMPTeamsDistributeSimdDirective:
6383 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
6384 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
6385 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
6386 case CXCursor_OMPTeamsDistributeParallelForDirective:
6387 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
6388 case CXCursor_OMPTargetTeamsDirective:
6389 return cxstring::createRef("OMPTargetTeamsDirective");
6390 case CXCursor_OMPTargetTeamsDistributeDirective:
6391 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
6392 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
6393 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
6394 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
6395 return cxstring::createRef(
6396 "OMPTargetTeamsDistributeParallelForSimdDirective");
6397 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
6398 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
6399 case CXCursor_OMPInteropDirective:
6400 return cxstring::createRef("OMPInteropDirective");
6401 case CXCursor_OMPDispatchDirective:
6402 return cxstring::createRef("OMPDispatchDirective");
6403 case CXCursor_OMPMaskedDirective:
6404 return cxstring::createRef("OMPMaskedDirective");
6405 case CXCursor_OMPGenericLoopDirective:
6406 return cxstring::createRef("OMPGenericLoopDirective");
6407 case CXCursor_OMPTeamsGenericLoopDirective:
6408 return cxstring::createRef("OMPTeamsGenericLoopDirective");
6409 case CXCursor_OMPTargetTeamsGenericLoopDirective:
6410 return cxstring::createRef("OMPTargetTeamsGenericLoopDirective");
6411 case CXCursor_OMPParallelGenericLoopDirective:
6412 return cxstring::createRef("OMPParallelGenericLoopDirective");
6413 case CXCursor_OMPTargetParallelGenericLoopDirective:
6414 return cxstring::createRef("OMPTargetParallelGenericLoopDirective");
6415 case CXCursor_OverloadCandidate:
6416 return cxstring::createRef("OverloadCandidate");
6417 case CXCursor_TypeAliasTemplateDecl:
6418 return cxstring::createRef("TypeAliasTemplateDecl");
6419 case CXCursor_StaticAssert:
6420 return cxstring::createRef("StaticAssert");
6421 case CXCursor_FriendDecl:
6422 return cxstring::createRef("FriendDecl");
6423 case CXCursor_ConvergentAttr:
6424 return cxstring::createRef("attribute(convergent)");
6425 case CXCursor_WarnUnusedAttr:
6426 return cxstring::createRef("attribute(warn_unused)");
6427 case CXCursor_WarnUnusedResultAttr:
6428 return cxstring::createRef("attribute(warn_unused_result)");
6429 case CXCursor_AlignedAttr:
6430 return cxstring::createRef("attribute(aligned)");
6431 case CXCursor_ConceptDecl:
6432 return cxstring::createRef("ConceptDecl");
6433 case CXCursor_OpenACCComputeConstruct:
6434 return cxstring::createRef("OpenACCComputeConstruct");
6435 case CXCursor_OpenACCLoopConstruct:
6436 return cxstring::createRef("OpenACCLoopConstruct");
6437 case CXCursor_OpenACCCombinedConstruct:
6438 return cxstring::createRef("OpenACCCombinedConstruct");
6439 case CXCursor_OpenACCDataConstruct:
6440 return cxstring::createRef("OpenACCDataConstruct");
6441 case CXCursor_OpenACCEnterDataConstruct:
6442 return cxstring::createRef("OpenACCEnterDataConstruct");
6443 case CXCursor_OpenACCExitDataConstruct:
6444 return cxstring::createRef("OpenACCExitDataConstruct");
6445 case CXCursor_OpenACCHostDataConstruct:
6446 return cxstring::createRef("OpenACCHostDataConstruct");
6447 case CXCursor_OpenACCWaitConstruct:
6448 return cxstring::createRef("OpenACCWaitConstruct");
6449 case CXCursor_OpenACCInitConstruct:
6450 return cxstring::createRef("OpenACCInitConstruct");
6451 case CXCursor_OpenACCShutdownConstruct:
6452 return cxstring::createRef("OpenACCShutdownConstruct");
6453 case CXCursor_OpenACCSetConstruct:
6454 return cxstring::createRef("OpenACCSetConstruct");
6455 case CXCursor_OpenACCUpdateConstruct:
6456 return cxstring::createRef("OpenACCUpdateConstruct");
6459 llvm_unreachable("Unhandled CXCursorKind");
6462 struct GetCursorData {
6463 SourceLocation TokenBeginLoc;
6464 bool PointsAtMacroArgExpansion;
6465 bool VisitedObjCPropertyImplDecl;
6466 SourceLocation VisitedDeclaratorDeclStartLoc;
6467 CXCursor &BestCursor;
6469 GetCursorData(SourceManager &SM, SourceLocation tokenBegin,
6470 CXCursor &outputCursor)
6471 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
6472 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
6473 VisitedObjCPropertyImplDecl = false;
6477 static enum CXChildVisitResult
6478 GetCursorVisitor(CXCursor cursor, CXCursor parent, CXClientData client_data) {
6479 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
6480 CXCursor *BestCursor = &Data->BestCursor;
6482 // If we point inside a macro argument we should provide info of what the
6483 // token is so use the actual cursor, don't replace it with a macro expansion
6484 // cursor.
6485 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
6486 return CXChildVisit_Recurse;
6488 if (clang_isDeclaration(cursor.kind)) {
6489 // Avoid having the implicit methods override the property decls.
6490 if (const ObjCMethodDecl *MD =
6491 dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
6492 if (MD->isImplicit())
6493 return CXChildVisit_Break;
6495 } else if (const ObjCInterfaceDecl *ID =
6496 dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
6497 // Check that when we have multiple @class references in the same line,
6498 // that later ones do not override the previous ones.
6499 // If we have:
6500 // @class Foo, Bar;
6501 // source ranges for both start at '@', so 'Bar' will end up overriding
6502 // 'Foo' even though the cursor location was at 'Foo'.
6503 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
6504 BestCursor->kind == CXCursor_ObjCClassRef)
6505 if (const ObjCInterfaceDecl *PrevID =
6506 dyn_cast_or_null<ObjCInterfaceDecl>(
6507 getCursorDecl(*BestCursor))) {
6508 if (PrevID != ID && !PrevID->isThisDeclarationADefinition() &&
6509 !ID->isThisDeclarationADefinition())
6510 return CXChildVisit_Break;
6513 } else if (const DeclaratorDecl *DD =
6514 dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
6515 SourceLocation StartLoc = DD->getSourceRange().getBegin();
6516 // Check that when we have multiple declarators in the same line,
6517 // that later ones do not override the previous ones.
6518 // If we have:
6519 // int Foo, Bar;
6520 // source ranges for both start at 'int', so 'Bar' will end up overriding
6521 // 'Foo' even though the cursor location was at 'Foo'.
6522 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
6523 return CXChildVisit_Break;
6524 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
6526 } else if (const ObjCPropertyImplDecl *PropImp =
6527 dyn_cast_or_null<ObjCPropertyImplDecl>(
6528 getCursorDecl(cursor))) {
6529 (void)PropImp;
6530 // Check that when we have multiple @synthesize in the same line,
6531 // that later ones do not override the previous ones.
6532 // If we have:
6533 // @synthesize Foo, Bar;
6534 // source ranges for both start at '@', so 'Bar' will end up overriding
6535 // 'Foo' even though the cursor location was at 'Foo'.
6536 if (Data->VisitedObjCPropertyImplDecl)
6537 return CXChildVisit_Break;
6538 Data->VisitedObjCPropertyImplDecl = true;
6542 if (clang_isExpression(cursor.kind) &&
6543 clang_isDeclaration(BestCursor->kind)) {
6544 if (const Decl *D = getCursorDecl(*BestCursor)) {
6545 // Avoid having the cursor of an expression replace the declaration cursor
6546 // when the expression source range overlaps the declaration range.
6547 // This can happen for C++ constructor expressions whose range generally
6548 // include the variable declaration, e.g.:
6549 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl
6550 // cursor.
6551 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
6552 D->getLocation() == Data->TokenBeginLoc)
6553 return CXChildVisit_Break;
6557 // If our current best cursor is the construction of a temporary object,
6558 // don't replace that cursor with a type reference, because we want
6559 // clang_getCursor() to point at the constructor.
6560 if (clang_isExpression(BestCursor->kind) &&
6561 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
6562 cursor.kind == CXCursor_TypeRef) {
6563 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
6564 // as having the actual point on the type reference.
6565 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
6566 return CXChildVisit_Recurse;
6569 // If we already have an Objective-C superclass reference, don't
6570 // update it further.
6571 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
6572 return CXChildVisit_Break;
6574 *BestCursor = cursor;
6575 return CXChildVisit_Recurse;
6578 CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
6579 if (isNotUsableTU(TU)) {
6580 LOG_BAD_TU(TU);
6581 return clang_getNullCursor();
6584 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6585 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6587 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
6588 CXCursor Result = cxcursor::getCursor(TU, SLoc);
6590 LOG_FUNC_SECTION {
6591 CXFile SearchFile;
6592 unsigned SearchLine, SearchColumn;
6593 CXFile ResultFile;
6594 unsigned ResultLine, ResultColumn;
6595 CXString SearchFileName, ResultFileName, KindSpelling, USR;
6596 const char *IsDef = clang_isCursorDefinition(Result) ? " (Definition)" : "";
6597 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
6599 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
6600 nullptr);
6601 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine, &ResultColumn,
6602 nullptr);
6603 SearchFileName = clang_getFileName(SearchFile);
6604 ResultFileName = clang_getFileName(ResultFile);
6605 KindSpelling = clang_getCursorKindSpelling(Result.kind);
6606 USR = clang_getCursorUSR(Result);
6607 *Log << llvm::format("(%s:%d:%d) = %s", clang_getCString(SearchFileName),
6608 SearchLine, SearchColumn,
6609 clang_getCString(KindSpelling))
6610 << llvm::format("(%s:%d:%d):%s%s", clang_getCString(ResultFileName),
6611 ResultLine, ResultColumn, clang_getCString(USR),
6612 IsDef);
6613 clang_disposeString(SearchFileName);
6614 clang_disposeString(ResultFileName);
6615 clang_disposeString(KindSpelling);
6616 clang_disposeString(USR);
6618 CXCursor Definition = clang_getCursorDefinition(Result);
6619 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
6620 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
6621 CXString DefinitionKindSpelling =
6622 clang_getCursorKindSpelling(Definition.kind);
6623 CXFile DefinitionFile;
6624 unsigned DefinitionLine, DefinitionColumn;
6625 clang_getFileLocation(DefinitionLoc, &DefinitionFile, &DefinitionLine,
6626 &DefinitionColumn, nullptr);
6627 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
6628 *Log << llvm::format(" -> %s(%s:%d:%d)",
6629 clang_getCString(DefinitionKindSpelling),
6630 clang_getCString(DefinitionFileName), DefinitionLine,
6631 DefinitionColumn);
6632 clang_disposeString(DefinitionFileName);
6633 clang_disposeString(DefinitionKindSpelling);
6637 return Result;
6640 CXCursor clang_getNullCursor(void) {
6641 return MakeCXCursorInvalid(CXCursor_InvalidFile);
6644 unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
6645 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
6646 // can't set consistently. For example, when visiting a DeclStmt we will set
6647 // it but we don't set it on the result of clang_getCursorDefinition for
6648 // a reference of the same declaration.
6649 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
6650 // when visiting a DeclStmt currently, the AST should be enhanced to be able
6651 // to provide that kind of info.
6652 if (clang_isDeclaration(X.kind))
6653 X.data[1] = nullptr;
6654 if (clang_isDeclaration(Y.kind))
6655 Y.data[1] = nullptr;
6657 return X == Y;
6660 unsigned clang_hashCursor(CXCursor C) {
6661 unsigned Index = 0;
6662 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
6663 Index = 1;
6665 return llvm::DenseMapInfo<std::pair<unsigned, const void *>>::getHashValue(
6666 std::make_pair(C.kind, C.data[Index]));
6669 unsigned clang_isInvalid(enum CXCursorKind K) {
6670 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
6673 unsigned clang_isDeclaration(enum CXCursorKind K) {
6674 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
6675 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
6678 unsigned clang_isInvalidDeclaration(CXCursor C) {
6679 if (clang_isDeclaration(C.kind)) {
6680 if (const Decl *D = getCursorDecl(C))
6681 return D->isInvalidDecl();
6684 return 0;
6687 unsigned clang_isReference(enum CXCursorKind K) {
6688 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
6691 unsigned clang_isExpression(enum CXCursorKind K) {
6692 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
6695 unsigned clang_isStatement(enum CXCursorKind K) {
6696 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
6699 unsigned clang_isAttribute(enum CXCursorKind K) {
6700 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
6703 unsigned clang_isTranslationUnit(enum CXCursorKind K) {
6704 return K == CXCursor_TranslationUnit;
6707 unsigned clang_isPreprocessing(enum CXCursorKind K) {
6708 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
6711 unsigned clang_isUnexposed(enum CXCursorKind K) {
6712 switch (K) {
6713 case CXCursor_UnexposedDecl:
6714 case CXCursor_UnexposedExpr:
6715 case CXCursor_UnexposedStmt:
6716 case CXCursor_UnexposedAttr:
6717 return true;
6718 default:
6719 return false;
6723 CXCursorKind clang_getCursorKind(CXCursor C) { return C.kind; }
6725 CXSourceLocation clang_getCursorLocation(CXCursor C) {
6726 if (clang_isReference(C.kind)) {
6727 switch (C.kind) {
6728 case CXCursor_ObjCSuperClassRef: {
6729 std::pair<const ObjCInterfaceDecl *, SourceLocation> P =
6730 getCursorObjCSuperClassRef(C);
6731 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
6734 case CXCursor_ObjCProtocolRef: {
6735 std::pair<const ObjCProtocolDecl *, SourceLocation> P =
6736 getCursorObjCProtocolRef(C);
6737 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
6740 case CXCursor_ObjCClassRef: {
6741 std::pair<const ObjCInterfaceDecl *, SourceLocation> P =
6742 getCursorObjCClassRef(C);
6743 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
6746 case CXCursor_TypeRef: {
6747 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
6748 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
6751 case CXCursor_TemplateRef: {
6752 std::pair<const TemplateDecl *, SourceLocation> P =
6753 getCursorTemplateRef(C);
6754 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
6757 case CXCursor_NamespaceRef: {
6758 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
6759 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
6762 case CXCursor_MemberRef: {
6763 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
6764 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
6767 case CXCursor_VariableRef: {
6768 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
6769 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
6772 case CXCursor_CXXBaseSpecifier: {
6773 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
6774 if (!BaseSpec)
6775 return clang_getNullLocation();
6777 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
6778 return cxloc::translateSourceLocation(
6779 getCursorContext(C), TSInfo->getTypeLoc().getBeginLoc());
6781 return cxloc::translateSourceLocation(getCursorContext(C),
6782 BaseSpec->getBeginLoc());
6785 case CXCursor_LabelRef: {
6786 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
6787 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
6790 case CXCursor_OverloadedDeclRef:
6791 return cxloc::translateSourceLocation(
6792 getCursorContext(C), getCursorOverloadedDeclRef(C).second);
6794 default:
6795 // FIXME: Need a way to enumerate all non-reference cases.
6796 llvm_unreachable("Missed a reference kind");
6800 if (clang_isExpression(C.kind))
6801 return cxloc::translateSourceLocation(
6802 getCursorContext(C), getLocationFromExpr(getCursorExpr(C)));
6804 if (clang_isStatement(C.kind))
6805 return cxloc::translateSourceLocation(getCursorContext(C),
6806 getCursorStmt(C)->getBeginLoc());
6808 if (C.kind == CXCursor_PreprocessingDirective) {
6809 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
6810 return cxloc::translateSourceLocation(getCursorContext(C), L);
6813 if (C.kind == CXCursor_MacroExpansion) {
6814 SourceLocation L =
6815 cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
6816 return cxloc::translateSourceLocation(getCursorContext(C), L);
6819 if (C.kind == CXCursor_MacroDefinition) {
6820 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
6821 return cxloc::translateSourceLocation(getCursorContext(C), L);
6824 if (C.kind == CXCursor_InclusionDirective) {
6825 SourceLocation L =
6826 cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
6827 return cxloc::translateSourceLocation(getCursorContext(C), L);
6830 if (clang_isAttribute(C.kind)) {
6831 SourceLocation L = cxcursor::getCursorAttr(C)->getLocation();
6832 return cxloc::translateSourceLocation(getCursorContext(C), L);
6835 if (!clang_isDeclaration(C.kind))
6836 return clang_getNullLocation();
6838 const Decl *D = getCursorDecl(C);
6839 if (!D)
6840 return clang_getNullLocation();
6842 SourceLocation Loc = D->getLocation();
6843 // FIXME: Multiple variables declared in a single declaration
6844 // currently lack the information needed to correctly determine their
6845 // ranges when accounting for the type-specifier. We use context
6846 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6847 // and if so, whether it is the first decl.
6848 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6849 if (!cxcursor::isFirstInDeclGroup(C))
6850 Loc = VD->getLocation();
6853 // For ObjC methods, give the start location of the method name.
6854 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
6855 Loc = MD->getSelectorStartLoc();
6857 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
6860 } // end extern "C"
6862 CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
6863 assert(TU);
6865 // Guard against an invalid SourceLocation, or we may assert in one
6866 // of the following calls.
6867 if (SLoc.isInvalid())
6868 return clang_getNullCursor();
6870 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6872 // Translate the given source location to make it point at the beginning of
6873 // the token under the cursor.
6874 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
6875 CXXUnit->getASTContext().getLangOpts());
6877 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
6878 if (SLoc.isValid()) {
6879 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
6880 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
6881 /*VisitPreprocessorLast=*/true,
6882 /*VisitIncludedEntities=*/false,
6883 SourceLocation(SLoc));
6884 CursorVis.visitFileRegion();
6887 return Result;
6890 static SourceRange getRawCursorExtent(CXCursor C) {
6891 if (clang_isReference(C.kind)) {
6892 switch (C.kind) {
6893 case CXCursor_ObjCSuperClassRef:
6894 return getCursorObjCSuperClassRef(C).second;
6896 case CXCursor_ObjCProtocolRef:
6897 return getCursorObjCProtocolRef(C).second;
6899 case CXCursor_ObjCClassRef:
6900 return getCursorObjCClassRef(C).second;
6902 case CXCursor_TypeRef:
6903 return getCursorTypeRef(C).second;
6905 case CXCursor_TemplateRef:
6906 return getCursorTemplateRef(C).second;
6908 case CXCursor_NamespaceRef:
6909 return getCursorNamespaceRef(C).second;
6911 case CXCursor_MemberRef:
6912 return getCursorMemberRef(C).second;
6914 case CXCursor_CXXBaseSpecifier:
6915 return getCursorCXXBaseSpecifier(C)->getSourceRange();
6917 case CXCursor_LabelRef:
6918 return getCursorLabelRef(C).second;
6920 case CXCursor_OverloadedDeclRef:
6921 return getCursorOverloadedDeclRef(C).second;
6923 case CXCursor_VariableRef:
6924 return getCursorVariableRef(C).second;
6926 default:
6927 // FIXME: Need a way to enumerate all non-reference cases.
6928 llvm_unreachable("Missed a reference kind");
6932 if (clang_isExpression(C.kind))
6933 return getCursorExpr(C)->getSourceRange();
6935 if (clang_isStatement(C.kind))
6936 return getCursorStmt(C)->getSourceRange();
6938 if (clang_isAttribute(C.kind))
6939 return getCursorAttr(C)->getRange();
6941 if (C.kind == CXCursor_PreprocessingDirective)
6942 return cxcursor::getCursorPreprocessingDirective(C);
6944 if (C.kind == CXCursor_MacroExpansion) {
6945 ASTUnit *TU = getCursorASTUnit(C);
6946 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
6947 return TU->mapRangeFromPreamble(Range);
6950 if (C.kind == CXCursor_MacroDefinition) {
6951 ASTUnit *TU = getCursorASTUnit(C);
6952 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
6953 return TU->mapRangeFromPreamble(Range);
6956 if (C.kind == CXCursor_InclusionDirective) {
6957 ASTUnit *TU = getCursorASTUnit(C);
6958 SourceRange Range =
6959 cxcursor::getCursorInclusionDirective(C)->getSourceRange();
6960 return TU->mapRangeFromPreamble(Range);
6963 if (C.kind == CXCursor_TranslationUnit) {
6964 ASTUnit *TU = getCursorASTUnit(C);
6965 FileID MainID = TU->getSourceManager().getMainFileID();
6966 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
6967 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
6968 return SourceRange(Start, End);
6971 if (clang_isDeclaration(C.kind)) {
6972 const Decl *D = cxcursor::getCursorDecl(C);
6973 if (!D)
6974 return SourceRange();
6976 SourceRange R = D->getSourceRange();
6977 // FIXME: Multiple variables declared in a single declaration
6978 // currently lack the information needed to correctly determine their
6979 // ranges when accounting for the type-specifier. We use context
6980 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6981 // and if so, whether it is the first decl.
6982 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6983 if (!cxcursor::isFirstInDeclGroup(C))
6984 R.setBegin(VD->getLocation());
6986 return R;
6988 return SourceRange();
6991 /// Retrieves the "raw" cursor extent, which is then extended to include
6992 /// the decl-specifier-seq for declarations.
6993 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6994 if (clang_isDeclaration(C.kind)) {
6995 const Decl *D = cxcursor::getCursorDecl(C);
6996 if (!D)
6997 return SourceRange();
6999 SourceRange R = D->getSourceRange();
7001 // Adjust the start of the location for declarations preceded by
7002 // declaration specifiers.
7003 SourceLocation StartLoc;
7004 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7005 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
7006 StartLoc = TI->getTypeLoc().getBeginLoc();
7007 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
7008 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
7009 StartLoc = TI->getTypeLoc().getBeginLoc();
7012 if (StartLoc.isValid() && R.getBegin().isValid() &&
7013 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
7014 R.setBegin(StartLoc);
7016 // FIXME: Multiple variables declared in a single declaration
7017 // currently lack the information needed to correctly determine their
7018 // ranges when accounting for the type-specifier. We use context
7019 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
7020 // and if so, whether it is the first decl.
7021 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7022 if (!cxcursor::isFirstInDeclGroup(C))
7023 R.setBegin(VD->getLocation());
7026 return R;
7029 return getRawCursorExtent(C);
7032 CXSourceRange clang_getCursorExtent(CXCursor C) {
7033 SourceRange R = getRawCursorExtent(C);
7034 if (R.isInvalid())
7035 return clang_getNullRange();
7037 return cxloc::translateSourceRange(getCursorContext(C), R);
7040 CXCursor clang_getCursorReferenced(CXCursor C) {
7041 if (clang_isInvalid(C.kind))
7042 return clang_getNullCursor();
7044 CXTranslationUnit tu = getCursorTU(C);
7045 if (clang_isDeclaration(C.kind)) {
7046 const Decl *D = getCursorDecl(C);
7047 if (!D)
7048 return clang_getNullCursor();
7049 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
7050 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
7051 if (const ObjCPropertyImplDecl *PropImpl =
7052 dyn_cast<ObjCPropertyImplDecl>(D))
7053 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
7054 return MakeCXCursor(Property, tu);
7056 return C;
7059 if (clang_isExpression(C.kind)) {
7060 const Expr *E = getCursorExpr(C);
7061 const Decl *D = getDeclFromExpr(E);
7062 if (D) {
7063 CXCursor declCursor = MakeCXCursor(D, tu);
7064 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
7065 declCursor);
7066 return declCursor;
7069 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
7070 return MakeCursorOverloadedDeclRef(Ovl, tu);
7072 return clang_getNullCursor();
7075 if (clang_isStatement(C.kind)) {
7076 const Stmt *S = getCursorStmt(C);
7077 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
7078 if (LabelDecl *label = Goto->getLabel())
7079 if (LabelStmt *labelS = label->getStmt())
7080 return MakeCXCursor(labelS, getCursorDecl(C), tu);
7082 return clang_getNullCursor();
7085 if (C.kind == CXCursor_MacroExpansion) {
7086 if (const MacroDefinitionRecord *Def =
7087 getCursorMacroExpansion(C).getDefinition())
7088 return MakeMacroDefinitionCursor(Def, tu);
7091 if (!clang_isReference(C.kind))
7092 return clang_getNullCursor();
7094 switch (C.kind) {
7095 case CXCursor_ObjCSuperClassRef:
7096 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
7098 case CXCursor_ObjCProtocolRef: {
7099 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
7100 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
7101 return MakeCXCursor(Def, tu);
7103 return MakeCXCursor(Prot, tu);
7106 case CXCursor_ObjCClassRef: {
7107 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
7108 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
7109 return MakeCXCursor(Def, tu);
7111 return MakeCXCursor(Class, tu);
7114 case CXCursor_TypeRef:
7115 return MakeCXCursor(getCursorTypeRef(C).first, tu);
7117 case CXCursor_TemplateRef:
7118 return MakeCXCursor(getCursorTemplateRef(C).first, tu);
7120 case CXCursor_NamespaceRef:
7121 return MakeCXCursor(getCursorNamespaceRef(C).first, tu);
7123 case CXCursor_MemberRef:
7124 return MakeCXCursor(getCursorMemberRef(C).first, tu);
7126 case CXCursor_CXXBaseSpecifier: {
7127 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
7128 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(), tu));
7131 case CXCursor_LabelRef:
7132 // FIXME: We end up faking the "parent" declaration here because we
7133 // don't want to make CXCursor larger.
7134 return MakeCXCursor(
7135 getCursorLabelRef(C).first,
7136 cxtu::getASTUnit(tu)->getASTContext().getTranslationUnitDecl(), tu);
7138 case CXCursor_OverloadedDeclRef:
7139 return C;
7141 case CXCursor_VariableRef:
7142 return MakeCXCursor(getCursorVariableRef(C).first, tu);
7144 default:
7145 // We would prefer to enumerate all non-reference cursor kinds here.
7146 llvm_unreachable("Unhandled reference cursor kind");
7150 CXCursor clang_getCursorDefinition(CXCursor C) {
7151 if (clang_isInvalid(C.kind))
7152 return clang_getNullCursor();
7154 CXTranslationUnit TU = getCursorTU(C);
7156 bool WasReference = false;
7157 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
7158 C = clang_getCursorReferenced(C);
7159 WasReference = true;
7162 if (C.kind == CXCursor_MacroExpansion)
7163 return clang_getCursorReferenced(C);
7165 if (!clang_isDeclaration(C.kind))
7166 return clang_getNullCursor();
7168 const Decl *D = getCursorDecl(C);
7169 if (!D)
7170 return clang_getNullCursor();
7172 switch (D->getKind()) {
7173 // Declaration kinds that don't really separate the notions of
7174 // declaration and definition.
7175 case Decl::Namespace:
7176 case Decl::Typedef:
7177 case Decl::TypeAlias:
7178 case Decl::TypeAliasTemplate:
7179 case Decl::TemplateTypeParm:
7180 case Decl::EnumConstant:
7181 case Decl::Field:
7182 case Decl::Binding:
7183 case Decl::MSProperty:
7184 case Decl::MSGuid:
7185 case Decl::HLSLBuffer:
7186 case Decl::UnnamedGlobalConstant:
7187 case Decl::TemplateParamObject:
7188 case Decl::IndirectField:
7189 case Decl::ObjCIvar:
7190 case Decl::ObjCAtDefsField:
7191 case Decl::ImplicitParam:
7192 case Decl::ParmVar:
7193 case Decl::NonTypeTemplateParm:
7194 case Decl::TemplateTemplateParm:
7195 case Decl::ObjCCategoryImpl:
7196 case Decl::ObjCImplementation:
7197 case Decl::AccessSpec:
7198 case Decl::LinkageSpec:
7199 case Decl::Export:
7200 case Decl::ObjCPropertyImpl:
7201 case Decl::FileScopeAsm:
7202 case Decl::TopLevelStmt:
7203 case Decl::StaticAssert:
7204 case Decl::Block:
7205 case Decl::OutlinedFunction:
7206 case Decl::Captured:
7207 case Decl::OMPCapturedExpr:
7208 case Decl::Label: // FIXME: Is this right??
7209 case Decl::CXXDeductionGuide:
7210 case Decl::Import:
7211 case Decl::OMPThreadPrivate:
7212 case Decl::OMPAllocate:
7213 case Decl::OMPDeclareReduction:
7214 case Decl::OMPDeclareMapper:
7215 case Decl::OMPRequires:
7216 case Decl::ObjCTypeParam:
7217 case Decl::BuiltinTemplate:
7218 case Decl::PragmaComment:
7219 case Decl::PragmaDetectMismatch:
7220 case Decl::UsingPack:
7221 case Decl::Concept:
7222 case Decl::ImplicitConceptSpecialization:
7223 case Decl::LifetimeExtendedTemporary:
7224 case Decl::RequiresExprBody:
7225 case Decl::UnresolvedUsingIfExists:
7226 return C;
7228 // Declaration kinds that don't make any sense here, but are
7229 // nonetheless harmless.
7230 case Decl::Empty:
7231 case Decl::TranslationUnit:
7232 case Decl::ExternCContext:
7233 break;
7235 // Declaration kinds for which the definition is not resolvable.
7236 case Decl::UnresolvedUsingTypename:
7237 case Decl::UnresolvedUsingValue:
7238 break;
7240 case Decl::UsingDirective:
7241 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
7242 TU);
7244 case Decl::NamespaceAlias:
7245 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
7247 case Decl::Enum:
7248 case Decl::Record:
7249 case Decl::CXXRecord:
7250 case Decl::ClassTemplateSpecialization:
7251 case Decl::ClassTemplatePartialSpecialization:
7252 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
7253 return MakeCXCursor(Def, TU);
7254 return clang_getNullCursor();
7256 case Decl::Function:
7257 case Decl::CXXMethod:
7258 case Decl::CXXConstructor:
7259 case Decl::CXXDestructor:
7260 case Decl::CXXConversion: {
7261 const FunctionDecl *Def = nullptr;
7262 if (cast<FunctionDecl>(D)->getBody(Def))
7263 return MakeCXCursor(Def, TU);
7264 return clang_getNullCursor();
7267 case Decl::Var:
7268 case Decl::VarTemplateSpecialization:
7269 case Decl::VarTemplatePartialSpecialization:
7270 case Decl::Decomposition: {
7271 // Ask the variable if it has a definition.
7272 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
7273 return MakeCXCursor(Def, TU);
7274 return clang_getNullCursor();
7277 case Decl::FunctionTemplate: {
7278 const FunctionDecl *Def = nullptr;
7279 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
7280 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
7281 return clang_getNullCursor();
7284 case Decl::ClassTemplate: {
7285 if (RecordDecl *Def =
7286 cast<ClassTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
7287 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
7288 TU);
7289 return clang_getNullCursor();
7292 case Decl::VarTemplate: {
7293 if (VarDecl *Def =
7294 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
7295 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
7296 return clang_getNullCursor();
7299 case Decl::Using:
7300 case Decl::UsingEnum:
7301 return MakeCursorOverloadedDeclRef(cast<BaseUsingDecl>(D), D->getLocation(),
7302 TU);
7304 case Decl::UsingShadow:
7305 case Decl::ConstructorUsingShadow:
7306 return clang_getCursorDefinition(
7307 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(), TU));
7309 case Decl::ObjCMethod: {
7310 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
7311 if (Method->isThisDeclarationADefinition())
7312 return C;
7314 // Dig out the method definition in the associated
7315 // @implementation, if we have it.
7316 // FIXME: The ASTs should make finding the definition easier.
7317 if (const ObjCInterfaceDecl *Class =
7318 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
7319 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
7320 if (ObjCMethodDecl *Def = ClassImpl->getMethod(
7321 Method->getSelector(), Method->isInstanceMethod()))
7322 if (Def->isThisDeclarationADefinition())
7323 return MakeCXCursor(Def, TU);
7325 return clang_getNullCursor();
7328 case Decl::ObjCCategory:
7329 if (ObjCCategoryImplDecl *Impl =
7330 cast<ObjCCategoryDecl>(D)->getImplementation())
7331 return MakeCXCursor(Impl, TU);
7332 return clang_getNullCursor();
7334 case Decl::ObjCProtocol:
7335 if (const ObjCProtocolDecl *Def =
7336 cast<ObjCProtocolDecl>(D)->getDefinition())
7337 return MakeCXCursor(Def, TU);
7338 return clang_getNullCursor();
7340 case Decl::ObjCInterface: {
7341 // There are two notions of a "definition" for an Objective-C
7342 // class: the interface and its implementation. When we resolved a
7343 // reference to an Objective-C class, produce the @interface as
7344 // the definition; when we were provided with the interface,
7345 // produce the @implementation as the definition.
7346 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
7347 if (WasReference) {
7348 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
7349 return MakeCXCursor(Def, TU);
7350 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
7351 return MakeCXCursor(Impl, TU);
7352 return clang_getNullCursor();
7355 case Decl::ObjCProperty:
7356 // FIXME: We don't really know where to find the
7357 // ObjCPropertyImplDecls that implement this property.
7358 return clang_getNullCursor();
7360 case Decl::ObjCCompatibleAlias:
7361 if (const ObjCInterfaceDecl *Class =
7362 cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
7363 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
7364 return MakeCXCursor(Def, TU);
7366 return clang_getNullCursor();
7368 case Decl::Friend:
7369 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
7370 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
7371 return clang_getNullCursor();
7373 case Decl::FriendTemplate:
7374 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
7375 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
7376 return clang_getNullCursor();
7379 return clang_getNullCursor();
7382 unsigned clang_isCursorDefinition(CXCursor C) {
7383 if (!clang_isDeclaration(C.kind))
7384 return 0;
7386 return clang_getCursorDefinition(C) == C;
7389 CXCursor clang_getCanonicalCursor(CXCursor C) {
7390 if (!clang_isDeclaration(C.kind))
7391 return C;
7393 if (const Decl *D = getCursorDecl(C)) {
7394 if (const ObjCCategoryImplDecl *CatImplD =
7395 dyn_cast<ObjCCategoryImplDecl>(D))
7396 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
7397 return MakeCXCursor(CatD, getCursorTU(C));
7399 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
7400 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
7401 return MakeCXCursor(IFD, getCursorTU(C));
7403 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
7406 return C;
7409 int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
7410 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
7413 unsigned clang_getNumOverloadedDecls(CXCursor C) {
7414 if (C.kind != CXCursor_OverloadedDeclRef)
7415 return 0;
7417 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
7418 if (const OverloadExpr *E = dyn_cast<const OverloadExpr *>(Storage))
7419 return E->getNumDecls();
7421 if (OverloadedTemplateStorage *S =
7422 dyn_cast<OverloadedTemplateStorage *>(Storage))
7423 return S->size();
7425 const Decl *D = cast<const Decl *>(Storage);
7426 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
7427 return Using->shadow_size();
7429 return 0;
7432 CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
7433 if (cursor.kind != CXCursor_OverloadedDeclRef)
7434 return clang_getNullCursor();
7436 if (index >= clang_getNumOverloadedDecls(cursor))
7437 return clang_getNullCursor();
7439 CXTranslationUnit TU = getCursorTU(cursor);
7440 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
7441 if (const OverloadExpr *E = dyn_cast<const OverloadExpr *>(Storage))
7442 return MakeCXCursor(E->decls_begin()[index], TU);
7444 if (OverloadedTemplateStorage *S =
7445 dyn_cast<OverloadedTemplateStorage *>(Storage))
7446 return MakeCXCursor(S->begin()[index], TU);
7448 const Decl *D = cast<const Decl *>(Storage);
7449 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
7450 // FIXME: This is, unfortunately, linear time.
7451 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
7452 std::advance(Pos, index);
7453 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
7456 return clang_getNullCursor();
7459 void clang_getDefinitionSpellingAndExtent(
7460 CXCursor C, const char **startBuf, const char **endBuf, unsigned *startLine,
7461 unsigned *startColumn, unsigned *endLine, unsigned *endColumn) {
7462 assert(getCursorDecl(C) && "CXCursor has null decl");
7463 const auto *FD = cast<FunctionDecl>(getCursorDecl(C));
7464 const auto *Body = cast<CompoundStmt>(FD->getBody());
7466 SourceManager &SM = FD->getASTContext().getSourceManager();
7467 *startBuf = SM.getCharacterData(Body->getLBracLoc());
7468 *endBuf = SM.getCharacterData(Body->getRBracLoc());
7469 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
7470 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
7471 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
7472 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
7475 CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
7476 unsigned PieceIndex) {
7477 RefNamePieces Pieces;
7479 switch (C.kind) {
7480 case CXCursor_MemberRefExpr:
7481 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
7482 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
7483 E->getQualifierLoc().getSourceRange());
7484 break;
7486 case CXCursor_DeclRefExpr:
7487 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
7488 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
7489 Pieces =
7490 buildPieces(NameFlags, false, E->getNameInfo(),
7491 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
7493 break;
7495 case CXCursor_CallExpr:
7496 if (const CXXOperatorCallExpr *OCE =
7497 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
7498 const Expr *Callee = OCE->getCallee();
7499 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
7500 Callee = ICE->getSubExpr();
7502 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
7503 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
7504 DRE->getQualifierLoc().getSourceRange());
7506 break;
7508 default:
7509 break;
7512 if (Pieces.empty()) {
7513 if (PieceIndex == 0)
7514 return clang_getCursorExtent(C);
7515 } else if (PieceIndex < Pieces.size()) {
7516 SourceRange R = Pieces[PieceIndex];
7517 if (R.isValid())
7518 return cxloc::translateSourceRange(getCursorContext(C), R);
7521 return clang_getNullRange();
7524 void clang_enableStackTraces(void) {
7525 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
7526 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
7529 void clang_executeOnThread(void (*fn)(void *), void *user_data,
7530 unsigned stack_size) {
7531 llvm::thread Thread(stack_size == 0 ? clang::DesiredStackSize
7532 : std::optional<unsigned>(stack_size),
7533 fn, user_data);
7534 Thread.join();
7537 //===----------------------------------------------------------------------===//
7538 // Token-based Operations.
7539 //===----------------------------------------------------------------------===//
7541 /* CXToken layout:
7542 * int_data[0]: a CXTokenKind
7543 * int_data[1]: starting token location
7544 * int_data[2]: token length
7545 * int_data[3]: reserved
7546 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
7547 * otherwise unused.
7549 CXTokenKind clang_getTokenKind(CXToken CXTok) {
7550 return static_cast<CXTokenKind>(CXTok.int_data[0]);
7553 CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
7554 switch (clang_getTokenKind(CXTok)) {
7555 case CXToken_Identifier:
7556 case CXToken_Keyword:
7557 // We know we have an IdentifierInfo*, so use that.
7558 return cxstring::createRef(
7559 static_cast<IdentifierInfo *>(CXTok.ptr_data)->getNameStart());
7561 case CXToken_Literal: {
7562 // We have stashed the starting pointer in the ptr_data field. Use it.
7563 const char *Text = static_cast<const char *>(CXTok.ptr_data);
7564 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
7567 case CXToken_Punctuation:
7568 case CXToken_Comment:
7569 break;
7572 if (isNotUsableTU(TU)) {
7573 LOG_BAD_TU(TU);
7574 return cxstring::createEmpty();
7577 // We have to find the starting buffer pointer the hard way, by
7578 // deconstructing the source location.
7579 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
7580 if (!CXXUnit)
7581 return cxstring::createEmpty();
7583 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
7584 std::pair<FileID, unsigned> LocInfo =
7585 CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
7586 bool Invalid = false;
7587 StringRef Buffer =
7588 CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
7589 if (Invalid)
7590 return cxstring::createEmpty();
7592 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
7595 CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
7596 if (isNotUsableTU(TU)) {
7597 LOG_BAD_TU(TU);
7598 return clang_getNullLocation();
7601 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
7602 if (!CXXUnit)
7603 return clang_getNullLocation();
7605 return cxloc::translateSourceLocation(
7606 CXXUnit->getASTContext(),
7607 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
7610 CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
7611 if (isNotUsableTU(TU)) {
7612 LOG_BAD_TU(TU);
7613 return clang_getNullRange();
7616 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
7617 if (!CXXUnit)
7618 return clang_getNullRange();
7620 return cxloc::translateSourceRange(
7621 CXXUnit->getASTContext(),
7622 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
7625 static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
7626 SmallVectorImpl<CXToken> &CXTokens) {
7627 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7628 std::pair<FileID, unsigned> BeginLocInfo =
7629 SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
7630 std::pair<FileID, unsigned> EndLocInfo =
7631 SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
7633 // Cannot tokenize across files.
7634 if (BeginLocInfo.first != EndLocInfo.first)
7635 return;
7637 // Create a lexer
7638 bool Invalid = false;
7639 StringRef Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7640 if (Invalid)
7641 return;
7643 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7644 CXXUnit->getASTContext().getLangOpts(), Buffer.begin(),
7645 Buffer.data() + BeginLocInfo.second, Buffer.end());
7646 Lex.SetCommentRetentionState(true);
7648 // Lex tokens until we hit the end of the range.
7649 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
7650 Token Tok;
7651 bool previousWasAt = false;
7652 do {
7653 // Lex the next token
7654 Lex.LexFromRawLexer(Tok);
7655 if (Tok.is(tok::eof))
7656 break;
7658 // Initialize the CXToken.
7659 CXToken CXTok;
7661 // - Common fields
7662 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
7663 CXTok.int_data[2] = Tok.getLength();
7664 CXTok.int_data[3] = 0;
7666 // - Kind-specific fields
7667 if (Tok.isLiteral()) {
7668 CXTok.int_data[0] = CXToken_Literal;
7669 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
7670 } else if (Tok.is(tok::raw_identifier)) {
7671 // Lookup the identifier to determine whether we have a keyword.
7672 IdentifierInfo *II = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
7674 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
7675 CXTok.int_data[0] = CXToken_Keyword;
7676 } else {
7677 CXTok.int_data[0] =
7678 Tok.is(tok::identifier) ? CXToken_Identifier : CXToken_Keyword;
7680 CXTok.ptr_data = II;
7681 } else if (Tok.is(tok::comment)) {
7682 CXTok.int_data[0] = CXToken_Comment;
7683 CXTok.ptr_data = nullptr;
7684 } else {
7685 CXTok.int_data[0] = CXToken_Punctuation;
7686 CXTok.ptr_data = nullptr;
7688 CXTokens.push_back(CXTok);
7689 previousWasAt = Tok.is(tok::at);
7690 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
7693 CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
7694 LOG_FUNC_SECTION { *Log << TU << ' ' << Location; }
7696 if (isNotUsableTU(TU)) {
7697 LOG_BAD_TU(TU);
7698 return nullptr;
7701 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
7702 if (!CXXUnit)
7703 return nullptr;
7705 SourceLocation Begin = cxloc::translateSourceLocation(Location);
7706 if (Begin.isInvalid())
7707 return nullptr;
7708 SourceManager &SM = CXXUnit->getSourceManager();
7709 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
7710 DecomposedEnd.second +=
7711 Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
7713 SourceLocation End =
7714 SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
7716 SmallVector<CXToken, 32> CXTokens;
7717 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
7719 if (CXTokens.empty())
7720 return nullptr;
7722 CXTokens.resize(1);
7723 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
7725 memmove(Token, CXTokens.data(), sizeof(CXToken));
7726 return Token;
7729 void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range, CXToken **Tokens,
7730 unsigned *NumTokens) {
7731 LOG_FUNC_SECTION { *Log << TU << ' ' << Range; }
7733 if (Tokens)
7734 *Tokens = nullptr;
7735 if (NumTokens)
7736 *NumTokens = 0;
7738 if (isNotUsableTU(TU)) {
7739 LOG_BAD_TU(TU);
7740 return;
7743 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
7744 if (!CXXUnit || !Tokens || !NumTokens)
7745 return;
7747 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
7749 SourceRange R = cxloc::translateCXSourceRange(Range);
7750 if (R.isInvalid())
7751 return;
7753 SmallVector<CXToken, 32> CXTokens;
7754 getTokens(CXXUnit, R, CXTokens);
7756 if (CXTokens.empty())
7757 return;
7759 *Tokens = static_cast<CXToken *>(
7760 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
7761 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
7762 *NumTokens = CXTokens.size();
7765 void clang_disposeTokens(CXTranslationUnit TU, CXToken *Tokens,
7766 unsigned NumTokens) {
7767 free(Tokens);
7770 //===----------------------------------------------------------------------===//
7771 // Token annotation APIs.
7772 //===----------------------------------------------------------------------===//
7774 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7775 CXCursor parent,
7776 CXClientData client_data);
7777 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7778 CXClientData client_data);
7780 namespace {
7781 class AnnotateTokensWorker {
7782 CXToken *Tokens;
7783 CXCursor *Cursors;
7784 unsigned NumTokens;
7785 unsigned TokIdx;
7786 unsigned PreprocessingTokIdx;
7787 CursorVisitor AnnotateVis;
7788 SourceManager &SrcMgr;
7789 bool HasContextSensitiveKeywords;
7791 struct PostChildrenAction {
7792 CXCursor cursor;
7793 enum Action { Invalid, Ignore, Postpone } action;
7795 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
7797 struct PostChildrenInfo {
7798 CXCursor Cursor;
7799 SourceRange CursorRange;
7800 unsigned BeforeReachingCursorIdx;
7801 unsigned BeforeChildrenTokenIdx;
7802 PostChildrenActions ChildActions;
7804 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
7806 CXToken &getTok(unsigned Idx) {
7807 assert(Idx < NumTokens);
7808 return Tokens[Idx];
7810 const CXToken &getTok(unsigned Idx) const {
7811 assert(Idx < NumTokens);
7812 return Tokens[Idx];
7814 bool MoreTokens() const { return TokIdx < NumTokens; }
7815 unsigned NextToken() const { return TokIdx; }
7816 void AdvanceToken() { ++TokIdx; }
7817 SourceLocation GetTokenLoc(unsigned tokI) {
7818 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
7820 bool isFunctionMacroToken(unsigned tokI) const {
7821 return getTok(tokI).int_data[3] != 0;
7823 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
7824 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
7827 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
7828 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
7829 SourceRange);
7831 public:
7832 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
7833 CXTranslationUnit TU, SourceRange RegionOfInterest)
7834 : Tokens(tokens), Cursors(cursors), NumTokens(numTokens), TokIdx(0),
7835 PreprocessingTokIdx(0),
7836 AnnotateVis(TU, AnnotateTokensVisitor, this,
7837 /*VisitPreprocessorLast=*/true,
7838 /*VisitIncludedEntities=*/false, RegionOfInterest,
7839 /*VisitDeclsOnly=*/false,
7840 AnnotateTokensPostChildrenVisitor),
7841 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
7842 HasContextSensitiveKeywords(false) {}
7844 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
7845 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
7846 bool IsIgnoredChildCursor(CXCursor cursor) const;
7847 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
7849 bool postVisitChildren(CXCursor cursor);
7850 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
7851 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
7853 void AnnotateTokens();
7855 /// Determine whether the annotator saw any cursors that have
7856 /// context-sensitive keywords.
7857 bool hasContextSensitiveKeywords() const {
7858 return HasContextSensitiveKeywords;
7861 ~AnnotateTokensWorker() { assert(PostChildrenInfos.empty()); }
7863 } // namespace
7865 void AnnotateTokensWorker::AnnotateTokens() {
7866 // Walk the AST within the region of interest, annotating tokens
7867 // along the way.
7868 AnnotateVis.visitFileRegion();
7871 bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
7872 if (PostChildrenInfos.empty())
7873 return false;
7875 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
7876 if (ChildAction.cursor == cursor &&
7877 ChildAction.action == PostChildrenAction::Ignore) {
7878 return true;
7882 return false;
7885 const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
7886 if (!clang_isExpression(Cursor.kind))
7887 return nullptr;
7889 const Expr *E = getCursorExpr(Cursor);
7890 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
7891 const OverloadedOperatorKind Kind = OCE->getOperator();
7892 if (Kind == OO_Call || Kind == OO_Subscript)
7893 return OCE;
7896 return nullptr;
7899 AnnotateTokensWorker::PostChildrenActions
7900 AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
7901 PostChildrenActions actions;
7903 // The DeclRefExpr of CXXOperatorCallExpr referring to the custom operator is
7904 // visited before the arguments to the operator call. For the Call and
7905 // Subscript operator the range of this DeclRefExpr includes the whole call
7906 // expression, so that all tokens in that range would be mapped to the
7907 // operator function, including the tokens of the arguments. To avoid that,
7908 // ensure to visit this DeclRefExpr as last node.
7909 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
7910 const Expr *Callee = OCE->getCallee();
7911 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
7912 const Expr *SubExpr = ICE->getSubExpr();
7913 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
7914 const Decl *parentDecl = getCursorDecl(Cursor);
7915 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
7917 // Visit the DeclRefExpr as last.
7918 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
7919 actions.push_back({cxChild, PostChildrenAction::Postpone});
7921 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
7922 // wide range as the DeclRefExpr. We can skip visiting this entirely.
7923 cxChild = MakeCXCursor(ICE, parentDecl, TU);
7924 actions.push_back({cxChild, PostChildrenAction::Ignore});
7929 return actions;
7932 static inline void updateCursorAnnotation(CXCursor &Cursor,
7933 const CXCursor &updateC) {
7934 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
7935 return;
7936 Cursor = updateC;
7939 /// It annotates and advances tokens with a cursor until the comparison
7940 //// between the cursor location and the source range is the same as
7941 /// \arg compResult.
7943 /// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
7944 /// Pass RangeOverlap to annotate tokens inside a range.
7945 void AnnotateTokensWorker::annotateAndAdvanceTokens(
7946 CXCursor updateC, RangeComparisonResult compResult, SourceRange range) {
7947 while (MoreTokens()) {
7948 const unsigned I = NextToken();
7949 if (isFunctionMacroToken(I))
7950 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
7951 return;
7953 SourceLocation TokLoc = GetTokenLoc(I);
7954 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7955 updateCursorAnnotation(Cursors[I], updateC);
7956 AdvanceToken();
7957 continue;
7959 break;
7963 /// Special annotation handling for macro argument tokens.
7964 /// \returns true if it advanced beyond all macro tokens, false otherwise.
7965 bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
7966 CXCursor updateC, RangeComparisonResult compResult, SourceRange range) {
7967 assert(MoreTokens());
7968 assert(isFunctionMacroToken(NextToken()) &&
7969 "Should be called only for macro arg tokens");
7971 // This works differently than annotateAndAdvanceTokens; because expanded
7972 // macro arguments can have arbitrary translation-unit source order, we do not
7973 // advance the token index one by one until a token fails the range test.
7974 // We only advance once past all of the macro arg tokens if all of them
7975 // pass the range test. If one of them fails we keep the token index pointing
7976 // at the start of the macro arg tokens so that the failing token will be
7977 // annotated by a subsequent annotation try.
7979 bool atLeastOneCompFail = false;
7981 unsigned I = NextToken();
7982 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7983 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7984 if (TokLoc.isFileID())
7985 continue; // not macro arg token, it's parens or comma.
7986 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7987 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7988 Cursors[I] = updateC;
7989 } else
7990 atLeastOneCompFail = true;
7993 if (atLeastOneCompFail)
7994 return false;
7996 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7997 return true;
8000 enum CXChildVisitResult AnnotateTokensWorker::Visit(CXCursor cursor,
8001 CXCursor parent) {
8002 SourceRange cursorRange = getRawCursorExtent(cursor);
8003 if (cursorRange.isInvalid())
8004 return CXChildVisit_Recurse;
8006 if (IsIgnoredChildCursor(cursor))
8007 return CXChildVisit_Continue;
8009 if (!HasContextSensitiveKeywords) {
8010 // Objective-C properties can have context-sensitive keywords.
8011 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
8012 if (const ObjCPropertyDecl *Property =
8013 dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
8014 HasContextSensitiveKeywords =
8015 Property->getPropertyAttributesAsWritten() != 0;
8017 // Objective-C methods can have context-sensitive keywords.
8018 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
8019 cursor.kind == CXCursor_ObjCClassMethodDecl) {
8020 if (const ObjCMethodDecl *Method =
8021 dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
8022 if (Method->getObjCDeclQualifier())
8023 HasContextSensitiveKeywords = true;
8024 else {
8025 for (const auto *P : Method->parameters()) {
8026 if (P->getObjCDeclQualifier()) {
8027 HasContextSensitiveKeywords = true;
8028 break;
8034 // C++ methods can have context-sensitive keywords.
8035 else if (cursor.kind == CXCursor_CXXMethod) {
8036 if (const CXXMethodDecl *Method =
8037 dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
8038 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
8039 HasContextSensitiveKeywords = true;
8042 // C++ classes can have context-sensitive keywords.
8043 else if (cursor.kind == CXCursor_StructDecl ||
8044 cursor.kind == CXCursor_ClassDecl ||
8045 cursor.kind == CXCursor_ClassTemplate ||
8046 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
8047 if (const Decl *D = getCursorDecl(cursor))
8048 if (D->hasAttr<FinalAttr>())
8049 HasContextSensitiveKeywords = true;
8053 // Don't override a property annotation with its getter/setter method.
8054 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
8055 parent.kind == CXCursor_ObjCPropertyDecl)
8056 return CXChildVisit_Continue;
8058 if (clang_isPreprocessing(cursor.kind)) {
8059 // Items in the preprocessing record are kept separate from items in
8060 // declarations, so we keep a separate token index.
8061 unsigned SavedTokIdx = TokIdx;
8062 TokIdx = PreprocessingTokIdx;
8064 // Skip tokens up until we catch up to the beginning of the preprocessing
8065 // entry.
8066 while (MoreTokens()) {
8067 const unsigned I = NextToken();
8068 SourceLocation TokLoc = GetTokenLoc(I);
8069 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
8070 case RangeBefore:
8071 AdvanceToken();
8072 continue;
8073 case RangeAfter:
8074 case RangeOverlap:
8075 break;
8077 break;
8080 // Look at all of the tokens within this range.
8081 while (MoreTokens()) {
8082 const unsigned I = NextToken();
8083 SourceLocation TokLoc = GetTokenLoc(I);
8084 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
8085 case RangeBefore:
8086 llvm_unreachable("Infeasible");
8087 case RangeAfter:
8088 break;
8089 case RangeOverlap:
8090 // For macro expansions, just note where the beginning of the macro
8091 // expansion occurs.
8092 if (cursor.kind == CXCursor_MacroExpansion) {
8093 if (TokLoc == cursorRange.getBegin())
8094 Cursors[I] = cursor;
8095 AdvanceToken();
8096 break;
8098 // We may have already annotated macro names inside macro definitions.
8099 if (Cursors[I].kind != CXCursor_MacroExpansion)
8100 Cursors[I] = cursor;
8101 AdvanceToken();
8102 continue;
8104 break;
8107 // Save the preprocessing token index; restore the non-preprocessing
8108 // token index.
8109 PreprocessingTokIdx = TokIdx;
8110 TokIdx = SavedTokIdx;
8111 return CXChildVisit_Recurse;
8114 if (cursorRange.isInvalid())
8115 return CXChildVisit_Continue;
8117 unsigned BeforeReachingCursorIdx = NextToken();
8118 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
8119 const enum CXCursorKind K = clang_getCursorKind(parent);
8120 const CXCursor updateC =
8121 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
8122 // Attributes are annotated out-of-order, skip tokens until we reach it.
8123 clang_isAttribute(cursor.kind))
8124 ? clang_getNullCursor()
8125 : parent;
8127 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
8129 // Avoid having the cursor of an expression "overwrite" the annotation of the
8130 // variable declaration that it belongs to.
8131 // This can happen for C++ constructor expressions whose range generally
8132 // include the variable declaration, e.g.:
8133 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
8134 if (clang_isExpression(cursorK) && MoreTokens()) {
8135 const Expr *E = getCursorExpr(cursor);
8136 if (const Decl *D = getCursorDecl(cursor)) {
8137 const unsigned I = NextToken();
8138 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
8139 E->getBeginLoc() == D->getLocation() &&
8140 E->getBeginLoc() == GetTokenLoc(I)) {
8141 updateCursorAnnotation(Cursors[I], updateC);
8142 AdvanceToken();
8147 // Before recursing into the children keep some state that we are going
8148 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
8149 // extra work after the child nodes are visited.
8150 // Note that we don't call VisitChildren here to avoid traversing statements
8151 // code-recursively which can blow the stack.
8153 PostChildrenInfo Info;
8154 Info.Cursor = cursor;
8155 Info.CursorRange = cursorRange;
8156 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
8157 Info.BeforeChildrenTokenIdx = NextToken();
8158 Info.ChildActions = DetermineChildActions(cursor);
8159 PostChildrenInfos.push_back(Info);
8161 return CXChildVisit_Recurse;
8164 bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
8165 if (PostChildrenInfos.empty())
8166 return false;
8167 const PostChildrenInfo &Info = PostChildrenInfos.back();
8168 if (!clang_equalCursors(Info.Cursor, cursor))
8169 return false;
8171 HandlePostPonedChildCursors(Info);
8173 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
8174 const unsigned AfterChildren = NextToken();
8175 SourceRange cursorRange = Info.CursorRange;
8177 // Scan the tokens that are at the end of the cursor, but are not captured
8178 // but the child cursors.
8179 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
8181 // Scan the tokens that are at the beginning of the cursor, but are not
8182 // capture by the child cursors.
8183 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
8184 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
8185 break;
8187 Cursors[I] = cursor;
8190 // Attributes are annotated out-of-order, rewind TokIdx to when we first
8191 // encountered the attribute cursor.
8192 if (clang_isAttribute(cursor.kind))
8193 TokIdx = Info.BeforeReachingCursorIdx;
8195 PostChildrenInfos.pop_back();
8196 return false;
8199 void AnnotateTokensWorker::HandlePostPonedChildCursors(
8200 const PostChildrenInfo &Info) {
8201 for (const auto &ChildAction : Info.ChildActions) {
8202 if (ChildAction.action == PostChildrenAction::Postpone) {
8203 HandlePostPonedChildCursor(ChildAction.cursor,
8204 Info.BeforeChildrenTokenIdx);
8209 void AnnotateTokensWorker::HandlePostPonedChildCursor(
8210 CXCursor Cursor, unsigned StartTokenIndex) {
8211 unsigned I = StartTokenIndex;
8213 // The bracket tokens of a Call or Subscript operator are mapped to
8214 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
8215 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
8216 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
8217 const CXSourceRange CXRefNameRange = clang_getCursorReferenceNameRange(
8218 Cursor, CXNameRange_WantQualifier, RefNameRangeNr);
8219 if (clang_Range_isNull(CXRefNameRange))
8220 break; // All ranges handled.
8222 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
8223 while (I < NumTokens) {
8224 const SourceLocation TokenLocation = GetTokenLoc(I);
8225 if (!TokenLocation.isValid())
8226 break;
8228 // Adapt the end range, because LocationCompare() reports
8229 // RangeOverlap even for the not-inclusive end location.
8230 const SourceLocation fixedEnd =
8231 RefNameRange.getEnd().getLocWithOffset(-1);
8232 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
8234 const RangeComparisonResult ComparisonResult =
8235 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
8237 if (ComparisonResult == RangeOverlap) {
8238 Cursors[I++] = Cursor;
8239 } else if (ComparisonResult == RangeBefore) {
8240 ++I; // Not relevant token, check next one.
8241 } else if (ComparisonResult == RangeAfter) {
8242 break; // All tokens updated for current range, check next.
8248 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
8249 CXCursor parent,
8250 CXClientData client_data) {
8251 return static_cast<AnnotateTokensWorker *>(client_data)
8252 ->Visit(cursor, parent);
8255 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
8256 CXClientData client_data) {
8257 return static_cast<AnnotateTokensWorker *>(client_data)
8258 ->postVisitChildren(cursor);
8261 namespace {
8263 /// Uses the macro expansions in the preprocessing record to find
8264 /// and mark tokens that are macro arguments. This info is used by the
8265 /// AnnotateTokensWorker.
8266 class MarkMacroArgTokensVisitor {
8267 SourceManager &SM;
8268 CXToken *Tokens;
8269 unsigned NumTokens;
8270 unsigned CurIdx;
8272 public:
8273 MarkMacroArgTokensVisitor(SourceManager &SM, CXToken *tokens,
8274 unsigned numTokens)
8275 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) {}
8277 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
8278 if (cursor.kind != CXCursor_MacroExpansion)
8279 return CXChildVisit_Continue;
8281 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
8282 if (macroRange.getBegin() == macroRange.getEnd())
8283 return CXChildVisit_Continue; // it's not a function macro.
8285 for (; CurIdx < NumTokens; ++CurIdx) {
8286 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
8287 macroRange.getBegin()))
8288 break;
8291 if (CurIdx == NumTokens)
8292 return CXChildVisit_Break;
8294 for (; CurIdx < NumTokens; ++CurIdx) {
8295 SourceLocation tokLoc = getTokenLoc(CurIdx);
8296 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
8297 break;
8299 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
8302 if (CurIdx == NumTokens)
8303 return CXChildVisit_Break;
8305 return CXChildVisit_Continue;
8308 private:
8309 CXToken &getTok(unsigned Idx) {
8310 assert(Idx < NumTokens);
8311 return Tokens[Idx];
8313 const CXToken &getTok(unsigned Idx) const {
8314 assert(Idx < NumTokens);
8315 return Tokens[Idx];
8318 SourceLocation getTokenLoc(unsigned tokI) {
8319 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
8322 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
8323 // The third field is reserved and currently not used. Use it here
8324 // to mark macro arg expanded tokens with their expanded locations.
8325 getTok(tokI).int_data[3] = loc.getRawEncoding();
8329 } // end anonymous namespace
8331 static CXChildVisitResult
8332 MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
8333 CXClientData client_data) {
8334 return static_cast<MarkMacroArgTokensVisitor *>(client_data)
8335 ->visit(cursor, parent);
8338 /// Used by \c annotatePreprocessorTokens.
8339 /// \returns true if lexing was finished, false otherwise.
8340 static bool lexNext(Lexer &Lex, Token &Tok, unsigned &NextIdx,
8341 unsigned NumTokens) {
8342 if (NextIdx >= NumTokens)
8343 return true;
8345 ++NextIdx;
8346 Lex.LexFromRawLexer(Tok);
8347 return Tok.is(tok::eof);
8350 static void annotatePreprocessorTokens(CXTranslationUnit TU,
8351 SourceRange RegionOfInterest,
8352 CXCursor *Cursors, CXToken *Tokens,
8353 unsigned NumTokens) {
8354 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
8356 Preprocessor &PP = CXXUnit->getPreprocessor();
8357 SourceManager &SourceMgr = CXXUnit->getSourceManager();
8358 std::pair<FileID, unsigned> BeginLocInfo =
8359 SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
8360 std::pair<FileID, unsigned> EndLocInfo =
8361 SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
8363 if (BeginLocInfo.first != EndLocInfo.first)
8364 return;
8366 StringRef Buffer;
8367 bool Invalid = false;
8368 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
8369 if (Buffer.empty() || Invalid)
8370 return;
8372 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
8373 CXXUnit->getASTContext().getLangOpts(), Buffer.begin(),
8374 Buffer.data() + BeginLocInfo.second, Buffer.end());
8375 Lex.SetCommentRetentionState(true);
8377 unsigned NextIdx = 0;
8378 // Lex tokens in raw mode until we hit the end of the range, to avoid
8379 // entering #includes or expanding macros.
8380 while (true) {
8381 Token Tok;
8382 if (lexNext(Lex, Tok, NextIdx, NumTokens))
8383 break;
8384 unsigned TokIdx = NextIdx - 1;
8385 assert(Tok.getLocation() ==
8386 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
8388 reprocess:
8389 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
8390 // We have found a preprocessing directive. Annotate the tokens
8391 // appropriately.
8393 // FIXME: Some simple tests here could identify macro definitions and
8394 // #undefs, to provide specific cursor kinds for those.
8396 SourceLocation BeginLoc = Tok.getLocation();
8397 if (lexNext(Lex, Tok, NextIdx, NumTokens))
8398 break;
8400 MacroInfo *MI = nullptr;
8401 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
8402 if (lexNext(Lex, Tok, NextIdx, NumTokens))
8403 break;
8405 if (Tok.is(tok::raw_identifier)) {
8406 IdentifierInfo &II =
8407 PP.getIdentifierTable().get(Tok.getRawIdentifier());
8408 SourceLocation MappedTokLoc =
8409 CXXUnit->mapLocationToPreamble(Tok.getLocation());
8410 MI = getMacroInfo(II, MappedTokLoc, TU);
8414 bool finished = false;
8415 do {
8416 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
8417 finished = true;
8418 break;
8420 // If we are in a macro definition, check if the token was ever a
8421 // macro name and annotate it if that's the case.
8422 if (MI) {
8423 SourceLocation SaveLoc = Tok.getLocation();
8424 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
8425 MacroDefinitionRecord *MacroDef =
8426 checkForMacroInMacroDefinition(MI, Tok, TU);
8427 Tok.setLocation(SaveLoc);
8428 if (MacroDef)
8429 Cursors[NextIdx - 1] =
8430 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
8432 } while (!Tok.isAtStartOfLine());
8434 unsigned LastIdx = finished ? NextIdx - 1 : NextIdx - 2;
8435 assert(TokIdx <= LastIdx);
8436 SourceLocation EndLoc =
8437 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
8438 CXCursor Cursor =
8439 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
8441 for (; TokIdx <= LastIdx; ++TokIdx)
8442 updateCursorAnnotation(Cursors[TokIdx], Cursor);
8444 if (finished)
8445 break;
8446 goto reprocess;
8451 // This gets run a separate thread to avoid stack blowout.
8452 static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
8453 CXToken *Tokens, unsigned NumTokens,
8454 CXCursor *Cursors) {
8455 CIndexer *CXXIdx = TU->CIdx;
8456 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
8457 setThreadBackgroundPriority();
8459 // Determine the region of interest, which contains all of the tokens.
8460 SourceRange RegionOfInterest;
8461 RegionOfInterest.setBegin(
8462 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
8463 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
8464 clang_getTokenLocation(TU, Tokens[NumTokens - 1])));
8466 // Relex the tokens within the source range to look for preprocessing
8467 // directives.
8468 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
8470 // If begin location points inside a macro argument, set it to the expansion
8471 // location so we can have the full context when annotating semantically.
8473 SourceManager &SM = CXXUnit->getSourceManager();
8474 SourceLocation Loc =
8475 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
8476 if (Loc.isMacroID())
8477 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
8480 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
8481 // Search and mark tokens that are macro argument expansions.
8482 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(), Tokens,
8483 NumTokens);
8484 CursorVisitor MacroArgMarker(
8485 TU, MarkMacroArgTokensVisitorDelegate, &Visitor,
8486 /*VisitPreprocessorLast=*/true,
8487 /*VisitIncludedEntities=*/false, RegionOfInterest);
8488 MacroArgMarker.visitPreprocessedEntitiesInRegion();
8491 // Annotate all of the source locations in the region of interest that map to
8492 // a specific cursor.
8493 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
8495 // FIXME: We use a ridiculous stack size here because the data-recursion
8496 // algorithm uses a large stack frame than the non-data recursive version,
8497 // and AnnotationTokensWorker currently transforms the data-recursion
8498 // algorithm back into a traditional recursion by explicitly calling
8499 // VisitChildren(). We will need to remove this explicit recursive call.
8500 W.AnnotateTokens();
8502 // If we ran into any entities that involve context-sensitive keywords,
8503 // take another pass through the tokens to mark them as such.
8504 if (W.hasContextSensitiveKeywords()) {
8505 for (unsigned I = 0; I != NumTokens; ++I) {
8506 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
8507 continue;
8509 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
8510 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
8511 if (const ObjCPropertyDecl *Property =
8512 dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
8513 if (Property->getPropertyAttributesAsWritten() != 0 &&
8514 llvm::StringSwitch<bool>(II->getName())
8515 .Case("readonly", true)
8516 .Case("assign", true)
8517 .Case("unsafe_unretained", true)
8518 .Case("readwrite", true)
8519 .Case("retain", true)
8520 .Case("copy", true)
8521 .Case("nonatomic", true)
8522 .Case("atomic", true)
8523 .Case("getter", true)
8524 .Case("setter", true)
8525 .Case("strong", true)
8526 .Case("weak", true)
8527 .Case("class", true)
8528 .Default(false))
8529 Tokens[I].int_data[0] = CXToken_Keyword;
8531 continue;
8534 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
8535 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
8536 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
8537 if (llvm::StringSwitch<bool>(II->getName())
8538 .Case("in", true)
8539 .Case("out", true)
8540 .Case("inout", true)
8541 .Case("oneway", true)
8542 .Case("bycopy", true)
8543 .Case("byref", true)
8544 .Default(false))
8545 Tokens[I].int_data[0] = CXToken_Keyword;
8546 continue;
8549 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
8550 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
8551 Tokens[I].int_data[0] = CXToken_Keyword;
8552 continue;
8558 void clang_annotateTokens(CXTranslationUnit TU, CXToken *Tokens,
8559 unsigned NumTokens, CXCursor *Cursors) {
8560 if (isNotUsableTU(TU)) {
8561 LOG_BAD_TU(TU);
8562 return;
8564 if (NumTokens == 0 || !Tokens || !Cursors) {
8565 LOG_FUNC_SECTION { *Log << "<null input>"; }
8566 return;
8569 LOG_FUNC_SECTION {
8570 *Log << TU << ' ';
8571 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
8572 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens - 1]);
8573 *Log << clang_getRange(bloc, eloc);
8576 // Any token we don't specifically annotate will have a NULL cursor.
8577 CXCursor C = clang_getNullCursor();
8578 for (unsigned I = 0; I != NumTokens; ++I)
8579 Cursors[I] = C;
8581 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
8582 if (!CXXUnit)
8583 return;
8585 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
8587 auto AnnotateTokensImpl = [=]() {
8588 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
8590 llvm::CrashRecoveryContext CRC;
8591 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
8592 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
8596 //===----------------------------------------------------------------------===//
8597 // Operations for querying linkage of a cursor.
8598 //===----------------------------------------------------------------------===//
8600 CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
8601 if (!clang_isDeclaration(cursor.kind))
8602 return CXLinkage_Invalid;
8604 const Decl *D = cxcursor::getCursorDecl(cursor);
8605 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
8606 switch (ND->getLinkageInternal()) {
8607 case Linkage::Invalid:
8608 return CXLinkage_Invalid;
8609 case Linkage::None:
8610 case Linkage::VisibleNone:
8611 return CXLinkage_NoLinkage;
8612 case Linkage::Internal:
8613 return CXLinkage_Internal;
8614 case Linkage::UniqueExternal:
8615 return CXLinkage_UniqueExternal;
8616 case Linkage::Module:
8617 case Linkage::External:
8618 return CXLinkage_External;
8621 return CXLinkage_Invalid;
8624 //===----------------------------------------------------------------------===//
8625 // Operations for querying visibility of a cursor.
8626 //===----------------------------------------------------------------------===//
8628 CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
8629 if (!clang_isDeclaration(cursor.kind))
8630 return CXVisibility_Invalid;
8632 const Decl *D = cxcursor::getCursorDecl(cursor);
8633 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
8634 switch (ND->getVisibility()) {
8635 case HiddenVisibility:
8636 return CXVisibility_Hidden;
8637 case ProtectedVisibility:
8638 return CXVisibility_Protected;
8639 case DefaultVisibility:
8640 return CXVisibility_Default;
8643 return CXVisibility_Invalid;
8646 //===----------------------------------------------------------------------===//
8647 // Operations for querying language of a cursor.
8648 //===----------------------------------------------------------------------===//
8650 static CXLanguageKind getDeclLanguage(const Decl *D) {
8651 if (!D)
8652 return CXLanguage_C;
8654 switch (D->getKind()) {
8655 default:
8656 break;
8657 case Decl::ImplicitParam:
8658 case Decl::ObjCAtDefsField:
8659 case Decl::ObjCCategory:
8660 case Decl::ObjCCategoryImpl:
8661 case Decl::ObjCCompatibleAlias:
8662 case Decl::ObjCImplementation:
8663 case Decl::ObjCInterface:
8664 case Decl::ObjCIvar:
8665 case Decl::ObjCMethod:
8666 case Decl::ObjCProperty:
8667 case Decl::ObjCPropertyImpl:
8668 case Decl::ObjCProtocol:
8669 case Decl::ObjCTypeParam:
8670 return CXLanguage_ObjC;
8671 case Decl::CXXConstructor:
8672 case Decl::CXXConversion:
8673 case Decl::CXXDestructor:
8674 case Decl::CXXMethod:
8675 case Decl::CXXRecord:
8676 case Decl::ClassTemplate:
8677 case Decl::ClassTemplatePartialSpecialization:
8678 case Decl::ClassTemplateSpecialization:
8679 case Decl::Friend:
8680 case Decl::FriendTemplate:
8681 case Decl::FunctionTemplate:
8682 case Decl::LinkageSpec:
8683 case Decl::Namespace:
8684 case Decl::NamespaceAlias:
8685 case Decl::NonTypeTemplateParm:
8686 case Decl::StaticAssert:
8687 case Decl::TemplateTemplateParm:
8688 case Decl::TemplateTypeParm:
8689 case Decl::UnresolvedUsingTypename:
8690 case Decl::UnresolvedUsingValue:
8691 case Decl::Using:
8692 case Decl::UsingDirective:
8693 case Decl::UsingShadow:
8694 return CXLanguage_CPlusPlus;
8697 return CXLanguage_C;
8700 static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
8701 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
8702 return CXAvailability_NotAvailable;
8704 switch (D->getAvailability()) {
8705 case AR_Available:
8706 case AR_NotYetIntroduced:
8707 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
8708 return getCursorAvailabilityForDecl(
8709 cast<Decl>(EnumConst->getDeclContext()));
8710 return CXAvailability_Available;
8712 case AR_Deprecated:
8713 return CXAvailability_Deprecated;
8715 case AR_Unavailable:
8716 return CXAvailability_NotAvailable;
8719 llvm_unreachable("Unknown availability kind!");
8722 enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
8723 if (clang_isDeclaration(cursor.kind))
8724 if (const Decl *D = cxcursor::getCursorDecl(cursor))
8725 return getCursorAvailabilityForDecl(D);
8727 return CXAvailability_Available;
8730 static CXVersion convertVersion(VersionTuple In) {
8731 CXVersion Out = {-1, -1, -1};
8732 if (In.empty())
8733 return Out;
8735 Out.Major = In.getMajor();
8737 std::optional<unsigned> Minor = In.getMinor();
8738 if (Minor)
8739 Out.Minor = *Minor;
8740 else
8741 return Out;
8743 std::optional<unsigned> Subminor = In.getSubminor();
8744 if (Subminor)
8745 Out.Subminor = *Subminor;
8747 return Out;
8750 static void getCursorPlatformAvailabilityForDecl(
8751 const Decl *D, int *always_deprecated, CXString *deprecated_message,
8752 int *always_unavailable, CXString *unavailable_message,
8753 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
8754 bool HadAvailAttr = false;
8755 for (auto A : D->attrs()) {
8756 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
8757 HadAvailAttr = true;
8758 if (always_deprecated)
8759 *always_deprecated = 1;
8760 if (deprecated_message) {
8761 clang_disposeString(*deprecated_message);
8762 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
8764 continue;
8767 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
8768 HadAvailAttr = true;
8769 if (always_unavailable)
8770 *always_unavailable = 1;
8771 if (unavailable_message) {
8772 clang_disposeString(*unavailable_message);
8773 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
8775 continue;
8778 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
8779 AvailabilityAttrs.push_back(Avail);
8780 HadAvailAttr = true;
8784 if (!HadAvailAttr)
8785 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
8786 return getCursorPlatformAvailabilityForDecl(
8787 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
8788 deprecated_message, always_unavailable, unavailable_message,
8789 AvailabilityAttrs);
8791 // If no availability attributes are found, inherit the attribute from the
8792 // containing decl or the class or category interface decl.
8793 if (AvailabilityAttrs.empty()) {
8794 const ObjCContainerDecl *CD = nullptr;
8795 const DeclContext *DC = D->getDeclContext();
8797 if (auto *IMD = dyn_cast<ObjCImplementationDecl>(D))
8798 CD = IMD->getClassInterface();
8799 else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(D))
8800 CD = CatD->getClassInterface();
8801 else if (auto *IMD = dyn_cast<ObjCCategoryImplDecl>(D))
8802 CD = IMD->getCategoryDecl();
8803 else if (auto *ID = dyn_cast<ObjCInterfaceDecl>(DC))
8804 CD = ID;
8805 else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(DC))
8806 CD = CatD;
8807 else if (auto *IMD = dyn_cast<ObjCImplementationDecl>(DC))
8808 CD = IMD->getClassInterface();
8809 else if (auto *IMD = dyn_cast<ObjCCategoryImplDecl>(DC))
8810 CD = IMD->getCategoryDecl();
8811 else if (auto *PD = dyn_cast<ObjCProtocolDecl>(DC))
8812 CD = PD;
8814 if (CD)
8815 getCursorPlatformAvailabilityForDecl(
8816 CD, always_deprecated, deprecated_message, always_unavailable,
8817 unavailable_message, AvailabilityAttrs);
8818 return;
8821 llvm::sort(
8822 AvailabilityAttrs, [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
8823 return LHS->getPlatform()->getName() < RHS->getPlatform()->getName();
8825 ASTContext &Ctx = D->getASTContext();
8826 auto It = std::unique(
8827 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
8828 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
8829 if (LHS->getPlatform() != RHS->getPlatform())
8830 return false;
8832 if (LHS->getIntroduced() == RHS->getIntroduced() &&
8833 LHS->getDeprecated() == RHS->getDeprecated() &&
8834 LHS->getObsoleted() == RHS->getObsoleted() &&
8835 LHS->getMessage() == RHS->getMessage() &&
8836 LHS->getReplacement() == RHS->getReplacement())
8837 return true;
8839 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
8840 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
8841 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
8842 return false;
8844 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
8845 LHS->setIntroduced(Ctx, RHS->getIntroduced());
8847 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
8848 LHS->setDeprecated(Ctx, RHS->getDeprecated());
8849 if (LHS->getMessage().empty())
8850 LHS->setMessage(Ctx, RHS->getMessage());
8851 if (LHS->getReplacement().empty())
8852 LHS->setReplacement(Ctx, RHS->getReplacement());
8855 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
8856 LHS->setObsoleted(Ctx, RHS->getObsoleted());
8857 if (LHS->getMessage().empty())
8858 LHS->setMessage(Ctx, RHS->getMessage());
8859 if (LHS->getReplacement().empty())
8860 LHS->setReplacement(Ctx, RHS->getReplacement());
8863 return true;
8865 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
8868 int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
8869 CXString *deprecated_message,
8870 int *always_unavailable,
8871 CXString *unavailable_message,
8872 CXPlatformAvailability *availability,
8873 int availability_size) {
8874 if (always_deprecated)
8875 *always_deprecated = 0;
8876 if (deprecated_message)
8877 *deprecated_message = cxstring::createEmpty();
8878 if (always_unavailable)
8879 *always_unavailable = 0;
8880 if (unavailable_message)
8881 *unavailable_message = cxstring::createEmpty();
8883 if (!clang_isDeclaration(cursor.kind))
8884 return 0;
8886 const Decl *D = cxcursor::getCursorDecl(cursor);
8887 if (!D)
8888 return 0;
8890 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
8891 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
8892 always_unavailable, unavailable_message,
8893 AvailabilityAttrs);
8894 for (const auto &Avail : llvm::enumerate(
8895 llvm::ArrayRef(AvailabilityAttrs).take_front(availability_size))) {
8896 availability[Avail.index()].Platform =
8897 cxstring::createDup(Avail.value()->getPlatform()->getName());
8898 availability[Avail.index()].Introduced =
8899 convertVersion(Avail.value()->getIntroduced());
8900 availability[Avail.index()].Deprecated =
8901 convertVersion(Avail.value()->getDeprecated());
8902 availability[Avail.index()].Obsoleted =
8903 convertVersion(Avail.value()->getObsoleted());
8904 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
8905 availability[Avail.index()].Message =
8906 cxstring::createDup(Avail.value()->getMessage());
8909 return AvailabilityAttrs.size();
8912 void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
8913 clang_disposeString(availability->Platform);
8914 clang_disposeString(availability->Message);
8917 CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
8918 if (clang_isDeclaration(cursor.kind))
8919 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
8921 return CXLanguage_Invalid;
8924 CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
8925 const Decl *D = cxcursor::getCursorDecl(cursor);
8926 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8927 switch (VD->getTLSKind()) {
8928 case VarDecl::TLS_None:
8929 return CXTLS_None;
8930 case VarDecl::TLS_Dynamic:
8931 return CXTLS_Dynamic;
8932 case VarDecl::TLS_Static:
8933 return CXTLS_Static;
8937 return CXTLS_None;
8940 /// If the given cursor is the "templated" declaration
8941 /// describing a class or function template, return the class or
8942 /// function template.
8943 static const Decl *maybeGetTemplateCursor(const Decl *D) {
8944 if (!D)
8945 return nullptr;
8947 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8948 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
8949 return FunTmpl;
8951 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
8952 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
8953 return ClassTmpl;
8955 return D;
8958 enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
8959 StorageClass sc = SC_None;
8960 const Decl *D = getCursorDecl(C);
8961 if (D) {
8962 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8963 sc = FD->getStorageClass();
8964 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8965 sc = VD->getStorageClass();
8966 } else {
8967 return CX_SC_Invalid;
8969 } else {
8970 return CX_SC_Invalid;
8972 switch (sc) {
8973 case SC_None:
8974 return CX_SC_None;
8975 case SC_Extern:
8976 return CX_SC_Extern;
8977 case SC_Static:
8978 return CX_SC_Static;
8979 case SC_PrivateExtern:
8980 return CX_SC_PrivateExtern;
8981 case SC_Auto:
8982 return CX_SC_Auto;
8983 case SC_Register:
8984 return CX_SC_Register;
8986 llvm_unreachable("Unhandled storage class!");
8989 CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
8990 if (clang_isDeclaration(cursor.kind)) {
8991 if (const Decl *D = getCursorDecl(cursor)) {
8992 const DeclContext *DC = D->getDeclContext();
8993 if (!DC)
8994 return clang_getNullCursor();
8996 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8997 getCursorTU(cursor));
9001 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
9002 if (const Decl *D = getCursorDecl(cursor))
9003 return MakeCXCursor(D, getCursorTU(cursor));
9006 return clang_getNullCursor();
9009 CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
9010 if (clang_isDeclaration(cursor.kind)) {
9011 if (const Decl *D = getCursorDecl(cursor)) {
9012 const DeclContext *DC = D->getLexicalDeclContext();
9013 if (!DC)
9014 return clang_getNullCursor();
9016 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
9017 getCursorTU(cursor));
9021 // FIXME: Note that we can't easily compute the lexical context of a
9022 // statement or expression, so we return nothing.
9023 return clang_getNullCursor();
9026 CXFile clang_getIncludedFile(CXCursor cursor) {
9027 if (cursor.kind != CXCursor_InclusionDirective)
9028 return nullptr;
9030 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
9031 return cxfile::makeCXFile(ID->getFile());
9034 unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
9035 if (C.kind != CXCursor_ObjCPropertyDecl)
9036 return CXObjCPropertyAttr_noattr;
9038 unsigned Result = CXObjCPropertyAttr_noattr;
9039 const auto *PD = cast<ObjCPropertyDecl>(getCursorDecl(C));
9040 ObjCPropertyAttribute::Kind Attr = PD->getPropertyAttributesAsWritten();
9042 #define SET_CXOBJCPROP_ATTR(A) \
9043 if (Attr & ObjCPropertyAttribute::kind_##A) \
9044 Result |= CXObjCPropertyAttr_##A
9045 SET_CXOBJCPROP_ATTR(readonly);
9046 SET_CXOBJCPROP_ATTR(getter);
9047 SET_CXOBJCPROP_ATTR(assign);
9048 SET_CXOBJCPROP_ATTR(readwrite);
9049 SET_CXOBJCPROP_ATTR(retain);
9050 SET_CXOBJCPROP_ATTR(copy);
9051 SET_CXOBJCPROP_ATTR(nonatomic);
9052 SET_CXOBJCPROP_ATTR(setter);
9053 SET_CXOBJCPROP_ATTR(atomic);
9054 SET_CXOBJCPROP_ATTR(weak);
9055 SET_CXOBJCPROP_ATTR(strong);
9056 SET_CXOBJCPROP_ATTR(unsafe_unretained);
9057 SET_CXOBJCPROP_ATTR(class);
9058 #undef SET_CXOBJCPROP_ATTR
9060 return Result;
9063 CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
9064 if (C.kind != CXCursor_ObjCPropertyDecl)
9065 return cxstring::createNull();
9067 const auto *PD = cast<ObjCPropertyDecl>(getCursorDecl(C));
9068 Selector sel = PD->getGetterName();
9069 if (sel.isNull())
9070 return cxstring::createNull();
9072 return cxstring::createDup(sel.getAsString());
9075 CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
9076 if (C.kind != CXCursor_ObjCPropertyDecl)
9077 return cxstring::createNull();
9079 const auto *PD = cast<ObjCPropertyDecl>(getCursorDecl(C));
9080 Selector sel = PD->getSetterName();
9081 if (sel.isNull())
9082 return cxstring::createNull();
9084 return cxstring::createDup(sel.getAsString());
9087 unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
9088 if (!clang_isDeclaration(C.kind))
9089 return CXObjCDeclQualifier_None;
9091 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
9092 const Decl *D = getCursorDecl(C);
9093 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
9094 QT = MD->getObjCDeclQualifier();
9095 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
9096 QT = PD->getObjCDeclQualifier();
9097 if (QT == Decl::OBJC_TQ_None)
9098 return CXObjCDeclQualifier_None;
9100 unsigned Result = CXObjCDeclQualifier_None;
9101 if (QT & Decl::OBJC_TQ_In)
9102 Result |= CXObjCDeclQualifier_In;
9103 if (QT & Decl::OBJC_TQ_Inout)
9104 Result |= CXObjCDeclQualifier_Inout;
9105 if (QT & Decl::OBJC_TQ_Out)
9106 Result |= CXObjCDeclQualifier_Out;
9107 if (QT & Decl::OBJC_TQ_Bycopy)
9108 Result |= CXObjCDeclQualifier_Bycopy;
9109 if (QT & Decl::OBJC_TQ_Byref)
9110 Result |= CXObjCDeclQualifier_Byref;
9111 if (QT & Decl::OBJC_TQ_Oneway)
9112 Result |= CXObjCDeclQualifier_Oneway;
9114 return Result;
9117 unsigned clang_Cursor_isObjCOptional(CXCursor C) {
9118 if (!clang_isDeclaration(C.kind))
9119 return 0;
9121 const Decl *D = getCursorDecl(C);
9122 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
9123 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
9124 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
9125 return MD->getImplementationControl() ==
9126 ObjCImplementationControl::Optional;
9128 return 0;
9131 unsigned clang_Cursor_isVariadic(CXCursor C) {
9132 if (!clang_isDeclaration(C.kind))
9133 return 0;
9135 const Decl *D = getCursorDecl(C);
9136 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9137 return FD->isVariadic();
9138 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
9139 return MD->isVariadic();
9141 return 0;
9144 unsigned clang_Cursor_isExternalSymbol(CXCursor C, CXString *language,
9145 CXString *definedIn,
9146 unsigned *isGenerated) {
9147 if (!clang_isDeclaration(C.kind))
9148 return 0;
9150 const Decl *D = getCursorDecl(C);
9152 if (auto *attr = D->getExternalSourceSymbolAttr()) {
9153 if (language)
9154 *language = cxstring::createDup(attr->getLanguage());
9155 if (definedIn)
9156 *definedIn = cxstring::createDup(attr->getDefinedIn());
9157 if (isGenerated)
9158 *isGenerated = attr->getGeneratedDeclaration();
9159 return 1;
9161 return 0;
9164 enum CX_BinaryOperatorKind clang_Cursor_getBinaryOpcode(CXCursor C) {
9165 if (C.kind != CXCursor_BinaryOperator &&
9166 C.kind != CXCursor_CompoundAssignOperator) {
9167 return CX_BO_Invalid;
9170 const Expr *D = getCursorExpr(C);
9171 if (const auto *BinOp = dyn_cast<BinaryOperator>(D)) {
9172 switch (BinOp->getOpcode()) {
9173 #define BINARY_OPERATION(Name, Spelling) \
9174 case BO_##Name: \
9175 return CX_BO_##Name;
9176 #include "clang/AST/OperationKinds.def"
9180 return CX_BO_Invalid;
9183 CXString clang_Cursor_getBinaryOpcodeStr(enum CX_BinaryOperatorKind Op) {
9184 if (Op > CX_BO_LAST)
9185 return cxstring::createEmpty();
9187 return cxstring::createDup(
9188 // BinaryOperator::getOpcodeStr has no case for CX_BO_Invalid,
9189 // so subtract 1
9190 BinaryOperator::getOpcodeStr(static_cast<BinaryOperatorKind>(Op - 1)));
9193 CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
9194 if (!clang_isDeclaration(C.kind))
9195 return clang_getNullRange();
9197 const Decl *D = getCursorDecl(C);
9198 ASTContext &Context = getCursorContext(C);
9199 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
9200 if (!RC)
9201 return clang_getNullRange();
9203 return cxloc::translateSourceRange(Context, RC->getSourceRange());
9206 CXString clang_Cursor_getRawCommentText(CXCursor C) {
9207 if (!clang_isDeclaration(C.kind))
9208 return cxstring::createNull();
9210 const Decl *D = getCursorDecl(C);
9211 ASTContext &Context = getCursorContext(C);
9212 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
9213 StringRef RawText =
9214 RC ? RC->getRawText(Context.getSourceManager()) : StringRef();
9216 // Don't duplicate the string because RawText points directly into source
9217 // code.
9218 return cxstring::createRef(RawText);
9221 CXString clang_Cursor_getBriefCommentText(CXCursor C) {
9222 if (!clang_isDeclaration(C.kind))
9223 return cxstring::createNull();
9225 const Decl *D = getCursorDecl(C);
9226 const ASTContext &Context = getCursorContext(C);
9227 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
9229 if (RC) {
9230 StringRef BriefText = RC->getBriefText(Context);
9232 // Don't duplicate the string because RawComment ensures that this memory
9233 // will not go away.
9234 return cxstring::createRef(BriefText);
9237 return cxstring::createNull();
9240 CXModule clang_Cursor_getModule(CXCursor C) {
9241 if (C.kind == CXCursor_ModuleImportDecl) {
9242 if (const ImportDecl *ImportD =
9243 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
9244 return ImportD->getImportedModule();
9247 return nullptr;
9250 CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
9251 if (isNotUsableTU(TU)) {
9252 LOG_BAD_TU(TU);
9253 return nullptr;
9255 if (!File)
9256 return nullptr;
9257 FileEntryRef FE = *cxfile::getFileEntryRef(File);
9259 ASTUnit &Unit = *cxtu::getASTUnit(TU);
9260 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
9261 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
9263 return Header.getModule();
9266 CXFile clang_Module_getASTFile(CXModule CXMod) {
9267 if (!CXMod)
9268 return nullptr;
9269 Module *Mod = static_cast<Module *>(CXMod);
9270 return cxfile::makeCXFile(Mod->getASTFile());
9273 CXModule clang_Module_getParent(CXModule CXMod) {
9274 if (!CXMod)
9275 return nullptr;
9276 Module *Mod = static_cast<Module *>(CXMod);
9277 return Mod->Parent;
9280 CXString clang_Module_getName(CXModule CXMod) {
9281 if (!CXMod)
9282 return cxstring::createEmpty();
9283 Module *Mod = static_cast<Module *>(CXMod);
9284 return cxstring::createDup(Mod->Name);
9287 CXString clang_Module_getFullName(CXModule CXMod) {
9288 if (!CXMod)
9289 return cxstring::createEmpty();
9290 Module *Mod = static_cast<Module *>(CXMod);
9291 return cxstring::createDup(Mod->getFullModuleName());
9294 int clang_Module_isSystem(CXModule CXMod) {
9295 if (!CXMod)
9296 return 0;
9297 Module *Mod = static_cast<Module *>(CXMod);
9298 return Mod->IsSystem;
9301 unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
9302 CXModule CXMod) {
9303 if (isNotUsableTU(TU)) {
9304 LOG_BAD_TU(TU);
9305 return 0;
9307 if (!CXMod)
9308 return 0;
9309 Module *Mod = static_cast<Module *>(CXMod);
9310 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
9311 ArrayRef<FileEntryRef> TopHeaders = Mod->getTopHeaders(FileMgr);
9312 return TopHeaders.size();
9315 CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU, CXModule CXMod,
9316 unsigned Index) {
9317 if (isNotUsableTU(TU)) {
9318 LOG_BAD_TU(TU);
9319 return nullptr;
9321 if (!CXMod)
9322 return nullptr;
9323 Module *Mod = static_cast<Module *>(CXMod);
9324 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
9326 ArrayRef<FileEntryRef> TopHeaders = Mod->getTopHeaders(FileMgr);
9327 if (Index < TopHeaders.size())
9328 return cxfile::makeCXFile(TopHeaders[Index]);
9330 return nullptr;
9333 //===----------------------------------------------------------------------===//
9334 // C++ AST instrospection.
9335 //===----------------------------------------------------------------------===//
9337 unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
9338 if (!clang_isDeclaration(C.kind))
9339 return 0;
9341 const Decl *D = cxcursor::getCursorDecl(C);
9342 const CXXConstructorDecl *Constructor =
9343 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
9344 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
9347 unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
9348 if (!clang_isDeclaration(C.kind))
9349 return 0;
9351 const Decl *D = cxcursor::getCursorDecl(C);
9352 const CXXConstructorDecl *Constructor =
9353 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
9354 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
9357 unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
9358 if (!clang_isDeclaration(C.kind))
9359 return 0;
9361 const Decl *D = cxcursor::getCursorDecl(C);
9362 const CXXConstructorDecl *Constructor =
9363 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
9364 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
9367 unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
9368 if (!clang_isDeclaration(C.kind))
9369 return 0;
9371 const Decl *D = cxcursor::getCursorDecl(C);
9372 const CXXConstructorDecl *Constructor =
9373 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
9374 // Passing 'false' excludes constructors marked 'explicit'.
9375 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
9378 unsigned clang_CXXField_isMutable(CXCursor C) {
9379 if (!clang_isDeclaration(C.kind))
9380 return 0;
9382 if (const auto D = cxcursor::getCursorDecl(C))
9383 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
9384 return FD->isMutable() ? 1 : 0;
9385 return 0;
9388 unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
9389 if (!clang_isDeclaration(C.kind))
9390 return 0;
9392 const Decl *D = cxcursor::getCursorDecl(C);
9393 const CXXMethodDecl *Method =
9394 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
9395 return (Method && Method->isPureVirtual()) ? 1 : 0;
9398 unsigned clang_CXXMethod_isConst(CXCursor C) {
9399 if (!clang_isDeclaration(C.kind))
9400 return 0;
9402 const Decl *D = cxcursor::getCursorDecl(C);
9403 const CXXMethodDecl *Method =
9404 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
9405 return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0;
9408 unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
9409 if (!clang_isDeclaration(C.kind))
9410 return 0;
9412 const Decl *D = cxcursor::getCursorDecl(C);
9413 const CXXMethodDecl *Method =
9414 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
9415 return (Method && Method->isDefaulted()) ? 1 : 0;
9418 unsigned clang_CXXMethod_isDeleted(CXCursor C) {
9419 if (!clang_isDeclaration(C.kind))
9420 return 0;
9422 const Decl *D = cxcursor::getCursorDecl(C);
9423 const CXXMethodDecl *Method =
9424 D ? dyn_cast_if_present<CXXMethodDecl>(D->getAsFunction()) : nullptr;
9425 return (Method && Method->isDeleted()) ? 1 : 0;
9428 unsigned clang_CXXMethod_isStatic(CXCursor C) {
9429 if (!clang_isDeclaration(C.kind))
9430 return 0;
9432 const Decl *D = cxcursor::getCursorDecl(C);
9433 const CXXMethodDecl *Method =
9434 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
9435 return (Method && Method->isStatic()) ? 1 : 0;
9438 unsigned clang_CXXMethod_isVirtual(CXCursor C) {
9439 if (!clang_isDeclaration(C.kind))
9440 return 0;
9442 const Decl *D = cxcursor::getCursorDecl(C);
9443 const CXXMethodDecl *Method =
9444 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
9445 return (Method && Method->isVirtual()) ? 1 : 0;
9448 unsigned clang_CXXMethod_isCopyAssignmentOperator(CXCursor C) {
9449 if (!clang_isDeclaration(C.kind))
9450 return 0;
9452 const Decl *D = cxcursor::getCursorDecl(C);
9453 const CXXMethodDecl *Method =
9454 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
9456 return (Method && Method->isCopyAssignmentOperator()) ? 1 : 0;
9459 unsigned clang_CXXMethod_isMoveAssignmentOperator(CXCursor C) {
9460 if (!clang_isDeclaration(C.kind))
9461 return 0;
9463 const Decl *D = cxcursor::getCursorDecl(C);
9464 const CXXMethodDecl *Method =
9465 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
9467 return (Method && Method->isMoveAssignmentOperator()) ? 1 : 0;
9470 unsigned clang_CXXMethod_isExplicit(CXCursor C) {
9471 if (!clang_isDeclaration(C.kind))
9472 return 0;
9474 const Decl *D = cxcursor::getCursorDecl(C);
9475 const FunctionDecl *FD = D->getAsFunction();
9477 if (!FD)
9478 return 0;
9480 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD))
9481 return Ctor->isExplicit();
9483 if (const auto *Conv = dyn_cast<CXXConversionDecl>(FD))
9484 return Conv->isExplicit();
9486 return 0;
9489 unsigned clang_CXXRecord_isAbstract(CXCursor C) {
9490 if (!clang_isDeclaration(C.kind))
9491 return 0;
9493 const auto *D = cxcursor::getCursorDecl(C);
9494 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
9495 if (RD)
9496 RD = RD->getDefinition();
9497 return (RD && RD->isAbstract()) ? 1 : 0;
9500 unsigned clang_EnumDecl_isScoped(CXCursor C) {
9501 if (!clang_isDeclaration(C.kind))
9502 return 0;
9504 const Decl *D = cxcursor::getCursorDecl(C);
9505 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
9506 return (Enum && Enum->isScoped()) ? 1 : 0;
9509 //===----------------------------------------------------------------------===//
9510 // Attribute introspection.
9511 //===----------------------------------------------------------------------===//
9513 CXType clang_getIBOutletCollectionType(CXCursor C) {
9514 if (C.kind != CXCursor_IBOutletCollectionAttr)
9515 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
9517 const IBOutletCollectionAttr *A =
9518 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
9520 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
9523 //===----------------------------------------------------------------------===//
9524 // Inspecting memory usage.
9525 //===----------------------------------------------------------------------===//
9527 typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
9529 static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
9530 enum CXTUResourceUsageKind k,
9531 unsigned long amount) {
9532 CXTUResourceUsageEntry entry = {k, amount};
9533 entries.push_back(entry);
9536 const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
9537 const char *str = "";
9538 switch (kind) {
9539 case CXTUResourceUsage_AST:
9540 str = "ASTContext: expressions, declarations, and types";
9541 break;
9542 case CXTUResourceUsage_Identifiers:
9543 str = "ASTContext: identifiers";
9544 break;
9545 case CXTUResourceUsage_Selectors:
9546 str = "ASTContext: selectors";
9547 break;
9548 case CXTUResourceUsage_GlobalCompletionResults:
9549 str = "Code completion: cached global results";
9550 break;
9551 case CXTUResourceUsage_SourceManagerContentCache:
9552 str = "SourceManager: content cache allocator";
9553 break;
9554 case CXTUResourceUsage_AST_SideTables:
9555 str = "ASTContext: side tables";
9556 break;
9557 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
9558 str = "SourceManager: malloc'ed memory buffers";
9559 break;
9560 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
9561 str = "SourceManager: mmap'ed memory buffers";
9562 break;
9563 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
9564 str = "ExternalASTSource: malloc'ed memory buffers";
9565 break;
9566 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
9567 str = "ExternalASTSource: mmap'ed memory buffers";
9568 break;
9569 case CXTUResourceUsage_Preprocessor:
9570 str = "Preprocessor: malloc'ed memory";
9571 break;
9572 case CXTUResourceUsage_PreprocessingRecord:
9573 str = "Preprocessor: PreprocessingRecord";
9574 break;
9575 case CXTUResourceUsage_SourceManager_DataStructures:
9576 str = "SourceManager: data structures and tables";
9577 break;
9578 case CXTUResourceUsage_Preprocessor_HeaderSearch:
9579 str = "Preprocessor: header search tables";
9580 break;
9582 return str;
9585 CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
9586 if (isNotUsableTU(TU)) {
9587 LOG_BAD_TU(TU);
9588 CXTUResourceUsage usage = {(void *)nullptr, 0, nullptr};
9589 return usage;
9592 ASTUnit *astUnit = cxtu::getASTUnit(TU);
9593 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
9594 ASTContext &astContext = astUnit->getASTContext();
9596 // How much memory is used by AST nodes and types?
9597 createCXTUResourceUsageEntry(
9598 *entries, CXTUResourceUsage_AST,
9599 (unsigned long)astContext.getASTAllocatedMemory());
9601 // How much memory is used by identifiers?
9602 createCXTUResourceUsageEntry(
9603 *entries, CXTUResourceUsage_Identifiers,
9604 (unsigned long)astContext.Idents.getAllocator().getTotalMemory());
9606 // How much memory is used for selectors?
9607 createCXTUResourceUsageEntry(
9608 *entries, CXTUResourceUsage_Selectors,
9609 (unsigned long)astContext.Selectors.getTotalMemory());
9611 // How much memory is used by ASTContext's side tables?
9612 createCXTUResourceUsageEntry(
9613 *entries, CXTUResourceUsage_AST_SideTables,
9614 (unsigned long)astContext.getSideTableAllocatedMemory());
9616 // How much memory is used for caching global code completion results?
9617 unsigned long completionBytes = 0;
9618 if (GlobalCodeCompletionAllocator *completionAllocator =
9619 astUnit->getCachedCompletionAllocator().get()) {
9620 completionBytes = completionAllocator->getTotalMemory();
9622 createCXTUResourceUsageEntry(
9623 *entries, CXTUResourceUsage_GlobalCompletionResults, completionBytes);
9625 // How much memory is being used by SourceManager's content cache?
9626 createCXTUResourceUsageEntry(
9627 *entries, CXTUResourceUsage_SourceManagerContentCache,
9628 (unsigned long)astContext.getSourceManager().getContentCacheSize());
9630 // How much memory is being used by the MemoryBuffer's in SourceManager?
9631 const SourceManager::MemoryBufferSizes &srcBufs =
9632 astUnit->getSourceManager().getMemoryBufferSizes();
9634 createCXTUResourceUsageEntry(*entries,
9635 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
9636 (unsigned long)srcBufs.malloc_bytes);
9637 createCXTUResourceUsageEntry(*entries,
9638 CXTUResourceUsage_SourceManager_Membuffer_MMap,
9639 (unsigned long)srcBufs.mmap_bytes);
9640 createCXTUResourceUsageEntry(
9641 *entries, CXTUResourceUsage_SourceManager_DataStructures,
9642 (unsigned long)astContext.getSourceManager().getDataStructureSizes());
9644 // How much memory is being used by the ExternalASTSource?
9645 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
9646 const ExternalASTSource::MemoryBufferSizes &sizes =
9647 esrc->getMemoryBufferSizes();
9649 createCXTUResourceUsageEntry(
9650 *entries, CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
9651 (unsigned long)sizes.malloc_bytes);
9652 createCXTUResourceUsageEntry(
9653 *entries, CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
9654 (unsigned long)sizes.mmap_bytes);
9657 // How much memory is being used by the Preprocessor?
9658 Preprocessor &pp = astUnit->getPreprocessor();
9659 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Preprocessor,
9660 pp.getTotalMemory());
9662 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
9663 createCXTUResourceUsageEntry(*entries,
9664 CXTUResourceUsage_PreprocessingRecord,
9665 pRec->getTotalMemory());
9668 createCXTUResourceUsageEntry(*entries,
9669 CXTUResourceUsage_Preprocessor_HeaderSearch,
9670 pp.getHeaderSearchInfo().getTotalMemory());
9672 CXTUResourceUsage usage = {(void *)entries.get(), (unsigned)entries->size(),
9673 !entries->empty() ? &(*entries)[0] : nullptr};
9674 (void)entries.release();
9675 return usage;
9678 void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
9679 if (usage.data)
9680 delete (MemUsageEntries *)usage.data;
9683 CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
9684 CXSourceRangeList *skipped = new CXSourceRangeList;
9685 skipped->count = 0;
9686 skipped->ranges = nullptr;
9688 if (isNotUsableTU(TU)) {
9689 LOG_BAD_TU(TU);
9690 return skipped;
9693 if (!file)
9694 return skipped;
9696 ASTUnit *astUnit = cxtu::getASTUnit(TU);
9697 PreprocessingRecord *ppRec =
9698 astUnit->getPreprocessor().getPreprocessingRecord();
9699 if (!ppRec)
9700 return skipped;
9702 ASTContext &Ctx = astUnit->getASTContext();
9703 SourceManager &sm = Ctx.getSourceManager();
9704 FileEntryRef fileEntry = *cxfile::getFileEntryRef(file);
9705 FileID wantedFileID = sm.translateFile(fileEntry);
9706 bool isMainFile = wantedFileID == sm.getMainFileID();
9708 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
9709 std::vector<SourceRange> wantedRanges;
9710 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(),
9711 ei = SkippedRanges.end();
9712 i != ei; ++i) {
9713 if (sm.getFileID(i->getBegin()) == wantedFileID ||
9714 sm.getFileID(i->getEnd()) == wantedFileID)
9715 wantedRanges.push_back(*i);
9716 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) ||
9717 astUnit->isInPreambleFileID(i->getEnd())))
9718 wantedRanges.push_back(*i);
9721 skipped->count = wantedRanges.size();
9722 skipped->ranges = new CXSourceRange[skipped->count];
9723 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
9724 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
9726 return skipped;
9729 CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
9730 CXSourceRangeList *skipped = new CXSourceRangeList;
9731 skipped->count = 0;
9732 skipped->ranges = nullptr;
9734 if (isNotUsableTU(TU)) {
9735 LOG_BAD_TU(TU);
9736 return skipped;
9739 ASTUnit *astUnit = cxtu::getASTUnit(TU);
9740 PreprocessingRecord *ppRec =
9741 astUnit->getPreprocessor().getPreprocessingRecord();
9742 if (!ppRec)
9743 return skipped;
9745 ASTContext &Ctx = astUnit->getASTContext();
9747 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
9749 skipped->count = SkippedRanges.size();
9750 skipped->ranges = new CXSourceRange[skipped->count];
9751 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
9752 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
9754 return skipped;
9757 void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
9758 if (ranges) {
9759 delete[] ranges->ranges;
9760 delete ranges;
9764 void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
9765 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
9766 for (unsigned I = 0; I != Usage.numEntries; ++I)
9767 fprintf(stderr, " %s: %lu\n",
9768 clang_getTUResourceUsageName(Usage.entries[I].kind),
9769 Usage.entries[I].amount);
9771 clang_disposeCXTUResourceUsage(Usage);
9774 CXCursor clang_Cursor_getVarDeclInitializer(CXCursor cursor) {
9775 const Decl *const D = getCursorDecl(cursor);
9776 if (!D)
9777 return clang_getNullCursor();
9778 const auto *const VD = dyn_cast<VarDecl>(D);
9779 if (!VD)
9780 return clang_getNullCursor();
9781 const Expr *const Init = VD->getInit();
9782 if (!Init)
9783 return clang_getNullCursor();
9785 return cxcursor::MakeCXCursor(Init, VD, cxcursor::getCursorTU(cursor));
9788 int clang_Cursor_hasVarDeclGlobalStorage(CXCursor cursor) {
9789 const Decl *const D = getCursorDecl(cursor);
9790 if (!D)
9791 return -1;
9792 const auto *const VD = dyn_cast<VarDecl>(D);
9793 if (!VD)
9794 return -1;
9796 return VD->hasGlobalStorage();
9799 int clang_Cursor_hasVarDeclExternalStorage(CXCursor cursor) {
9800 const Decl *const D = getCursorDecl(cursor);
9801 if (!D)
9802 return -1;
9803 const auto *const VD = dyn_cast<VarDecl>(D);
9804 if (!VD)
9805 return -1;
9807 return VD->hasExternalStorage();
9810 //===----------------------------------------------------------------------===//
9811 // Misc. utility functions.
9812 //===----------------------------------------------------------------------===//
9814 /// Default to using our desired 8 MB stack size on "safety" threads.
9815 static unsigned SafetyStackThreadSize = DesiredStackSize;
9817 namespace clang {
9819 bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
9820 unsigned Size) {
9821 if (!Size)
9822 Size = GetSafetyThreadStackSize();
9823 if (Size && !getenv("LIBCLANG_NOTHREADS"))
9824 return CRC.RunSafelyOnThread(Fn, Size);
9825 return CRC.RunSafely(Fn);
9828 unsigned GetSafetyThreadStackSize() { return SafetyStackThreadSize; }
9830 void SetSafetyThreadStackSize(unsigned Value) { SafetyStackThreadSize = Value; }
9832 } // namespace clang
9834 void clang::setThreadBackgroundPriority() {
9835 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
9836 return;
9838 #if LLVM_ENABLE_THREADS
9839 // The function name setThreadBackgroundPriority is for historical reasons;
9840 // Low is more appropriate.
9841 llvm::set_thread_priority(llvm::ThreadPriority::Low);
9842 #endif
9845 void cxindex::printDiagsToStderr(ASTUnit *Unit) {
9846 if (!Unit)
9847 return;
9849 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
9850 DEnd = Unit->stored_diag_end();
9851 D != DEnd; ++D) {
9852 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
9853 CXString Msg =
9854 clang_formatDiagnostic(&Diag, clang_defaultDiagnosticDisplayOptions());
9855 fprintf(stderr, "%s\n", clang_getCString(Msg));
9856 clang_disposeString(Msg);
9858 #ifdef _WIN32
9859 // On Windows, force a flush, since there may be multiple copies of
9860 // stderr and stdout in the file system, all with different buffers
9861 // but writing to the same device.
9862 fflush(stderr);
9863 #endif
9866 MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
9867 SourceLocation MacroDefLoc,
9868 CXTranslationUnit TU) {
9869 if (MacroDefLoc.isInvalid() || !TU)
9870 return nullptr;
9871 if (!II.hadMacroDefinition())
9872 return nullptr;
9874 ASTUnit *Unit = cxtu::getASTUnit(TU);
9875 Preprocessor &PP = Unit->getPreprocessor();
9876 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
9877 if (MD) {
9878 for (MacroDirective::DefInfo Def = MD->getDefinition(); Def;
9879 Def = Def.getPreviousDefinition()) {
9880 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
9881 return Def.getMacroInfo();
9885 return nullptr;
9888 const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
9889 CXTranslationUnit TU) {
9890 if (!MacroDef || !TU)
9891 return nullptr;
9892 const IdentifierInfo *II = MacroDef->getName();
9893 if (!II)
9894 return nullptr;
9896 return getMacroInfo(*II, MacroDef->getLocation(), TU);
9899 MacroDefinitionRecord *
9900 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
9901 CXTranslationUnit TU) {
9902 if (!MI || !TU)
9903 return nullptr;
9904 if (Tok.isNot(tok::raw_identifier))
9905 return nullptr;
9907 if (MI->getNumTokens() == 0)
9908 return nullptr;
9909 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
9910 MI->getDefinitionEndLoc());
9911 ASTUnit *Unit = cxtu::getASTUnit(TU);
9913 // Check that the token is inside the definition and not its argument list.
9914 SourceManager &SM = Unit->getSourceManager();
9915 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
9916 return nullptr;
9917 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
9918 return nullptr;
9920 Preprocessor &PP = Unit->getPreprocessor();
9921 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
9922 if (!PPRec)
9923 return nullptr;
9925 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
9926 if (!II.hadMacroDefinition())
9927 return nullptr;
9929 // Check that the identifier is not one of the macro arguments.
9930 if (llvm::is_contained(MI->params(), &II))
9931 return nullptr;
9933 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
9934 if (!InnerMD)
9935 return nullptr;
9937 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
9940 MacroDefinitionRecord *
9941 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
9942 CXTranslationUnit TU) {
9943 if (Loc.isInvalid() || !MI || !TU)
9944 return nullptr;
9946 if (MI->getNumTokens() == 0)
9947 return nullptr;
9948 ASTUnit *Unit = cxtu::getASTUnit(TU);
9949 Preprocessor &PP = Unit->getPreprocessor();
9950 if (!PP.getPreprocessingRecord())
9951 return nullptr;
9952 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
9953 Token Tok;
9954 if (PP.getRawToken(Loc, Tok))
9955 return nullptr;
9957 return checkForMacroInMacroDefinition(MI, Tok, TU);
9960 CXString clang_getClangVersion() {
9961 return cxstring::createDup(getClangFullVersion());
9964 Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
9965 if (TU) {
9966 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
9967 LogOS << '<' << Unit->getMainFileName() << '>';
9968 if (Unit->isMainFileAST())
9969 LogOS << " (" << Unit->getASTFileName() << ')';
9970 return *this;
9972 } else {
9973 LogOS << "<NULL TU>";
9975 return *this;
9978 Logger &cxindex::Logger::operator<<(FileEntryRef FE) {
9979 *this << FE.getName();
9980 return *this;
9983 Logger &cxindex::Logger::operator<<(CXCursor cursor) {
9984 CXString cursorName = clang_getCursorDisplayName(cursor);
9985 *this << cursorName << "@" << clang_getCursorLocation(cursor);
9986 clang_disposeString(cursorName);
9987 return *this;
9990 Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
9991 CXFile File;
9992 unsigned Line, Column;
9993 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
9994 CXString FileName = clang_getFileName(File);
9995 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
9996 clang_disposeString(FileName);
9997 return *this;
10000 Logger &cxindex::Logger::operator<<(CXSourceRange range) {
10001 CXSourceLocation BLoc = clang_getRangeStart(range);
10002 CXSourceLocation ELoc = clang_getRangeEnd(range);
10004 CXFile BFile;
10005 unsigned BLine, BColumn;
10006 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
10008 CXFile EFile;
10009 unsigned ELine, EColumn;
10010 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
10012 CXString BFileName = clang_getFileName(BFile);
10013 if (BFile == EFile) {
10014 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
10015 BLine, BColumn, ELine, EColumn);
10016 } else {
10017 CXString EFileName = clang_getFileName(EFile);
10018 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName), BLine,
10019 BColumn)
10020 << llvm::format("%s:%d:%d]", clang_getCString(EFileName), ELine,
10021 EColumn);
10022 clang_disposeString(EFileName);
10024 clang_disposeString(BFileName);
10025 return *this;
10028 Logger &cxindex::Logger::operator<<(CXString Str) {
10029 *this << clang_getCString(Str);
10030 return *this;
10033 Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
10034 LogOS << Fmt;
10035 return *this;
10038 static llvm::ManagedStatic<std::mutex> LoggingMutex;
10040 cxindex::Logger::~Logger() {
10041 std::lock_guard<std::mutex> L(*LoggingMutex);
10043 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
10045 raw_ostream &OS = llvm::errs();
10046 OS << "[libclang:" << Name << ':';
10048 #ifdef USE_DARWIN_THREADS
10049 // TODO: Portability.
10050 mach_port_t tid = pthread_mach_thread_np(pthread_self());
10051 OS << tid << ':';
10052 #endif
10054 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
10055 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
10056 OS << Msg << '\n';
10058 if (Trace) {
10059 llvm::sys::PrintStackTrace(OS);
10060 OS << "--------------------------------------------------\n";
10064 CXString clang_getBinaryOperatorKindSpelling(enum CXBinaryOperatorKind kind) {
10065 return cxstring::createRef(
10066 BinaryOperator::getOpcodeStr(static_cast<BinaryOperatorKind>(kind - 1)));
10069 enum CXBinaryOperatorKind clang_getCursorBinaryOperatorKind(CXCursor cursor) {
10070 if (clang_isExpression(cursor.kind)) {
10071 const Expr *expr = getCursorExpr(cursor);
10073 if (const auto *op = dyn_cast<BinaryOperator>(expr))
10074 return static_cast<CXBinaryOperatorKind>(op->getOpcode() + 1);
10076 if (const auto *op = dyn_cast<CXXRewrittenBinaryOperator>(expr))
10077 return static_cast<CXBinaryOperatorKind>(op->getOpcode() + 1);
10080 return CXBinaryOperator_Invalid;
10083 CXString clang_getUnaryOperatorKindSpelling(enum CXUnaryOperatorKind kind) {
10084 return cxstring::createRef(
10085 UnaryOperator::getOpcodeStr(static_cast<UnaryOperatorKind>(kind - 1)));
10088 enum CXUnaryOperatorKind clang_getCursorUnaryOperatorKind(CXCursor cursor) {
10089 if (clang_isExpression(cursor.kind)) {
10090 const Expr *expr = getCursorExpr(cursor);
10092 if (const auto *op = dyn_cast<UnaryOperator>(expr))
10093 return static_cast<CXUnaryOperatorKind>(op->getOpcode() + 1);
10096 return CXUnaryOperator_Invalid;