1962 lines · cpp
1//===--- DeclPrinter.cpp - Printing implementation for Decl ASTs ----------===//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-exception6//7//===----------------------------------------------------------------------===//8//9// This file implements the Decl::print method, which pretty prints the10// AST back out to C/Objective-C/C++/Objective-C++ code.11//12//===----------------------------------------------------------------------===//13#include "clang/AST/ASTContext.h"14#include "clang/AST/Attr.h"15#include "clang/AST/Decl.h"16#include "clang/AST/DeclCXX.h"17#include "clang/AST/DeclObjC.h"18#include "clang/AST/DeclTemplate.h"19#include "clang/AST/DeclVisitor.h"20#include "clang/AST/Expr.h"21#include "clang/AST/ExprCXX.h"22#include "clang/AST/PrettyPrinter.h"23#include "clang/Basic/Module.h"24#include "clang/Basic/SourceManager.h"25#include "llvm/Support/raw_ostream.h"26using namespace clang;27 28namespace {29 class DeclPrinter : public DeclVisitor<DeclPrinter> {30 raw_ostream &Out;31 PrintingPolicy Policy;32 const ASTContext &Context;33 unsigned Indentation;34 bool PrintInstantiation;35 36 raw_ostream& Indent() { return Indent(Indentation); }37 raw_ostream& Indent(unsigned Indentation);38 void ProcessDeclGroup(SmallVectorImpl<Decl*>& Decls);39 40 void Print(AccessSpecifier AS);41 void PrintConstructorInitializers(CXXConstructorDecl *CDecl,42 std::string &Proto);43 44 /// Print an Objective-C method type in parentheses.45 ///46 /// \param Quals The Objective-C declaration qualifiers.47 /// \param T The type to print.48 void PrintObjCMethodType(ASTContext &Ctx, Decl::ObjCDeclQualifier Quals,49 QualType T);50 51 void PrintObjCTypeParams(ObjCTypeParamList *Params);52 void PrintOpenACCRoutineOnLambda(Decl *D);53 54 public:55 DeclPrinter(raw_ostream &Out, const PrintingPolicy &Policy,56 const ASTContext &Context, unsigned Indentation = 0,57 bool PrintInstantiation = false)58 : Out(Out), Policy(Policy), Context(Context), Indentation(Indentation),59 PrintInstantiation(PrintInstantiation) {}60 61 void VisitDeclContext(DeclContext *DC, bool Indent = true);62 63 void VisitTranslationUnitDecl(TranslationUnitDecl *D);64 void VisitTypedefDecl(TypedefDecl *D);65 void VisitTypeAliasDecl(TypeAliasDecl *D);66 void VisitEnumDecl(EnumDecl *D);67 void VisitRecordDecl(RecordDecl *D);68 void VisitEnumConstantDecl(EnumConstantDecl *D);69 void VisitEmptyDecl(EmptyDecl *D);70 void VisitFunctionDecl(FunctionDecl *D);71 void VisitFriendDecl(FriendDecl *D);72 void VisitFieldDecl(FieldDecl *D);73 void VisitVarDecl(VarDecl *D);74 void VisitLabelDecl(LabelDecl *D);75 void VisitParmVarDecl(ParmVarDecl *D);76 void VisitFileScopeAsmDecl(FileScopeAsmDecl *D);77 void VisitTopLevelStmtDecl(TopLevelStmtDecl *D);78 void VisitImportDecl(ImportDecl *D);79 void VisitStaticAssertDecl(StaticAssertDecl *D);80 void VisitNamespaceDecl(NamespaceDecl *D);81 void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);82 void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);83 void VisitCXXRecordDecl(CXXRecordDecl *D);84 void VisitLinkageSpecDecl(LinkageSpecDecl *D);85 void VisitTemplateDecl(const TemplateDecl *D);86 void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);87 void VisitClassTemplateDecl(ClassTemplateDecl *D);88 void VisitClassTemplateSpecializationDecl(89 ClassTemplateSpecializationDecl *D);90 void VisitClassTemplatePartialSpecializationDecl(91 ClassTemplatePartialSpecializationDecl *D);92 void VisitObjCMethodDecl(ObjCMethodDecl *D);93 void VisitObjCImplementationDecl(ObjCImplementationDecl *D);94 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);95 void VisitObjCProtocolDecl(ObjCProtocolDecl *D);96 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);97 void VisitObjCCategoryDecl(ObjCCategoryDecl *D);98 void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);99 void VisitObjCPropertyDecl(ObjCPropertyDecl *D);100 void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);101 void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);102 void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);103 void VisitUsingDecl(UsingDecl *D);104 void VisitUsingEnumDecl(UsingEnumDecl *D);105 void VisitUsingShadowDecl(UsingShadowDecl *D);106 void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);107 void VisitOMPAllocateDecl(OMPAllocateDecl *D);108 void VisitOMPRequiresDecl(OMPRequiresDecl *D);109 void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D);110 void VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D);111 void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D);112 void VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *TTP);113 void VisitNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *NTTP);114 void VisitTemplateTemplateParmDecl(const TemplateTemplateParmDecl *);115 void VisitHLSLBufferDecl(HLSLBufferDecl *D);116 117 void VisitOpenACCDeclareDecl(OpenACCDeclareDecl *D);118 void VisitOpenACCRoutineDecl(OpenACCRoutineDecl *D);119 120 void printTemplateParameters(const TemplateParameterList *Params,121 bool OmitTemplateKW = false);122 void printTemplateArguments(ArrayRef<TemplateArgument> Args,123 const TemplateParameterList *Params);124 void printTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,125 const TemplateParameterList *Params);126 enum class AttrPosAsWritten { Default = 0, Left, Right };127 bool128 prettyPrintAttributes(const Decl *D,129 AttrPosAsWritten Pos = AttrPosAsWritten::Default);130 void prettyPrintPragmas(Decl *D);131 void printDeclType(QualType T, StringRef DeclName, bool Pack = false);132 };133}134 135void Decl::print(raw_ostream &Out, unsigned Indentation,136 bool PrintInstantiation) const {137 print(Out, getASTContext().getPrintingPolicy(), Indentation, PrintInstantiation);138}139 140void Decl::print(raw_ostream &Out, const PrintingPolicy &Policy,141 unsigned Indentation, bool PrintInstantiation) const {142 DeclPrinter Printer(Out, Policy, getASTContext(), Indentation,143 PrintInstantiation);144 Printer.Visit(const_cast<Decl*>(this));145}146 147void TemplateParameterList::print(raw_ostream &Out, const ASTContext &Context,148 bool OmitTemplateKW) const {149 print(Out, Context, Context.getPrintingPolicy(), OmitTemplateKW);150}151 152void TemplateParameterList::print(raw_ostream &Out, const ASTContext &Context,153 const PrintingPolicy &Policy,154 bool OmitTemplateKW) const {155 DeclPrinter Printer(Out, Policy, Context);156 Printer.printTemplateParameters(this, OmitTemplateKW);157}158 159static QualType GetBaseType(QualType T) {160 // FIXME: This should be on the Type class!161 QualType BaseType = T;162 while (!BaseType->isSpecifierType()) {163 if (const PointerType *PTy = BaseType->getAs<PointerType>())164 BaseType = PTy->getPointeeType();165 else if (const ObjCObjectPointerType *OPT =166 BaseType->getAs<ObjCObjectPointerType>())167 BaseType = OPT->getPointeeType();168 else if (const BlockPointerType *BPy = BaseType->getAs<BlockPointerType>())169 BaseType = BPy->getPointeeType();170 else if (const ArrayType *ATy = dyn_cast<ArrayType>(BaseType))171 BaseType = ATy->getElementType();172 else if (const FunctionType *FTy = BaseType->getAs<FunctionType>())173 BaseType = FTy->getReturnType();174 else if (const VectorType *VTy = BaseType->getAs<VectorType>())175 BaseType = VTy->getElementType();176 else if (const ReferenceType *RTy = BaseType->getAs<ReferenceType>())177 BaseType = RTy->getPointeeType();178 else if (const AutoType *ATy = BaseType->getAs<AutoType>())179 BaseType = ATy->getDeducedType();180 else if (const ParenType *PTy = BaseType->getAs<ParenType>())181 BaseType = PTy->desugar();182 else183 // This must be a syntax error.184 break;185 }186 return BaseType;187}188 189static QualType getDeclType(Decl* D) {190 if (TypedefNameDecl* TDD = dyn_cast<TypedefNameDecl>(D))191 return TDD->getUnderlyingType();192 if (ValueDecl* VD = dyn_cast<ValueDecl>(D))193 return VD->getType();194 return QualType();195}196 197void Decl::printGroup(Decl** Begin, unsigned NumDecls,198 raw_ostream &Out, const PrintingPolicy &Policy,199 unsigned Indentation) {200 if (NumDecls == 1) {201 (*Begin)->print(Out, Policy, Indentation);202 return;203 }204 205 Decl** End = Begin + NumDecls;206 if (isa<TagDecl>(*Begin))207 ++Begin;208 209 PrintingPolicy SubPolicy(Policy);210 211 bool isFirst = true;212 for ( ; Begin != End; ++Begin) {213 if (isFirst) {214 isFirst = false;215 } else {216 Out << ", ";217 SubPolicy.SuppressSpecifiers = true;218 }219 220 (*Begin)->print(Out, SubPolicy, Indentation);221 }222}223 224LLVM_DUMP_METHOD void DeclContext::dumpDeclContext() const {225 // Get the translation unit226 const DeclContext *DC = this;227 while (!DC->isTranslationUnit())228 DC = DC->getParent();229 230 ASTContext &Ctx = cast<TranslationUnitDecl>(DC)->getASTContext();231 DeclPrinter Printer(llvm::errs(), Ctx.getPrintingPolicy(), Ctx, 0);232 Printer.VisitDeclContext(const_cast<DeclContext *>(this), /*Indent=*/false);233}234 235raw_ostream& DeclPrinter::Indent(unsigned Indentation) {236 for (unsigned i = 0; i != Indentation; ++i)237 Out << " ";238 return Out;239}240 241static DeclPrinter::AttrPosAsWritten getPosAsWritten(const Attr *A,242 const Decl *D) {243 SourceLocation ALoc = A->getLoc();244 SourceLocation DLoc = D->getLocation();245 const ASTContext &C = D->getASTContext();246 if (ALoc.isInvalid() || DLoc.isInvalid())247 return DeclPrinter::AttrPosAsWritten::Left;248 249 if (C.getSourceManager().isBeforeInTranslationUnit(ALoc, DLoc))250 return DeclPrinter::AttrPosAsWritten::Left;251 252 return DeclPrinter::AttrPosAsWritten::Right;253}254 255// returns true if an attribute was printed.256bool DeclPrinter::prettyPrintAttributes(const Decl *D,257 AttrPosAsWritten Pos /*=Default*/) {258 bool hasPrinted = false;259 260 if (D->hasAttrs()) {261 const AttrVec &Attrs = D->getAttrs();262 for (auto *A : Attrs) {263 if (A->isInherited() || A->isImplicit())264 continue;265 // Print out the keyword attributes, they aren't regular attributes.266 if (Policy.PolishForDeclaration && !A->isKeywordAttribute())267 continue;268 switch (A->getKind()) {269#define ATTR(X)270#define PRAGMA_SPELLING_ATTR(X) case attr::X:271#include "clang/Basic/AttrList.inc"272 break;273 default:274 AttrPosAsWritten APos = getPosAsWritten(A, D);275 assert(APos != AttrPosAsWritten::Default &&276 "Default not a valid for an attribute location");277 if (Pos == AttrPosAsWritten::Default || Pos == APos) {278 if (Pos != AttrPosAsWritten::Left)279 Out << ' ';280 A->printPretty(Out, Policy);281 hasPrinted = true;282 if (Pos == AttrPosAsWritten::Left)283 Out << ' ';284 }285 break;286 }287 }288 }289 return hasPrinted;290}291 292void DeclPrinter::PrintOpenACCRoutineOnLambda(Decl *D) {293 CXXRecordDecl *CXXRD = nullptr;294 if (const auto *VD = dyn_cast<VarDecl>(D)) {295 if (const auto *Init = VD->getInit())296 CXXRD = Init->getType().isNull() ? nullptr297 : Init->getType()->getAsCXXRecordDecl();298 } else if (const auto *FD = dyn_cast<FieldDecl>(D)) {299 CXXRD =300 FD->getType().isNull() ? nullptr : FD->getType()->getAsCXXRecordDecl();301 }302 303 if (!CXXRD || !CXXRD->isLambda())304 return;305 306 if (const auto *Call = CXXRD->getLambdaCallOperator()) {307 for (auto *A : Call->specific_attrs<OpenACCRoutineDeclAttr>()) {308 A->printPretty(Out, Policy);309 Indent();310 }311 }312}313 314void DeclPrinter::prettyPrintPragmas(Decl *D) {315 if (Policy.PolishForDeclaration)316 return;317 318 PrintOpenACCRoutineOnLambda(D);319 320 if (D->hasAttrs()) {321 AttrVec &Attrs = D->getAttrs();322 for (auto *A : Attrs) {323 switch (A->getKind()) {324#define ATTR(X)325#define PRAGMA_SPELLING_ATTR(X) case attr::X:326#include "clang/Basic/AttrList.inc"327 A->printPretty(Out, Policy);328 Indent();329 break;330 default:331 break;332 }333 }334 }335}336 337void DeclPrinter::printDeclType(QualType T, StringRef DeclName, bool Pack) {338 // Normally, a PackExpansionType is written as T[3]... (for instance, as a339 // template argument), but if it is the type of a declaration, the ellipsis340 // is placed before the name being declared.341 if (auto *PET = T->getAs<PackExpansionType>()) {342 Pack = true;343 T = PET->getPattern();344 }345 T.print(Out, Policy, (Pack ? "..." : "") + DeclName, Indentation);346}347 348void DeclPrinter::ProcessDeclGroup(SmallVectorImpl<Decl*>& Decls) {349 this->Indent();350 Decl::printGroup(Decls.data(), Decls.size(), Out, Policy, Indentation);351 Out << ";\n";352 Decls.clear();353 354}355 356void DeclPrinter::Print(AccessSpecifier AS) {357 const auto AccessSpelling = getAccessSpelling(AS);358 if (AccessSpelling.empty())359 llvm_unreachable("No access specifier!");360 Out << AccessSpelling;361}362 363void DeclPrinter::PrintConstructorInitializers(CXXConstructorDecl *CDecl,364 std::string &Proto) {365 bool HasInitializerList = false;366 for (const auto *BMInitializer : CDecl->inits()) {367 if (BMInitializer->isInClassMemberInitializer())368 continue;369 if (!BMInitializer->isWritten())370 continue;371 372 if (!HasInitializerList) {373 Proto += " : ";374 Out << Proto;375 Proto.clear();376 HasInitializerList = true;377 } else378 Out << ", ";379 380 if (BMInitializer->isAnyMemberInitializer()) {381 FieldDecl *FD = BMInitializer->getAnyMember();382 Out << *FD;383 } else if (BMInitializer->isDelegatingInitializer()) {384 Out << CDecl->getNameAsString();385 } else {386 Out << QualType(BMInitializer->getBaseClass(), 0).getAsString(Policy);387 }388 389 if (Expr *Init = BMInitializer->getInit()) {390 bool OutParens = !isa<InitListExpr>(Init);391 392 if (OutParens)393 Out << "(";394 395 if (ExprWithCleanups *Tmp = dyn_cast<ExprWithCleanups>(Init))396 Init = Tmp->getSubExpr();397 398 Init = Init->IgnoreParens();399 400 Expr *SimpleInit = nullptr;401 Expr **Args = nullptr;402 unsigned NumArgs = 0;403 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {404 Args = ParenList->getExprs();405 NumArgs = ParenList->getNumExprs();406 } else if (CXXConstructExpr *Construct =407 dyn_cast<CXXConstructExpr>(Init)) {408 Args = Construct->getArgs();409 NumArgs = Construct->getNumArgs();410 } else411 SimpleInit = Init;412 413 if (SimpleInit)414 SimpleInit->printPretty(Out, nullptr, Policy, Indentation, "\n",415 &Context);416 else {417 for (unsigned I = 0; I != NumArgs; ++I) {418 assert(Args[I] != nullptr && "Expected non-null Expr");419 if (isa<CXXDefaultArgExpr>(Args[I]))420 break;421 422 if (I)423 Out << ", ";424 Args[I]->printPretty(Out, nullptr, Policy, Indentation, "\n",425 &Context);426 }427 }428 429 if (OutParens)430 Out << ")";431 } else {432 Out << "()";433 }434 435 if (BMInitializer->isPackExpansion())436 Out << "...";437 }438}439 440//----------------------------------------------------------------------------441// Common C declarations442//----------------------------------------------------------------------------443 444void DeclPrinter::VisitDeclContext(DeclContext *DC, bool Indent) {445 if (Policy.TerseOutput)446 return;447 448 if (Indent)449 Indentation += Policy.Indentation;450 451 SmallVector<Decl*, 2> Decls;452 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();453 D != DEnd; ++D) {454 455 // Don't print ObjCIvarDecls, as they are printed when visiting the456 // containing ObjCInterfaceDecl.457 if (isa<ObjCIvarDecl>(*D))458 continue;459 460 // Skip over implicit declarations in pretty-printing mode.461 if (D->isImplicit())462 continue;463 464 // Don't print implicit specializations, as they are printed when visiting465 // corresponding templates.466 if (auto FD = dyn_cast<FunctionDecl>(*D))467 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&468 !isa<ClassTemplateSpecializationDecl>(DC))469 continue;470 471 // The next bits of code handle stuff like "struct {int x;} a,b"; we're472 // forced to merge the declarations because there's no other way to473 // refer to the struct in question. When that struct is named instead, we474 // also need to merge to avoid splitting off a stand-alone struct475 // declaration that produces the warning ext_no_declarators in some476 // contexts.477 //478 // This limited merging is safe without a bunch of other checks because it479 // only merges declarations directly referring to the tag, not typedefs.480 //481 // Check whether the current declaration should be grouped with a previous482 // non-free-standing tag declaration.483 QualType CurDeclType = getDeclType(*D);484 if (!Decls.empty() && !CurDeclType.isNull()) {485 QualType BaseType = GetBaseType(CurDeclType);486 if (const auto *TT = dyn_cast_or_null<TagType>(BaseType);487 TT && TT->isTagOwned()) {488 if (TT->getDecl() == Decls[0]) {489 Decls.push_back(*D);490 continue;491 }492 }493 }494 495 // If we have a merged group waiting to be handled, handle it now.496 if (!Decls.empty())497 ProcessDeclGroup(Decls);498 499 // If the current declaration is not a free standing declaration, save it500 // so we can merge it with the subsequent declaration(s) using it.501 if (isa<TagDecl>(*D) && !cast<TagDecl>(*D)->isFreeStanding()) {502 Decls.push_back(*D);503 continue;504 }505 506 if (isa<AccessSpecDecl>(*D)) {507 Indentation -= Policy.Indentation;508 this->Indent();509 Print(D->getAccess());510 Out << ":\n";511 Indentation += Policy.Indentation;512 continue;513 }514 515 this->Indent();516 Visit(*D);517 518 // FIXME: Need to be able to tell the DeclPrinter when519 const char *Terminator = nullptr;520 if (isa<OMPThreadPrivateDecl>(*D) || isa<OMPDeclareReductionDecl>(*D) ||521 isa<OMPDeclareMapperDecl>(*D) || isa<OMPRequiresDecl>(*D) ||522 isa<OMPAllocateDecl>(*D))523 Terminator = nullptr;524 else if (isa<OpenACCDeclareDecl, OpenACCRoutineDecl>(*D))525 Terminator = nullptr;526 else if (isa<ObjCMethodDecl>(*D) && cast<ObjCMethodDecl>(*D)->hasBody())527 Terminator = nullptr;528 else if (auto FD = dyn_cast<FunctionDecl>(*D)) {529 if (FD->doesThisDeclarationHaveABody() && !FD->isDefaulted())530 Terminator = nullptr;531 else532 Terminator = ";";533 } else if (auto TD = dyn_cast<FunctionTemplateDecl>(*D)) {534 if (TD->getTemplatedDecl()->doesThisDeclarationHaveABody())535 Terminator = nullptr;536 else537 Terminator = ";";538 } else if (isa<NamespaceDecl, LinkageSpecDecl, ObjCImplementationDecl,539 ObjCInterfaceDecl, ObjCProtocolDecl, ObjCCategoryImplDecl,540 ObjCCategoryDecl, HLSLBufferDecl>(*D))541 Terminator = nullptr;542 else if (isa<EnumConstantDecl>(*D)) {543 DeclContext::decl_iterator Next = D;544 ++Next;545 if (Next != DEnd)546 Terminator = ",";547 } else548 Terminator = ";";549 550 if (Terminator)551 Out << Terminator;552 if (!Policy.TerseOutput &&553 ((isa<FunctionDecl>(*D) &&554 cast<FunctionDecl>(*D)->doesThisDeclarationHaveABody()) ||555 (isa<FunctionTemplateDecl>(*D) &&556 cast<FunctionTemplateDecl>(*D)->getTemplatedDecl()->doesThisDeclarationHaveABody())))557 ; // StmtPrinter already added '\n' after CompoundStmt.558 else559 Out << "\n";560 561 // Declare target attribute is special one, natural spelling for the pragma562 // assumes "ending" construct so print it here.563 if (D->hasAttr<OMPDeclareTargetDeclAttr>())564 Out << "#pragma omp end declare target\n";565 }566 567 if (!Decls.empty())568 ProcessDeclGroup(Decls);569 570 if (Indent)571 Indentation -= Policy.Indentation;572}573 574void DeclPrinter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {575 VisitDeclContext(D, false);576}577 578void DeclPrinter::VisitTypedefDecl(TypedefDecl *D) {579 if (!Policy.SuppressSpecifiers) {580 Out << "typedef ";581 582 if (D->isModulePrivate())583 Out << "__module_private__ ";584 }585 QualType Ty = D->getTypeSourceInfo()->getType();586 Ty.print(Out, Policy, D->getName(), Indentation);587 prettyPrintAttributes(D);588}589 590void DeclPrinter::VisitTypeAliasDecl(TypeAliasDecl *D) {591 Out << "using " << *D;592 prettyPrintAttributes(D);593 Out << " = " << D->getTypeSourceInfo()->getType().getAsString(Policy);594}595 596void DeclPrinter::VisitEnumDecl(EnumDecl *D) {597 if (!Policy.SuppressSpecifiers && D->isModulePrivate())598 Out << "__module_private__ ";599 Out << "enum";600 if (D->isScoped()) {601 if (D->isScopedUsingClassTag())602 Out << " class";603 else604 Out << " struct";605 }606 607 prettyPrintAttributes(D);608 609 if (D->getDeclName())610 Out << ' ' << D->getDeclName();611 612 if (D->isFixed())613 Out << " : " << D->getIntegerType().stream(Policy);614 615 if (D->isCompleteDefinition()) {616 Out << " {\n";617 VisitDeclContext(D);618 Indent() << "}";619 }620}621 622void DeclPrinter::VisitRecordDecl(RecordDecl *D) {623 if (!Policy.SuppressSpecifiers && D->isModulePrivate())624 Out << "__module_private__ ";625 Out << D->getKindName();626 627 prettyPrintAttributes(D);628 629 if (D->getIdentifier())630 Out << ' ' << *D;631 632 if (D->isCompleteDefinition()) {633 Out << " {\n";634 VisitDeclContext(D);635 Indent() << "}";636 }637}638 639void DeclPrinter::VisitEnumConstantDecl(EnumConstantDecl *D) {640 Out << *D;641 prettyPrintAttributes(D);642 if (Expr *Init = D->getInitExpr()) {643 Out << " = ";644 Init->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context);645 }646}647 648static void printExplicitSpecifier(ExplicitSpecifier ES, llvm::raw_ostream &Out,649 PrintingPolicy &Policy, unsigned Indentation,650 const ASTContext &Context) {651 std::string Proto = "explicit";652 llvm::raw_string_ostream EOut(Proto);653 if (ES.getExpr()) {654 EOut << "(";655 ES.getExpr()->printPretty(EOut, nullptr, Policy, Indentation, "\n",656 &Context);657 EOut << ")";658 }659 EOut << " ";660 Out << Proto;661}662 663void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) {664 if (!D->getDescribedFunctionTemplate() &&665 !D->isFunctionTemplateSpecialization()) {666 prettyPrintPragmas(D);667 prettyPrintAttributes(D, AttrPosAsWritten::Left);668 }669 670 if (D->isFunctionTemplateSpecialization())671 Out << "template<> ";672 else if (!D->getDescribedFunctionTemplate()) {673 for (unsigned I = 0, NumTemplateParams = D->getNumTemplateParameterLists();674 I < NumTemplateParams; ++I)675 printTemplateParameters(D->getTemplateParameterList(I));676 }677 678 CXXConstructorDecl *CDecl = dyn_cast<CXXConstructorDecl>(D);679 CXXConversionDecl *ConversionDecl = dyn_cast<CXXConversionDecl>(D);680 CXXDeductionGuideDecl *GuideDecl = dyn_cast<CXXDeductionGuideDecl>(D);681 if (!Policy.SuppressSpecifiers) {682 switch (D->getStorageClass()) {683 case SC_None: break;684 case SC_Extern: Out << "extern "; break;685 case SC_Static: Out << "static "; break;686 case SC_PrivateExtern: Out << "__private_extern__ "; break;687 case SC_Auto: case SC_Register:688 llvm_unreachable("invalid for functions");689 }690 691 if (D->isInlineSpecified()) Out << "inline ";692 if (D->isVirtualAsWritten()) Out << "virtual ";693 if (D->isModulePrivate()) Out << "__module_private__ ";694 if (D->isConstexprSpecified() && !D->isExplicitlyDefaulted())695 Out << "constexpr ";696 if (D->isConsteval()) Out << "consteval ";697 else if (D->isImmediateFunction())698 Out << "immediate ";699 ExplicitSpecifier ExplicitSpec = ExplicitSpecifier::getFromDecl(D);700 if (ExplicitSpec.isSpecified())701 printExplicitSpecifier(ExplicitSpec, Out, Policy, Indentation, Context);702 }703 704 PrintingPolicy SubPolicy(Policy);705 SubPolicy.SuppressSpecifiers = false;706 std::string Proto;707 708 if (Policy.FullyQualifiedName) {709 Proto += D->getQualifiedNameAsString();710 } else {711 llvm::raw_string_ostream OS(Proto);712 if (!Policy.SuppressScope)713 D->getQualifier().print(OS, Policy);714 D->getNameInfo().printName(OS, Policy);715 }716 717 if (GuideDecl)718 Proto = GuideDecl->getDeducedTemplate()->getDeclName().getAsString();719 if (D->isFunctionTemplateSpecialization()) {720 llvm::raw_string_ostream POut(Proto);721 DeclPrinter TArgPrinter(POut, SubPolicy, Context, Indentation);722 const auto *TArgAsWritten = D->getTemplateSpecializationArgsAsWritten();723 if (TArgAsWritten && !Policy.PrintAsCanonical)724 TArgPrinter.printTemplateArguments(TArgAsWritten->arguments(), nullptr);725 else if (const TemplateArgumentList *TArgs =726 D->getTemplateSpecializationArgs())727 TArgPrinter.printTemplateArguments(TArgs->asArray(), nullptr);728 }729 730 QualType Ty = D->getType();731 while (const ParenType *PT = dyn_cast<ParenType>(Ty)) {732 Proto = '(' + Proto + ')';733 Ty = PT->getInnerType();734 }735 736 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {737 const FunctionProtoType *FT = nullptr;738 if (D->hasWrittenPrototype())739 FT = dyn_cast<FunctionProtoType>(AFT);740 741 Proto += "(";742 if (FT) {743 llvm::raw_string_ostream POut(Proto);744 DeclPrinter ParamPrinter(POut, SubPolicy, Context, Indentation);745 for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {746 if (i) POut << ", ";747 ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));748 }749 750 if (FT->isVariadic()) {751 if (D->getNumParams()) POut << ", ";752 POut << "...";753 } else if (!D->getNumParams() && !Context.getLangOpts().CPlusPlus) {754 // The function has a prototype, so it needs to retain the prototype755 // in C.756 POut << "void";757 }758 } else if (D->doesThisDeclarationHaveABody() && !D->hasPrototype()) {759 for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {760 if (i)761 Proto += ", ";762 Proto += D->getParamDecl(i)->getNameAsString();763 }764 }765 766 Proto += ")";767 768 if (FT) {769 if (FT->isConst())770 Proto += " const";771 if (FT->isVolatile())772 Proto += " volatile";773 if (FT->isRestrict())774 Proto += " restrict";775 776 switch (FT->getRefQualifier()) {777 case RQ_None:778 break;779 case RQ_LValue:780 Proto += " &";781 break;782 case RQ_RValue:783 Proto += " &&";784 break;785 }786 }787 788 if (FT && FT->hasDynamicExceptionSpec()) {789 Proto += " throw(";790 if (FT->getExceptionSpecType() == EST_MSAny)791 Proto += "...";792 else793 for (unsigned I = 0, N = FT->getNumExceptions(); I != N; ++I) {794 if (I)795 Proto += ", ";796 797 Proto += FT->getExceptionType(I).getAsString(SubPolicy);798 }799 Proto += ")";800 } else if (FT && isNoexceptExceptionSpec(FT->getExceptionSpecType())) {801 Proto += " noexcept";802 if (isComputedNoexcept(FT->getExceptionSpecType())) {803 Proto += "(";804 llvm::raw_string_ostream EOut(Proto);805 FT->getNoexceptExpr()->printPretty(EOut, nullptr, SubPolicy,806 Indentation, "\n", &Context);807 Proto += ")";808 }809 }810 811 if (CDecl) {812 if (!Policy.TerseOutput)813 PrintConstructorInitializers(CDecl, Proto);814 } else if (!ConversionDecl && !isa<CXXDestructorDecl>(D)) {815 if (FT && FT->hasTrailingReturn()) {816 if (!GuideDecl)817 Out << "auto ";818 Out << Proto << " -> ";819 Proto.clear();820 }821 AFT->getReturnType().print(Out, Policy, Proto);822 Proto.clear();823 }824 Out << Proto;825 826 if (const AssociatedConstraint &TrailingRequiresClause =827 D->getTrailingRequiresClause()) {828 Out << " requires ";829 // FIXME: The printer could support printing expressions and types as if830 // expanded by an index. Pass in the ArgumentPackSubstitutionIndex when831 // that's supported.832 TrailingRequiresClause.ConstraintExpr->printPretty(833 Out, nullptr, SubPolicy, Indentation, "\n", &Context);834 }835 } else {836 Ty.print(Out, Policy, Proto);837 }838 839 prettyPrintAttributes(D, AttrPosAsWritten::Right);840 841 if (D->isPureVirtual())842 Out << " = 0";843 else if (D->isDeletedAsWritten()) {844 Out << " = delete";845 if (const StringLiteral *M = D->getDeletedMessage()) {846 Out << "(";847 M->outputString(Out);848 Out << ")";849 }850 } else if (D->isExplicitlyDefaulted())851 Out << " = default";852 else if (D->doesThisDeclarationHaveABody()) {853 if (!Policy.TerseOutput) {854 if (!D->hasPrototype() && D->getNumParams()) {855 // This is a K&R function definition, so we need to print the856 // parameters.857 Out << '\n';858 DeclPrinter ParamPrinter(Out, SubPolicy, Context, Indentation);859 Indentation += Policy.Indentation;860 for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {861 Indent();862 ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));863 Out << ";\n";864 }865 Indentation -= Policy.Indentation;866 }867 868 if (D->getBody())869 D->getBody()->printPrettyControlled(Out, nullptr, SubPolicy, Indentation, "\n",870 &Context);871 } else {872 if (!Policy.TerseOutput && isa<CXXConstructorDecl>(*D))873 Out << " {}";874 }875 }876}877 878void DeclPrinter::VisitFriendDecl(FriendDecl *D) {879 if (TypeSourceInfo *TSI = D->getFriendType()) {880 unsigned NumTPLists = D->getFriendTypeNumTemplateParameterLists();881 for (unsigned i = 0; i < NumTPLists; ++i)882 printTemplateParameters(D->getFriendTypeTemplateParameterList(i));883 Out << "friend ";884 Out << TSI->getType().getAsString(Policy);885 }886 else if (FunctionDecl *FD =887 dyn_cast<FunctionDecl>(D->getFriendDecl())) {888 Out << "friend ";889 VisitFunctionDecl(FD);890 }891 else if (FunctionTemplateDecl *FTD =892 dyn_cast<FunctionTemplateDecl>(D->getFriendDecl())) {893 Out << "friend ";894 VisitFunctionTemplateDecl(FTD);895 }896 else if (ClassTemplateDecl *CTD =897 dyn_cast<ClassTemplateDecl>(D->getFriendDecl())) {898 Out << "friend ";899 VisitRedeclarableTemplateDecl(CTD);900 }901 902 if (D->isPackExpansion())903 Out << "...";904}905 906void DeclPrinter::VisitFieldDecl(FieldDecl *D) {907 prettyPrintPragmas(D);908 // FIXME: add printing of pragma attributes if required.909 if (!Policy.SuppressSpecifiers && D->isMutable())910 Out << "mutable ";911 if (!Policy.SuppressSpecifiers && D->isModulePrivate())912 Out << "__module_private__ ";913 914 Out << D->getASTContext().getUnqualifiedObjCPointerType(D->getType()).915 stream(Policy, D->getName(), Indentation);916 917 if (D->isBitField()) {918 Out << " : ";919 D->getBitWidth()->printPretty(Out, nullptr, Policy, Indentation, "\n",920 &Context);921 }922 923 Expr *Init = D->getInClassInitializer();924 if (!Policy.SuppressInitializers && Init) {925 if (D->getInClassInitStyle() == ICIS_ListInit)926 Out << " ";927 else928 Out << " = ";929 Init->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context);930 }931 prettyPrintAttributes(D);932}933 934void DeclPrinter::VisitLabelDecl(LabelDecl *D) {935 Out << *D << ":";936}937 938void DeclPrinter::VisitVarDecl(VarDecl *D) {939 prettyPrintPragmas(D);940 941 prettyPrintAttributes(D, AttrPosAsWritten::Left);942 943 if (const auto *Param = dyn_cast<ParmVarDecl>(D);944 Param && Param->isExplicitObjectParameter())945 Out << "this ";946 947 QualType T = D->getTypeSourceInfo()948 ? D->getTypeSourceInfo()->getType()949 : D->getASTContext().getUnqualifiedObjCPointerType(D->getType());950 951 if (!Policy.SuppressSpecifiers) {952 StorageClass SC = D->getStorageClass();953 if (SC != SC_None)954 Out << VarDecl::getStorageClassSpecifierString(SC) << " ";955 956 switch (D->getTSCSpec()) {957 case TSCS_unspecified:958 break;959 case TSCS___thread:960 Out << "__thread ";961 break;962 case TSCS__Thread_local:963 Out << "_Thread_local ";964 break;965 case TSCS_thread_local:966 Out << "thread_local ";967 break;968 }969 970 if (D->isModulePrivate())971 Out << "__module_private__ ";972 973 if (D->isConstexpr()) {974 Out << "constexpr ";975 T.removeLocalConst();976 }977 }978 979 printDeclType(T, (isa<ParmVarDecl>(D) && Policy.CleanUglifiedParameters &&980 D->getIdentifier())981 ? D->getIdentifier()->deuglifiedName()982 : D->getName());983 984 prettyPrintAttributes(D, AttrPosAsWritten::Right);985 986 Expr *Init = D->getInit();987 if (!Policy.SuppressInitializers && Init) {988 bool ImplicitInit = false;989 if (D->isCXXForRangeDecl()) {990 // FIXME: We should print the range expression instead.991 ImplicitInit = true;992 } else if (CXXConstructExpr *Construct =993 dyn_cast<CXXConstructExpr>(Init->IgnoreImplicit())) {994 if (D->getInitStyle() == VarDecl::CallInit &&995 !Construct->isListInitialization()) {996 ImplicitInit = Construct->getNumArgs() == 0 ||997 Construct->getArg(0)->isDefaultArgument();998 }999 }1000 if (!ImplicitInit) {1001 if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))1002 Out << "(";1003 else if (D->getInitStyle() == VarDecl::CInit) {1004 Out << " = ";1005 }1006 PrintingPolicy SubPolicy(Policy);1007 SubPolicy.SuppressSpecifiers = false;1008 Init->printPretty(Out, nullptr, SubPolicy, Indentation, "\n", &Context);1009 if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))1010 Out << ")";1011 }1012 }1013}1014 1015void DeclPrinter::VisitParmVarDecl(ParmVarDecl *D) {1016 VisitVarDecl(D);1017}1018 1019void DeclPrinter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) {1020 Out << "__asm (";1021 D->getAsmStringExpr()->printPretty(Out, nullptr, Policy, Indentation, "\n",1022 &Context);1023 Out << ")";1024}1025 1026void DeclPrinter::VisitTopLevelStmtDecl(TopLevelStmtDecl *D) {1027 assert(D->getStmt());1028 D->getStmt()->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context);1029}1030 1031void DeclPrinter::VisitImportDecl(ImportDecl *D) {1032 Out << "@import " << D->getImportedModule()->getFullModuleName()1033 << ";\n";1034}1035 1036void DeclPrinter::VisitStaticAssertDecl(StaticAssertDecl *D) {1037 Out << "static_assert(";1038 D->getAssertExpr()->printPretty(Out, nullptr, Policy, Indentation, "\n",1039 &Context);1040 if (Expr *E = D->getMessage()) {1041 Out << ", ";1042 E->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context);1043 }1044 Out << ")";1045}1046 1047//----------------------------------------------------------------------------1048// C++ declarations1049//----------------------------------------------------------------------------1050void DeclPrinter::VisitNamespaceDecl(NamespaceDecl *D) {1051 if (D->isInline())1052 Out << "inline ";1053 1054 Out << "namespace ";1055 if (D->getDeclName())1056 Out << D->getDeclName() << ' ';1057 Out << "{\n";1058 1059 VisitDeclContext(D);1060 Indent() << "}";1061}1062 1063void DeclPrinter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {1064 Out << "using namespace ";1065 D->getQualifier().print(Out, Policy);1066 Out << *D->getNominatedNamespaceAsWritten();1067}1068 1069void DeclPrinter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {1070 Out << "namespace " << *D << " = ";1071 D->getQualifier().print(Out, Policy);1072 Out << *D->getAliasedNamespace();1073}1074 1075void DeclPrinter::VisitEmptyDecl(EmptyDecl *D) {1076 prettyPrintAttributes(D);1077}1078 1079void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) {1080 // FIXME: add printing of pragma attributes if required.1081 if (!Policy.SuppressSpecifiers && D->isModulePrivate())1082 Out << "__module_private__ ";1083 1084 Out << D->getKindName() << ' ';1085 1086 // FIXME: Move before printing the decl kind to match the behavior of the1087 // attribute printing for variables and function where they are printed first.1088 if (prettyPrintAttributes(D, AttrPosAsWritten::Left))1089 Out << ' ';1090 1091 if (D->getIdentifier()) {1092 D->getQualifier().print(Out, Policy);1093 Out << *D;1094 1095 if (auto *S = dyn_cast<ClassTemplateSpecializationDecl>(D)) {1096 const TemplateParameterList *TParams =1097 S->getSpecializedTemplate()->getTemplateParameters();1098 const ASTTemplateArgumentListInfo *TArgAsWritten =1099 S->getTemplateArgsAsWritten();1100 if (TArgAsWritten && !Policy.PrintAsCanonical)1101 printTemplateArguments(TArgAsWritten->arguments(), TParams);1102 else1103 printTemplateArguments(S->getTemplateArgs().asArray(), TParams);1104 }1105 }1106 1107 prettyPrintAttributes(D, AttrPosAsWritten::Right);1108 1109 if (D->isCompleteDefinition()) {1110 Out << ' ';1111 // Print the base classes1112 if (D->getNumBases()) {1113 Out << ": ";1114 for (CXXRecordDecl::base_class_iterator Base = D->bases_begin(),1115 BaseEnd = D->bases_end(); Base != BaseEnd; ++Base) {1116 if (Base != D->bases_begin())1117 Out << ", ";1118 1119 if (Base->isVirtual())1120 Out << "virtual ";1121 1122 AccessSpecifier AS = Base->getAccessSpecifierAsWritten();1123 if (AS != AS_none) {1124 Print(AS);1125 Out << " ";1126 }1127 Out << Base->getType().getAsString(Policy);1128 1129 if (Base->isPackExpansion())1130 Out << "...";1131 }1132 Out << ' ';1133 }1134 1135 // Print the class definition1136 // FIXME: Doesn't print access specifiers, e.g., "public:"1137 if (Policy.TerseOutput) {1138 Out << "{}";1139 } else {1140 Out << "{\n";1141 VisitDeclContext(D);1142 Indent() << "}";1143 }1144 }1145}1146 1147void DeclPrinter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {1148 const char *l;1149 if (D->getLanguage() == LinkageSpecLanguageIDs::C)1150 l = "C";1151 else {1152 assert(D->getLanguage() == LinkageSpecLanguageIDs::CXX &&1153 "unknown language in linkage specification");1154 l = "C++";1155 }1156 1157 Out << "extern \"" << l << "\" ";1158 if (D->hasBraces()) {1159 Out << "{\n";1160 VisitDeclContext(D);1161 Indent() << "}";1162 } else1163 Visit(*D->decls_begin());1164}1165 1166void DeclPrinter::printTemplateParameters(const TemplateParameterList *Params,1167 bool OmitTemplateKW) {1168 assert(Params);1169 1170 // Don't print invented template parameter lists.1171 if (!Params->empty() && Params->getParam(0)->isImplicit())1172 return;1173 1174 if (!OmitTemplateKW)1175 Out << "template ";1176 Out << '<';1177 1178 bool NeedComma = false;1179 for (const Decl *Param : *Params) {1180 if (Param->isImplicit())1181 continue;1182 1183 if (NeedComma)1184 Out << ", ";1185 else1186 NeedComma = true;1187 1188 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {1189 VisitTemplateTypeParmDecl(TTP);1190 } else if (auto NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {1191 VisitNonTypeTemplateParmDecl(NTTP);1192 } else if (auto TTPD = dyn_cast<TemplateTemplateParmDecl>(Param)) {1193 VisitTemplateTemplateParmDecl(TTPD);1194 }1195 }1196 1197 Out << '>';1198 1199 if (const Expr *RequiresClause = Params->getRequiresClause()) {1200 Out << " requires ";1201 RequiresClause->printPretty(Out, nullptr, Policy, Indentation, "\n",1202 &Context);1203 }1204 1205 if (!OmitTemplateKW)1206 Out << ' ';1207}1208 1209void DeclPrinter::printTemplateArguments(ArrayRef<TemplateArgument> Args,1210 const TemplateParameterList *Params) {1211 Out << "<";1212 for (size_t I = 0, E = Args.size(); I < E; ++I) {1213 if (I)1214 Out << ", ";1215 if (!Params)1216 Args[I].print(Policy, Out, /*IncludeType*/ true);1217 else1218 Args[I].print(Policy, Out,1219 TemplateParameterList::shouldIncludeTypeForArgument(1220 Policy, Params, I));1221 }1222 Out << ">";1223}1224 1225void DeclPrinter::printTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,1226 const TemplateParameterList *Params) {1227 Out << "<";1228 for (size_t I = 0, E = Args.size(); I < E; ++I) {1229 if (I)1230 Out << ", ";1231 if (!Params)1232 Args[I].getArgument().print(Policy, Out, /*IncludeType*/ true);1233 else1234 Args[I].getArgument().print(1235 Policy, Out,1236 TemplateParameterList::shouldIncludeTypeForArgument(Policy, Params,1237 I));1238 }1239 Out << ">";1240}1241 1242void DeclPrinter::VisitTemplateDecl(const TemplateDecl *D) {1243 printTemplateParameters(D->getTemplateParameters());1244 1245 if (const TemplateTemplateParmDecl *TTP =1246 dyn_cast<TemplateTemplateParmDecl>(D)) {1247 if (TTP->wasDeclaredWithTypename())1248 Out << "typename";1249 else1250 Out << "class";1251 1252 if (TTP->isParameterPack())1253 Out << " ...";1254 else if (TTP->getDeclName())1255 Out << ' ';1256 1257 if (TTP->getDeclName()) {1258 if (Policy.CleanUglifiedParameters && TTP->getIdentifier())1259 Out << TTP->getIdentifier()->deuglifiedName();1260 else1261 Out << TTP->getDeclName();1262 }1263 } else if (auto *TD = D->getTemplatedDecl())1264 Visit(TD);1265 else if (const auto *Concept = dyn_cast<ConceptDecl>(D)) {1266 Out << "concept " << Concept->getName() << " = " ;1267 Concept->getConstraintExpr()->printPretty(Out, nullptr, Policy, Indentation,1268 "\n", &Context);1269 }1270}1271 1272void DeclPrinter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {1273 prettyPrintPragmas(D->getTemplatedDecl());1274 // Print any leading template parameter lists.1275 if (const FunctionDecl *FD = D->getTemplatedDecl()) {1276 for (unsigned I = 0, NumTemplateParams = FD->getNumTemplateParameterLists();1277 I < NumTemplateParams; ++I)1278 printTemplateParameters(FD->getTemplateParameterList(I));1279 }1280 VisitRedeclarableTemplateDecl(D);1281 // Declare target attribute is special one, natural spelling for the pragma1282 // assumes "ending" construct so print it here.1283 if (D->getTemplatedDecl()->hasAttr<OMPDeclareTargetDeclAttr>())1284 Out << "#pragma omp end declare target\n";1285 1286 // Never print "instantiations" for deduction guides (they don't really1287 // have them).1288 if (PrintInstantiation &&1289 !isa<CXXDeductionGuideDecl>(D->getTemplatedDecl())) {1290 FunctionDecl *PrevDecl = D->getTemplatedDecl();1291 const FunctionDecl *Def;1292 if (PrevDecl->isDefined(Def) && Def != PrevDecl)1293 return;1294 for (auto *I : D->specializations())1295 if (I->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) {1296 if (!PrevDecl->isThisDeclarationADefinition())1297 Out << ";\n";1298 Indent();1299 prettyPrintPragmas(I);1300 Visit(I);1301 }1302 }1303}1304 1305void DeclPrinter::VisitClassTemplateDecl(ClassTemplateDecl *D) {1306 VisitRedeclarableTemplateDecl(D);1307 1308 if (PrintInstantiation) {1309 for (auto *I : D->specializations())1310 if (I->getSpecializationKind() == TSK_ImplicitInstantiation) {1311 if (D->isThisDeclarationADefinition())1312 Out << ";";1313 Out << "\n";1314 Indent();1315 Visit(I);1316 }1317 }1318}1319 1320void DeclPrinter::VisitClassTemplateSpecializationDecl(1321 ClassTemplateSpecializationDecl *D) {1322 Out << "template<> ";1323 VisitCXXRecordDecl(D);1324}1325 1326void DeclPrinter::VisitClassTemplatePartialSpecializationDecl(1327 ClassTemplatePartialSpecializationDecl *D) {1328 printTemplateParameters(D->getTemplateParameters());1329 VisitCXXRecordDecl(D);1330}1331 1332//----------------------------------------------------------------------------1333// Objective-C declarations1334//----------------------------------------------------------------------------1335 1336void DeclPrinter::PrintObjCMethodType(ASTContext &Ctx,1337 Decl::ObjCDeclQualifier Quals,1338 QualType T) {1339 Out << '(';1340 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_In)1341 Out << "in ";1342 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Inout)1343 Out << "inout ";1344 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Out)1345 Out << "out ";1346 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Bycopy)1347 Out << "bycopy ";1348 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Byref)1349 Out << "byref ";1350 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Oneway)1351 Out << "oneway ";1352 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_CSNullability) {1353 if (auto nullability = AttributedType::stripOuterNullability(T))1354 Out << getNullabilitySpelling(*nullability, true) << ' ';1355 }1356 1357 Out << Ctx.getUnqualifiedObjCPointerType(T).getAsString(Policy);1358 Out << ')';1359}1360 1361void DeclPrinter::PrintObjCTypeParams(ObjCTypeParamList *Params) {1362 Out << "<";1363 unsigned First = true;1364 for (auto *Param : *Params) {1365 if (First) {1366 First = false;1367 } else {1368 Out << ", ";1369 }1370 1371 switch (Param->getVariance()) {1372 case ObjCTypeParamVariance::Invariant:1373 break;1374 1375 case ObjCTypeParamVariance::Covariant:1376 Out << "__covariant ";1377 break;1378 1379 case ObjCTypeParamVariance::Contravariant:1380 Out << "__contravariant ";1381 break;1382 }1383 1384 Out << Param->getDeclName();1385 1386 if (Param->hasExplicitBound()) {1387 Out << " : " << Param->getUnderlyingType().getAsString(Policy);1388 }1389 }1390 Out << ">";1391}1392 1393void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) {1394 if (OMD->isInstanceMethod())1395 Out << "- ";1396 else1397 Out << "+ ";1398 if (!OMD->getReturnType().isNull()) {1399 PrintObjCMethodType(OMD->getASTContext(), OMD->getObjCDeclQualifier(),1400 OMD->getReturnType());1401 }1402 1403 std::string name = OMD->getSelector().getAsString();1404 std::string::size_type pos, lastPos = 0;1405 for (const auto *PI : OMD->parameters()) {1406 // FIXME: selector is missing here!1407 pos = name.find_first_of(':', lastPos);1408 if (lastPos != 0)1409 Out << " ";1410 Out << name.substr(lastPos, pos - lastPos) << ':';1411 PrintObjCMethodType(OMD->getASTContext(),1412 PI->getObjCDeclQualifier(),1413 PI->getType());1414 Out << *PI;1415 lastPos = pos + 1;1416 }1417 1418 if (OMD->parameters().empty())1419 Out << name;1420 1421 if (OMD->isVariadic())1422 Out << ", ...";1423 1424 prettyPrintAttributes(OMD);1425 1426 if (OMD->getBody() && !Policy.TerseOutput) {1427 Out << ' ';1428 OMD->getBody()->printPretty(Out, nullptr, Policy, Indentation, "\n",1429 &Context);1430 }1431 else if (Policy.PolishForDeclaration)1432 Out << ';';1433}1434 1435void DeclPrinter::VisitObjCImplementationDecl(ObjCImplementationDecl *OID) {1436 std::string I = OID->getNameAsString();1437 ObjCInterfaceDecl *SID = OID->getSuperClass();1438 1439 bool eolnOut = false;1440 if (SID)1441 Out << "@implementation " << I << " : " << *SID;1442 else1443 Out << "@implementation " << I;1444 1445 if (OID->ivar_size() > 0) {1446 Out << "{\n";1447 eolnOut = true;1448 Indentation += Policy.Indentation;1449 for (const auto *I : OID->ivars()) {1450 Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).1451 getAsString(Policy) << ' ' << *I << ";\n";1452 }1453 Indentation -= Policy.Indentation;1454 Out << "}\n";1455 } else if (SID || !OID->decls().empty()) {1456 Out << "\n";1457 eolnOut = true;1458 }1459 VisitDeclContext(OID, false);1460 if (!eolnOut)1461 Out << "\n";1462 Out << "@end";1463}1464 1465void DeclPrinter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *OID) {1466 std::string I = OID->getNameAsString();1467 ObjCInterfaceDecl *SID = OID->getSuperClass();1468 1469 if (!OID->isThisDeclarationADefinition()) {1470 Out << "@class " << I;1471 1472 if (auto TypeParams = OID->getTypeParamListAsWritten()) {1473 PrintObjCTypeParams(TypeParams);1474 }1475 1476 Out << ";";1477 return;1478 }1479 bool eolnOut = false;1480 if (OID->hasAttrs()) {1481 prettyPrintAttributes(OID);1482 Out << "\n";1483 }1484 1485 Out << "@interface " << I;1486 1487 if (auto TypeParams = OID->getTypeParamListAsWritten()) {1488 PrintObjCTypeParams(TypeParams);1489 }1490 1491 if (SID)1492 Out << " : " << QualType(OID->getSuperClassType(), 0).getAsString(Policy);1493 1494 // Protocols?1495 const ObjCList<ObjCProtocolDecl> &Protocols = OID->getReferencedProtocols();1496 if (!Protocols.empty()) {1497 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),1498 E = Protocols.end(); I != E; ++I)1499 Out << (I == Protocols.begin() ? '<' : ',') << **I;1500 Out << "> ";1501 }1502 1503 if (OID->ivar_size() > 0) {1504 Out << "{\n";1505 eolnOut = true;1506 Indentation += Policy.Indentation;1507 for (const auto *I : OID->ivars()) {1508 Indent() << I->getASTContext()1509 .getUnqualifiedObjCPointerType(I->getType())1510 .getAsString(Policy) << ' ' << *I << ";\n";1511 }1512 Indentation -= Policy.Indentation;1513 Out << "}\n";1514 } else if (SID || !OID->decls().empty()) {1515 Out << "\n";1516 eolnOut = true;1517 }1518 1519 VisitDeclContext(OID, false);1520 if (!eolnOut)1521 Out << "\n";1522 Out << "@end";1523 // FIXME: implement the rest...1524}1525 1526void DeclPrinter::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {1527 if (!PID->isThisDeclarationADefinition()) {1528 Out << "@protocol " << *PID << ";\n";1529 return;1530 }1531 // Protocols?1532 const ObjCList<ObjCProtocolDecl> &Protocols = PID->getReferencedProtocols();1533 if (!Protocols.empty()) {1534 Out << "@protocol " << *PID;1535 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),1536 E = Protocols.end(); I != E; ++I)1537 Out << (I == Protocols.begin() ? '<' : ',') << **I;1538 Out << ">\n";1539 } else1540 Out << "@protocol " << *PID << '\n';1541 VisitDeclContext(PID, false);1542 Out << "@end";1543}1544 1545void DeclPrinter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *PID) {1546 Out << "@implementation ";1547 if (const auto *CID = PID->getClassInterface())1548 Out << *CID;1549 else1550 Out << "<<error-type>>";1551 Out << '(' << *PID << ")\n";1552 1553 VisitDeclContext(PID, false);1554 Out << "@end";1555 // FIXME: implement the rest...1556}1557 1558void DeclPrinter::VisitObjCCategoryDecl(ObjCCategoryDecl *PID) {1559 Out << "@interface ";1560 if (const auto *CID = PID->getClassInterface())1561 Out << *CID;1562 else1563 Out << "<<error-type>>";1564 if (auto TypeParams = PID->getTypeParamList()) {1565 PrintObjCTypeParams(TypeParams);1566 }1567 Out << "(" << *PID << ")\n";1568 if (PID->ivar_size() > 0) {1569 Out << "{\n";1570 Indentation += Policy.Indentation;1571 for (const auto *I : PID->ivars())1572 Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).1573 getAsString(Policy) << ' ' << *I << ";\n";1574 Indentation -= Policy.Indentation;1575 Out << "}\n";1576 }1577 1578 VisitDeclContext(PID, false);1579 Out << "@end";1580 1581 // FIXME: implement the rest...1582}1583 1584void DeclPrinter::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *AID) {1585 Out << "@compatibility_alias " << *AID1586 << ' ' << *AID->getClassInterface() << ";\n";1587}1588 1589/// PrintObjCPropertyDecl - print a property declaration.1590///1591/// Print attributes in the following order:1592/// - class1593/// - nonatomic | atomic1594/// - assign | retain | strong | copy | weak | unsafe_unretained1595/// - readwrite | readonly1596/// - getter & setter1597/// - nullability1598void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) {1599 if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Required)1600 Out << "@required\n";1601 else if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Optional)1602 Out << "@optional\n";1603 1604 QualType T = PDecl->getType();1605 1606 Out << "@property";1607 if (PDecl->getPropertyAttributes() != ObjCPropertyAttribute::kind_noattr) {1608 bool first = true;1609 Out << "(";1610 if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_class) {1611 Out << (first ? "" : ", ") << "class";1612 first = false;1613 }1614 1615 if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_direct) {1616 Out << (first ? "" : ", ") << "direct";1617 first = false;1618 }1619 1620 if (PDecl->getPropertyAttributes() &1621 ObjCPropertyAttribute::kind_nonatomic) {1622 Out << (first ? "" : ", ") << "nonatomic";1623 first = false;1624 }1625 if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_atomic) {1626 Out << (first ? "" : ", ") << "atomic";1627 first = false;1628 }1629 1630 if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_assign) {1631 Out << (first ? "" : ", ") << "assign";1632 first = false;1633 }1634 if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain) {1635 Out << (first ? "" : ", ") << "retain";1636 first = false;1637 }1638 1639 if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_strong) {1640 Out << (first ? "" : ", ") << "strong";1641 first = false;1642 }1643 if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy) {1644 Out << (first ? "" : ", ") << "copy";1645 first = false;1646 }1647 if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak) {1648 Out << (first ? "" : ", ") << "weak";1649 first = false;1650 }1651 if (PDecl->getPropertyAttributes() &1652 ObjCPropertyAttribute::kind_unsafe_unretained) {1653 Out << (first ? "" : ", ") << "unsafe_unretained";1654 first = false;1655 }1656 1657 if (PDecl->getPropertyAttributes() &1658 ObjCPropertyAttribute::kind_readwrite) {1659 Out << (first ? "" : ", ") << "readwrite";1660 first = false;1661 }1662 if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_readonly) {1663 Out << (first ? "" : ", ") << "readonly";1664 first = false;1665 }1666 1667 if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {1668 Out << (first ? "" : ", ") << "getter = ";1669 PDecl->getGetterName().print(Out);1670 first = false;1671 }1672 if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {1673 Out << (first ? "" : ", ") << "setter = ";1674 PDecl->getSetterName().print(Out);1675 first = false;1676 }1677 1678 if (PDecl->getPropertyAttributes() &1679 ObjCPropertyAttribute::kind_nullability) {1680 if (auto nullability = AttributedType::stripOuterNullability(T)) {1681 if (*nullability == NullabilityKind::Unspecified &&1682 (PDecl->getPropertyAttributes() &1683 ObjCPropertyAttribute::kind_null_resettable)) {1684 Out << (first ? "" : ", ") << "null_resettable";1685 } else {1686 Out << (first ? "" : ", ")1687 << getNullabilitySpelling(*nullability, true);1688 }1689 first = false;1690 }1691 }1692 1693 (void) first; // Silence dead store warning due to idiomatic code.1694 Out << ")";1695 }1696 std::string TypeStr = PDecl->getASTContext().getUnqualifiedObjCPointerType(T).1697 getAsString(Policy);1698 Out << ' ' << TypeStr;1699 if (!StringRef(TypeStr).ends_with("*"))1700 Out << ' ';1701 Out << *PDecl;1702 if (Policy.PolishForDeclaration)1703 Out << ';';1704}1705 1706void DeclPrinter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PID) {1707 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize)1708 Out << "@synthesize ";1709 else1710 Out << "@dynamic ";1711 Out << *PID->getPropertyDecl();1712 if (PID->getPropertyIvarDecl())1713 Out << '=' << *PID->getPropertyIvarDecl();1714}1715 1716void DeclPrinter::VisitUsingDecl(UsingDecl *D) {1717 if (!D->isAccessDeclaration())1718 Out << "using ";1719 if (D->hasTypename())1720 Out << "typename ";1721 D->getQualifier().print(Out, Policy);1722 1723 // Use the correct record name when the using declaration is used for1724 // inheriting constructors.1725 for (const auto *Shadow : D->shadows()) {1726 if (const auto *ConstructorShadow =1727 dyn_cast<ConstructorUsingShadowDecl>(Shadow)) {1728 assert(Shadow->getDeclContext() == ConstructorShadow->getDeclContext());1729 Out << *ConstructorShadow->getNominatedBaseClass();1730 return;1731 }1732 }1733 Out << *D;1734}1735 1736void DeclPrinter::VisitUsingEnumDecl(UsingEnumDecl *D) {1737 Out << "using enum " << D->getEnumDecl();1738}1739 1740void1741DeclPrinter::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {1742 Out << "using typename ";1743 D->getQualifier().print(Out, Policy);1744 Out << D->getDeclName();1745}1746 1747void DeclPrinter::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {1748 if (!D->isAccessDeclaration())1749 Out << "using ";1750 D->getQualifier().print(Out, Policy);1751 Out << D->getDeclName();1752}1753 1754void DeclPrinter::VisitUsingShadowDecl(UsingShadowDecl *D) {1755 // ignore1756}1757 1758void DeclPrinter::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {1759 Out << "#pragma omp threadprivate";1760 if (!D->varlist_empty()) {1761 for (OMPThreadPrivateDecl::varlist_iterator I = D->varlist_begin(),1762 E = D->varlist_end();1763 I != E; ++I) {1764 Out << (I == D->varlist_begin() ? '(' : ',');1765 NamedDecl *ND = cast<DeclRefExpr>(*I)->getDecl();1766 ND->printQualifiedName(Out);1767 }1768 Out << ")";1769 }1770}1771 1772void DeclPrinter::VisitHLSLBufferDecl(HLSLBufferDecl *D) {1773 if (D->isCBuffer())1774 Out << "cbuffer ";1775 else1776 Out << "tbuffer ";1777 1778 Out << *D;1779 1780 prettyPrintAttributes(D);1781 1782 Out << " {\n";1783 VisitDeclContext(D);1784 Indent() << "}";1785}1786 1787void DeclPrinter::VisitOMPAllocateDecl(OMPAllocateDecl *D) {1788 Out << "#pragma omp allocate";1789 if (!D->varlist_empty()) {1790 for (OMPAllocateDecl::varlist_iterator I = D->varlist_begin(),1791 E = D->varlist_end();1792 I != E; ++I) {1793 Out << (I == D->varlist_begin() ? '(' : ',');1794 NamedDecl *ND = cast<DeclRefExpr>(*I)->getDecl();1795 ND->printQualifiedName(Out);1796 }1797 Out << ")";1798 }1799 if (!D->clauselist_empty()) {1800 OMPClausePrinter Printer(Out, Policy, Context.getLangOpts().OpenMP);1801 for (OMPClause *C : D->clauselists()) {1802 Out << " ";1803 Printer.Visit(C);1804 }1805 }1806}1807 1808void DeclPrinter::VisitOMPRequiresDecl(OMPRequiresDecl *D) {1809 Out << "#pragma omp requires ";1810 if (!D->clauselist_empty()) {1811 OMPClausePrinter Printer(Out, Policy, Context.getLangOpts().OpenMP);1812 for (auto I = D->clauselist_begin(), E = D->clauselist_end(); I != E; ++I)1813 Printer.Visit(*I);1814 }1815}1816 1817void DeclPrinter::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {1818 if (!D->isInvalidDecl()) {1819 Out << "#pragma omp declare reduction (";1820 if (D->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) {1821 const char *OpName =1822 getOperatorSpelling(D->getDeclName().getCXXOverloadedOperator());1823 assert(OpName && "not an overloaded operator");1824 Out << OpName;1825 } else {1826 assert(D->getDeclName().isIdentifier());1827 D->printName(Out, Policy);1828 }1829 Out << " : ";1830 D->getType().print(Out, Policy);1831 Out << " : ";1832 D->getCombiner()->printPretty(Out, nullptr, Policy, 0, "\n", &Context);1833 Out << ")";1834 if (auto *Init = D->getInitializer()) {1835 Out << " initializer(";1836 switch (D->getInitializerKind()) {1837 case OMPDeclareReductionInitKind::Direct:1838 Out << "omp_priv(";1839 break;1840 case OMPDeclareReductionInitKind::Copy:1841 Out << "omp_priv = ";1842 break;1843 case OMPDeclareReductionInitKind::Call:1844 break;1845 }1846 Init->printPretty(Out, nullptr, Policy, 0, "\n", &Context);1847 if (D->getInitializerKind() == OMPDeclareReductionInitKind::Direct)1848 Out << ")";1849 Out << ")";1850 }1851 }1852}1853 1854void DeclPrinter::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {1855 if (!D->isInvalidDecl()) {1856 Out << "#pragma omp declare mapper (";1857 D->printName(Out, Policy);1858 Out << " : ";1859 D->getType().print(Out, Policy);1860 Out << " ";1861 Out << D->getVarName();1862 Out << ")";1863 if (!D->clauselist_empty()) {1864 OMPClausePrinter Printer(Out, Policy, Context.getLangOpts().OpenMP);1865 for (auto *C : D->clauselists()) {1866 Out << " ";1867 Printer.Visit(C);1868 }1869 }1870 }1871}1872 1873void DeclPrinter::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {1874 D->getInit()->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context);1875}1876 1877void DeclPrinter::VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *TTP) {1878 if (const TypeConstraint *TC = TTP->getTypeConstraint())1879 TC->print(Out, Policy);1880 else if (TTP->wasDeclaredWithTypename())1881 Out << "typename";1882 else1883 Out << "class";1884 1885 if (TTP->isParameterPack())1886 Out << " ...";1887 else if (TTP->getDeclName())1888 Out << ' ';1889 1890 if (TTP->getDeclName()) {1891 if (Policy.CleanUglifiedParameters && TTP->getIdentifier())1892 Out << TTP->getIdentifier()->deuglifiedName();1893 else1894 Out << TTP->getDeclName();1895 }1896 1897 if (TTP->hasDefaultArgument() && !TTP->defaultArgumentWasInherited()) {1898 Out << " = ";1899 TTP->getDefaultArgument().getArgument().print(Policy, Out,1900 /*IncludeType=*/false);1901 }1902}1903 1904void DeclPrinter::VisitNonTypeTemplateParmDecl(1905 const NonTypeTemplateParmDecl *NTTP) {1906 StringRef Name;1907 if (IdentifierInfo *II = NTTP->getIdentifier())1908 Name =1909 Policy.CleanUglifiedParameters ? II->deuglifiedName() : II->getName();1910 printDeclType(NTTP->getType(), Name, NTTP->isParameterPack());1911 1912 if (NTTP->hasDefaultArgument() && !NTTP->defaultArgumentWasInherited()) {1913 Out << " = ";1914 NTTP->getDefaultArgument().getArgument().print(Policy, Out,1915 /*IncludeType=*/false);1916 }1917}1918 1919void DeclPrinter::VisitTemplateTemplateParmDecl(1920 const TemplateTemplateParmDecl *TTPD) {1921 VisitTemplateDecl(TTPD);1922 if (TTPD->hasDefaultArgument() && !TTPD->defaultArgumentWasInherited()) {1923 Out << " = ";1924 TTPD->getDefaultArgument().getArgument().print(Policy, Out,1925 /*IncludeType=*/false);1926 }1927}1928 1929void DeclPrinter::VisitOpenACCDeclareDecl(OpenACCDeclareDecl *D) {1930 if (!D->isInvalidDecl()) {1931 Out << "#pragma acc declare";1932 if (!D->clauses().empty()) {1933 Out << ' ';1934 OpenACCClausePrinter Printer(Out, Policy);1935 Printer.VisitClauseList(D->clauses());1936 }1937 }1938}1939void DeclPrinter::VisitOpenACCRoutineDecl(OpenACCRoutineDecl *D) {1940 if (!D->isInvalidDecl()) {1941 Out << "#pragma acc routine";1942 1943 Out << "(";1944 1945 // The referenced function was named here, but this makes us tolerant of1946 // errors.1947 if (D->getFunctionReference())1948 D->getFunctionReference()->printPretty(Out, nullptr, Policy, Indentation,1949 "\n", &Context);1950 else1951 Out << "<error>";1952 1953 Out << ")";1954 1955 if (!D->clauses().empty()) {1956 Out << ' ';1957 OpenACCClausePrinter Printer(Out, Policy);1958 Printer.VisitClauseList(D->clauses());1959 }1960 }1961}1962