1 //===--- DeclPrinter.cpp - Printing implementation for Decl ASTs ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Decl::print method, which pretty prints the
11 // AST back out to C/Objective-C/C++/Objective-C++ code.
13 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/Attr.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.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 "llvm/Support/raw_ostream.h"
25 using namespace clang;
28 class DeclPrinter : public DeclVisitor<DeclPrinter> {
30 PrintingPolicy Policy;
32 bool PrintInstantiation;
34 raw_ostream& Indent() { return Indent(Indentation); }
35 raw_ostream& Indent(unsigned Indentation);
36 void ProcessDeclGroup(SmallVectorImpl<Decl*>& Decls);
38 void Print(AccessSpecifier AS);
40 /// Print an Objective-C method type in parentheses.
42 /// \param Quals The Objective-C declaration qualifiers.
43 /// \param T The type to print.
44 void PrintObjCMethodType(ASTContext &Ctx, Decl::ObjCDeclQualifier Quals,
47 void PrintObjCTypeParams(ObjCTypeParamList *Params);
50 DeclPrinter(raw_ostream &Out, const PrintingPolicy &Policy,
51 unsigned Indentation = 0, bool PrintInstantiation = false)
52 : Out(Out), Policy(Policy), Indentation(Indentation),
53 PrintInstantiation(PrintInstantiation) { }
55 void VisitDeclContext(DeclContext *DC, bool Indent = true);
57 void VisitTranslationUnitDecl(TranslationUnitDecl *D);
58 void VisitTypedefDecl(TypedefDecl *D);
59 void VisitTypeAliasDecl(TypeAliasDecl *D);
60 void VisitEnumDecl(EnumDecl *D);
61 void VisitRecordDecl(RecordDecl *D);
62 void VisitEnumConstantDecl(EnumConstantDecl *D);
63 void VisitEmptyDecl(EmptyDecl *D);
64 void VisitFunctionDecl(FunctionDecl *D);
65 void VisitFriendDecl(FriendDecl *D);
66 void VisitFieldDecl(FieldDecl *D);
67 void VisitVarDecl(VarDecl *D);
68 void VisitLabelDecl(LabelDecl *D);
69 void VisitParmVarDecl(ParmVarDecl *D);
70 void VisitFileScopeAsmDecl(FileScopeAsmDecl *D);
71 void VisitImportDecl(ImportDecl *D);
72 void VisitStaticAssertDecl(StaticAssertDecl *D);
73 void VisitNamespaceDecl(NamespaceDecl *D);
74 void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
75 void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
76 void VisitCXXRecordDecl(CXXRecordDecl *D);
77 void VisitLinkageSpecDecl(LinkageSpecDecl *D);
78 void VisitTemplateDecl(const TemplateDecl *D);
79 void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
80 void VisitClassTemplateDecl(ClassTemplateDecl *D);
81 void VisitObjCMethodDecl(ObjCMethodDecl *D);
82 void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
83 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
84 void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
85 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
86 void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
87 void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
88 void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
89 void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
90 void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
91 void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
92 void VisitUsingDecl(UsingDecl *D);
93 void VisitUsingShadowDecl(UsingShadowDecl *D);
94 void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
95 void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D);
96 void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D);
98 void PrintTemplateParameters(const TemplateParameterList *Params,
99 const TemplateArgumentList *Args = nullptr);
100 void prettyPrintAttributes(Decl *D);
101 void prettyPrintPragmas(Decl *D);
102 void printDeclType(QualType T, StringRef DeclName, bool Pack = false);
106 void Decl::print(raw_ostream &Out, unsigned Indentation,
107 bool PrintInstantiation) const {
108 print(Out, getASTContext().getPrintingPolicy(), Indentation, PrintInstantiation);
111 void Decl::print(raw_ostream &Out, const PrintingPolicy &Policy,
112 unsigned Indentation, bool PrintInstantiation) const {
113 DeclPrinter Printer(Out, Policy, Indentation, PrintInstantiation);
114 Printer.Visit(const_cast<Decl*>(this));
117 static QualType GetBaseType(QualType T) {
118 // FIXME: This should be on the Type class!
119 QualType BaseType = T;
120 while (!BaseType->isSpecifierType()) {
121 if (isa<TypedefType>(BaseType))
123 else if (const PointerType* PTy = BaseType->getAs<PointerType>())
124 BaseType = PTy->getPointeeType();
125 else if (const BlockPointerType *BPy = BaseType->getAs<BlockPointerType>())
126 BaseType = BPy->getPointeeType();
127 else if (const ArrayType* ATy = dyn_cast<ArrayType>(BaseType))
128 BaseType = ATy->getElementType();
129 else if (const FunctionType* FTy = BaseType->getAs<FunctionType>())
130 BaseType = FTy->getReturnType();
131 else if (const VectorType *VTy = BaseType->getAs<VectorType>())
132 BaseType = VTy->getElementType();
133 else if (const ReferenceType *RTy = BaseType->getAs<ReferenceType>())
134 BaseType = RTy->getPointeeType();
135 else if (const AutoType *ATy = BaseType->getAs<AutoType>())
136 BaseType = ATy->getDeducedType();
138 llvm_unreachable("Unknown declarator!");
143 static QualType getDeclType(Decl* D) {
144 if (TypedefNameDecl* TDD = dyn_cast<TypedefNameDecl>(D))
145 return TDD->getUnderlyingType();
146 if (ValueDecl* VD = dyn_cast<ValueDecl>(D))
147 return VD->getType();
151 void Decl::printGroup(Decl** Begin, unsigned NumDecls,
152 raw_ostream &Out, const PrintingPolicy &Policy,
153 unsigned Indentation) {
155 (*Begin)->print(Out, Policy, Indentation);
159 Decl** End = Begin + NumDecls;
160 TagDecl* TD = dyn_cast<TagDecl>(*Begin);
164 PrintingPolicy SubPolicy(Policy);
167 for ( ; Begin != End; ++Begin) {
170 SubPolicy.IncludeTagDefinition = true;
171 SubPolicy.SuppressSpecifiers = false;
174 if (!isFirst) Out << ", ";
175 SubPolicy.IncludeTagDefinition = false;
176 SubPolicy.SuppressSpecifiers = true;
179 (*Begin)->print(Out, SubPolicy, Indentation);
183 LLVM_DUMP_METHOD void DeclContext::dumpDeclContext() const {
184 // Get the translation unit
185 const DeclContext *DC = this;
186 while (!DC->isTranslationUnit())
187 DC = DC->getParent();
189 ASTContext &Ctx = cast<TranslationUnitDecl>(DC)->getASTContext();
190 DeclPrinter Printer(llvm::errs(), Ctx.getPrintingPolicy(), 0);
191 Printer.VisitDeclContext(const_cast<DeclContext *>(this), /*Indent=*/false);
194 raw_ostream& DeclPrinter::Indent(unsigned Indentation) {
195 for (unsigned i = 0; i != Indentation; ++i)
200 void DeclPrinter::prettyPrintAttributes(Decl *D) {
201 if (Policy.PolishForDeclaration)
205 AttrVec &Attrs = D->getAttrs();
206 for (auto *A : Attrs) {
207 switch (A->getKind()) {
209 #define PRAGMA_SPELLING_ATTR(X) case attr::X:
210 #include "clang/Basic/AttrList.inc"
213 A->printPretty(Out, Policy);
220 void DeclPrinter::prettyPrintPragmas(Decl *D) {
221 if (Policy.PolishForDeclaration)
225 AttrVec &Attrs = D->getAttrs();
226 for (auto *A : Attrs) {
227 switch (A->getKind()) {
229 #define PRAGMA_SPELLING_ATTR(X) case attr::X:
230 #include "clang/Basic/AttrList.inc"
231 A->printPretty(Out, Policy);
241 void DeclPrinter::printDeclType(QualType T, StringRef DeclName, bool Pack) {
242 // Normally, a PackExpansionType is written as T[3]... (for instance, as a
243 // template argument), but if it is the type of a declaration, the ellipsis
244 // is placed before the name being declared.
245 if (auto *PET = T->getAs<PackExpansionType>()) {
247 T = PET->getPattern();
249 T.print(Out, Policy, (Pack ? "..." : "") + DeclName, Indentation);
252 void DeclPrinter::ProcessDeclGroup(SmallVectorImpl<Decl*>& Decls) {
254 Decl::printGroup(Decls.data(), Decls.size(), Out, Policy, Indentation);
260 void DeclPrinter::Print(AccessSpecifier AS) {
262 case AS_none: llvm_unreachable("No access specifier!");
263 case AS_public: Out << "public"; break;
264 case AS_protected: Out << "protected"; break;
265 case AS_private: Out << "private"; break;
269 //----------------------------------------------------------------------------
270 // Common C declarations
271 //----------------------------------------------------------------------------
273 void DeclPrinter::VisitDeclContext(DeclContext *DC, bool Indent) {
274 if (Policy.TerseOutput)
278 Indentation += Policy.Indentation;
280 SmallVector<Decl*, 2> Decls;
281 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
284 // Don't print ObjCIvarDecls, as they are printed when visiting the
285 // containing ObjCInterfaceDecl.
286 if (isa<ObjCIvarDecl>(*D))
289 // Skip over implicit declarations in pretty-printing mode.
293 // The next bits of code handles stuff like "struct {int x;} a,b"; we're
294 // forced to merge the declarations because there's no other way to
295 // refer to the struct in question. This limited merging is safe without
296 // a bunch of other checks because it only merges declarations directly
297 // referring to the tag, not typedefs.
299 // Check whether the current declaration should be grouped with a previous
301 QualType CurDeclType = getDeclType(*D);
302 if (!Decls.empty() && !CurDeclType.isNull()) {
303 QualType BaseType = GetBaseType(CurDeclType);
304 if (!BaseType.isNull() && isa<ElaboratedType>(BaseType))
305 BaseType = cast<ElaboratedType>(BaseType)->getNamedType();
306 if (!BaseType.isNull() && isa<TagType>(BaseType) &&
307 cast<TagType>(BaseType)->getDecl() == Decls[0]) {
313 // If we have a merged group waiting to be handled, handle it now.
315 ProcessDeclGroup(Decls);
317 // If the current declaration is an unnamed tag type, save it
318 // so we can merge it with the subsequent declaration(s) using it.
319 if (isa<TagDecl>(*D) && !cast<TagDecl>(*D)->getIdentifier()) {
324 if (isa<AccessSpecDecl>(*D)) {
325 Indentation -= Policy.Indentation;
327 Print(D->getAccess());
329 Indentation += Policy.Indentation;
336 // FIXME: Need to be able to tell the DeclPrinter when
337 const char *Terminator = nullptr;
338 if (isa<OMPThreadPrivateDecl>(*D) || isa<OMPDeclareReductionDecl>(*D))
339 Terminator = nullptr;
340 else if (isa<FunctionDecl>(*D) &&
341 cast<FunctionDecl>(*D)->isThisDeclarationADefinition())
342 Terminator = nullptr;
343 else if (isa<ObjCMethodDecl>(*D) && cast<ObjCMethodDecl>(*D)->getBody())
344 Terminator = nullptr;
345 else if (isa<NamespaceDecl>(*D) || isa<LinkageSpecDecl>(*D) ||
346 isa<ObjCImplementationDecl>(*D) ||
347 isa<ObjCInterfaceDecl>(*D) ||
348 isa<ObjCProtocolDecl>(*D) ||
349 isa<ObjCCategoryImplDecl>(*D) ||
350 isa<ObjCCategoryDecl>(*D))
351 Terminator = nullptr;
352 else if (isa<EnumConstantDecl>(*D)) {
353 DeclContext::decl_iterator Next = D;
364 // Declare target attribute is special one, natural spelling for the pragma
365 // assumes "ending" construct so print it here.
366 if (D->hasAttr<OMPDeclareTargetDeclAttr>())
367 Out << "#pragma omp end declare target\n";
371 ProcessDeclGroup(Decls);
374 Indentation -= Policy.Indentation;
377 void DeclPrinter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
378 VisitDeclContext(D, false);
381 void DeclPrinter::VisitTypedefDecl(TypedefDecl *D) {
382 if (!Policy.SuppressSpecifiers) {
385 if (D->isModulePrivate())
386 Out << "__module_private__ ";
388 QualType Ty = D->getTypeSourceInfo()->getType();
389 Ty.print(Out, Policy, D->getName(), Indentation);
390 prettyPrintAttributes(D);
393 void DeclPrinter::VisitTypeAliasDecl(TypeAliasDecl *D) {
394 Out << "using " << *D;
395 prettyPrintAttributes(D);
396 Out << " = " << D->getTypeSourceInfo()->getType().getAsString(Policy);
399 void DeclPrinter::VisitEnumDecl(EnumDecl *D) {
400 if (!Policy.SuppressSpecifiers && D->isModulePrivate())
401 Out << "__module_private__ ";
404 if (D->isScopedUsingClassTag())
412 Out << " : " << D->getIntegerType().stream(Policy);
414 if (D->isCompleteDefinition()) {
419 prettyPrintAttributes(D);
422 void DeclPrinter::VisitRecordDecl(RecordDecl *D) {
423 if (!Policy.SuppressSpecifiers && D->isModulePrivate())
424 Out << "__module_private__ ";
425 Out << D->getKindName();
427 prettyPrintAttributes(D);
429 if (D->getIdentifier())
432 if (D->isCompleteDefinition()) {
439 void DeclPrinter::VisitEnumConstantDecl(EnumConstantDecl *D) {
441 if (Expr *Init = D->getInitExpr()) {
443 Init->printPretty(Out, nullptr, Policy, Indentation);
447 void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) {
448 if (!D->getDescribedFunctionTemplate() &&
449 !D->isFunctionTemplateSpecialization())
450 prettyPrintPragmas(D);
452 CXXConstructorDecl *CDecl = dyn_cast<CXXConstructorDecl>(D);
453 CXXConversionDecl *ConversionDecl = dyn_cast<CXXConversionDecl>(D);
454 if (!Policy.SuppressSpecifiers) {
455 switch (D->getStorageClass()) {
457 case SC_Extern: Out << "extern "; break;
458 case SC_Static: Out << "static "; break;
459 case SC_PrivateExtern: Out << "__private_extern__ "; break;
460 case SC_Auto: case SC_Register:
461 llvm_unreachable("invalid for functions");
464 if (D->isInlineSpecified()) Out << "inline ";
465 if (D->isVirtualAsWritten()) Out << "virtual ";
466 if (D->isModulePrivate()) Out << "__module_private__ ";
467 if (D->isConstexpr() && !D->isExplicitlyDefaulted()) Out << "constexpr ";
468 if ((CDecl && CDecl->isExplicitSpecified()) ||
469 (ConversionDecl && ConversionDecl->isExplicit()))
473 PrintingPolicy SubPolicy(Policy);
474 SubPolicy.SuppressSpecifiers = false;
475 std::string Proto = D->getNameInfo().getAsString();
477 QualType Ty = D->getType();
478 while (const ParenType *PT = dyn_cast<ParenType>(Ty)) {
479 Proto = '(' + Proto + ')';
480 Ty = PT->getInnerType();
483 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
484 const FunctionProtoType *FT = nullptr;
485 if (D->hasWrittenPrototype())
486 FT = dyn_cast<FunctionProtoType>(AFT);
490 llvm::raw_string_ostream POut(Proto);
491 DeclPrinter ParamPrinter(POut, SubPolicy, Indentation);
492 for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
494 ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
497 if (FT->isVariadic()) {
498 if (D->getNumParams()) POut << ", ";
501 } else if (D->doesThisDeclarationHaveABody() && !D->hasPrototype()) {
502 for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
505 Proto += D->getParamDecl(i)->getNameAsString();
514 if (FT->isVolatile())
515 Proto += " volatile";
516 if (FT->isRestrict())
517 Proto += " restrict";
519 switch (FT->getRefQualifier()) {
531 if (FT && FT->hasDynamicExceptionSpec()) {
533 if (FT->getExceptionSpecType() == EST_MSAny)
536 for (unsigned I = 0, N = FT->getNumExceptions(); I != N; ++I) {
540 Proto += FT->getExceptionType(I).getAsString(SubPolicy);
543 } else if (FT && isNoexceptExceptionSpec(FT->getExceptionSpecType())) {
544 Proto += " noexcept";
545 if (FT->getExceptionSpecType() == EST_ComputedNoexcept) {
547 llvm::raw_string_ostream EOut(Proto);
548 FT->getNoexceptExpr()->printPretty(EOut, nullptr, SubPolicy,
557 bool HasInitializerList = false;
558 for (const auto *BMInitializer : CDecl->inits()) {
559 if (BMInitializer->isInClassMemberInitializer())
562 if (!HasInitializerList) {
566 HasInitializerList = true;
570 if (BMInitializer->isAnyMemberInitializer()) {
571 FieldDecl *FD = BMInitializer->getAnyMember();
574 Out << QualType(BMInitializer->getBaseClass(), 0).getAsString(Policy);
578 if (!BMInitializer->getInit()) {
581 Expr *Init = BMInitializer->getInit();
582 if (ExprWithCleanups *Tmp = dyn_cast<ExprWithCleanups>(Init))
583 Init = Tmp->getSubExpr();
585 Init = Init->IgnoreParens();
587 Expr *SimpleInit = nullptr;
588 Expr **Args = nullptr;
589 unsigned NumArgs = 0;
590 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
591 Args = ParenList->getExprs();
592 NumArgs = ParenList->getNumExprs();
593 } else if (CXXConstructExpr *Construct
594 = dyn_cast<CXXConstructExpr>(Init)) {
595 Args = Construct->getArgs();
596 NumArgs = Construct->getNumArgs();
601 SimpleInit->printPretty(Out, nullptr, Policy, Indentation);
603 for (unsigned I = 0; I != NumArgs; ++I) {
604 assert(Args[I] != nullptr && "Expected non-null Expr");
605 if (isa<CXXDefaultArgExpr>(Args[I]))
610 Args[I]->printPretty(Out, nullptr, Policy, Indentation);
615 if (BMInitializer->isPackExpansion())
618 } else if (!ConversionDecl && !isa<CXXDestructorDecl>(D)) {
619 if (FT && FT->hasTrailingReturn()) {
620 Out << "auto " << Proto << " -> ";
623 AFT->getReturnType().print(Out, Policy, Proto);
628 Ty.print(Out, Policy, Proto);
631 prettyPrintAttributes(D);
635 else if (D->isDeletedAsWritten())
637 else if (D->isExplicitlyDefaulted())
639 else if (D->doesThisDeclarationHaveABody() && !Policy.TerseOutput) {
640 if (!D->hasPrototype() && D->getNumParams()) {
641 // This is a K&R function definition, so we need to print the
644 DeclPrinter ParamPrinter(Out, SubPolicy, Indentation);
645 Indentation += Policy.Indentation;
646 for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
648 ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
651 Indentation -= Policy.Indentation;
656 D->getBody()->printPretty(Out, nullptr, SubPolicy, Indentation);
661 void DeclPrinter::VisitFriendDecl(FriendDecl *D) {
662 if (TypeSourceInfo *TSI = D->getFriendType()) {
663 unsigned NumTPLists = D->getFriendTypeNumTemplateParameterLists();
664 for (unsigned i = 0; i < NumTPLists; ++i)
665 PrintTemplateParameters(D->getFriendTypeTemplateParameterList(i));
667 Out << " " << TSI->getType().getAsString(Policy);
669 else if (FunctionDecl *FD =
670 dyn_cast<FunctionDecl>(D->getFriendDecl())) {
672 VisitFunctionDecl(FD);
674 else if (FunctionTemplateDecl *FTD =
675 dyn_cast<FunctionTemplateDecl>(D->getFriendDecl())) {
677 VisitFunctionTemplateDecl(FTD);
679 else if (ClassTemplateDecl *CTD =
680 dyn_cast<ClassTemplateDecl>(D->getFriendDecl())) {
682 VisitRedeclarableTemplateDecl(CTD);
686 void DeclPrinter::VisitFieldDecl(FieldDecl *D) {
687 // FIXME: add printing of pragma attributes if required.
688 if (!Policy.SuppressSpecifiers && D->isMutable())
690 if (!Policy.SuppressSpecifiers && D->isModulePrivate())
691 Out << "__module_private__ ";
693 Out << D->getASTContext().getUnqualifiedObjCPointerType(D->getType()).
694 stream(Policy, D->getName(), Indentation);
696 if (D->isBitField()) {
698 D->getBitWidth()->printPretty(Out, nullptr, Policy, Indentation);
701 Expr *Init = D->getInClassInitializer();
702 if (!Policy.SuppressInitializers && Init) {
703 if (D->getInClassInitStyle() == ICIS_ListInit)
707 Init->printPretty(Out, nullptr, Policy, Indentation);
709 prettyPrintAttributes(D);
712 void DeclPrinter::VisitLabelDecl(LabelDecl *D) {
716 void DeclPrinter::VisitVarDecl(VarDecl *D) {
717 prettyPrintPragmas(D);
719 QualType T = D->getTypeSourceInfo()
720 ? D->getTypeSourceInfo()->getType()
721 : D->getASTContext().getUnqualifiedObjCPointerType(D->getType());
723 if (!Policy.SuppressSpecifiers) {
724 StorageClass SC = D->getStorageClass();
726 Out << VarDecl::getStorageClassSpecifierString(SC) << " ";
728 switch (D->getTSCSpec()) {
729 case TSCS_unspecified:
734 case TSCS__Thread_local:
735 Out << "_Thread_local ";
737 case TSCS_thread_local:
738 Out << "thread_local ";
742 if (D->isModulePrivate())
743 Out << "__module_private__ ";
745 if (D->isConstexpr()) {
747 T.removeLocalConst();
751 printDeclType(T, D->getName());
752 Expr *Init = D->getInit();
753 if (!Policy.SuppressInitializers && Init) {
754 bool ImplicitInit = false;
755 if (CXXConstructExpr *Construct =
756 dyn_cast<CXXConstructExpr>(Init->IgnoreImplicit())) {
757 if (D->getInitStyle() == VarDecl::CallInit &&
758 !Construct->isListInitialization()) {
759 ImplicitInit = Construct->getNumArgs() == 0 ||
760 Construct->getArg(0)->isDefaultArgument();
764 if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
766 else if (D->getInitStyle() == VarDecl::CInit) {
769 PrintingPolicy SubPolicy(Policy);
770 SubPolicy.SuppressSpecifiers = false;
771 SubPolicy.IncludeTagDefinition = false;
772 Init->printPretty(Out, nullptr, SubPolicy, Indentation);
773 if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
777 prettyPrintAttributes(D);
780 void DeclPrinter::VisitParmVarDecl(ParmVarDecl *D) {
784 void DeclPrinter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) {
786 D->getAsmString()->printPretty(Out, nullptr, Policy, Indentation);
790 void DeclPrinter::VisitImportDecl(ImportDecl *D) {
791 Out << "@import " << D->getImportedModule()->getFullModuleName()
795 void DeclPrinter::VisitStaticAssertDecl(StaticAssertDecl *D) {
796 Out << "static_assert(";
797 D->getAssertExpr()->printPretty(Out, nullptr, Policy, Indentation);
798 if (StringLiteral *SL = D->getMessage()) {
800 SL->printPretty(Out, nullptr, Policy, Indentation);
805 //----------------------------------------------------------------------------
807 //----------------------------------------------------------------------------
808 void DeclPrinter::VisitNamespaceDecl(NamespaceDecl *D) {
811 Out << "namespace " << *D << " {\n";
816 void DeclPrinter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
817 Out << "using namespace ";
818 if (D->getQualifier())
819 D->getQualifier()->print(Out, Policy);
820 Out << *D->getNominatedNamespaceAsWritten();
823 void DeclPrinter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
824 Out << "namespace " << *D << " = ";
825 if (D->getQualifier())
826 D->getQualifier()->print(Out, Policy);
827 Out << *D->getAliasedNamespace();
830 void DeclPrinter::VisitEmptyDecl(EmptyDecl *D) {
831 prettyPrintAttributes(D);
834 void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) {
835 // FIXME: add printing of pragma attributes if required.
836 if (!Policy.SuppressSpecifiers && D->isModulePrivate())
837 Out << "__module_private__ ";
838 Out << D->getKindName();
840 prettyPrintAttributes(D);
842 if (D->getIdentifier())
845 if (D->isCompleteDefinition()) {
846 // Print the base classes
847 if (D->getNumBases()) {
849 for (CXXRecordDecl::base_class_iterator Base = D->bases_begin(),
850 BaseEnd = D->bases_end(); Base != BaseEnd; ++Base) {
851 if (Base != D->bases_begin())
854 if (Base->isVirtual())
857 AccessSpecifier AS = Base->getAccessSpecifierAsWritten();
862 Out << Base->getType().getAsString(Policy);
864 if (Base->isPackExpansion())
869 // Print the class definition
870 // FIXME: Doesn't print access specifiers, e.g., "public:"
877 void DeclPrinter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
879 if (D->getLanguage() == LinkageSpecDecl::lang_c)
882 assert(D->getLanguage() == LinkageSpecDecl::lang_cxx &&
883 "unknown language in linkage specification");
887 Out << "extern \"" << l << "\" ";
888 if (D->hasBraces()) {
893 Visit(*D->decls_begin());
896 void DeclPrinter::PrintTemplateParameters(const TemplateParameterList *Params,
897 const TemplateArgumentList *Args) {
899 assert(!Args || Params->size() == Args->size());
903 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
907 const Decl *Param = Params->getParam(i);
908 if (const TemplateTypeParmDecl *TTP =
909 dyn_cast<TemplateTypeParmDecl>(Param)) {
911 if (TTP->wasDeclaredWithTypename())
916 if (TTP->isParameterPack())
923 Args->get(i).print(Policy, Out);
924 } else if (TTP->hasDefaultArgument()) {
926 Out << TTP->getDefaultArgument().getAsString(Policy);
928 } else if (const NonTypeTemplateParmDecl *NTTP =
929 dyn_cast<NonTypeTemplateParmDecl>(Param)) {
931 if (IdentifierInfo *II = NTTP->getIdentifier())
932 Name = II->getName();
933 printDeclType(NTTP->getType(), Name, NTTP->isParameterPack());
937 Args->get(i).print(Policy, Out);
938 } else if (NTTP->hasDefaultArgument()) {
940 NTTP->getDefaultArgument()->printPretty(Out, nullptr, Policy,
943 } else if (const TemplateTemplateParmDecl *TTPD =
944 dyn_cast<TemplateTemplateParmDecl>(Param)) {
945 VisitTemplateDecl(TTPD);
946 // FIXME: print the default argument, if present.
953 void DeclPrinter::VisitTemplateDecl(const TemplateDecl *D) {
954 PrintTemplateParameters(D->getTemplateParameters());
956 if (const TemplateTemplateParmDecl *TTP =
957 dyn_cast<TemplateTemplateParmDecl>(D)) {
959 if (TTP->isParameterPack())
963 Visit(D->getTemplatedDecl());
967 void DeclPrinter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
968 if (PrintInstantiation) {
969 TemplateParameterList *Params = D->getTemplateParameters();
970 for (auto *I : D->specializations()) {
971 prettyPrintPragmas(I);
972 PrintTemplateParameters(Params, I->getTemplateSpecializationArgs());
977 prettyPrintPragmas(D->getTemplatedDecl());
978 return VisitRedeclarableTemplateDecl(D);
981 void DeclPrinter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
982 if (PrintInstantiation) {
983 TemplateParameterList *Params = D->getTemplateParameters();
984 for (auto *I : D->specializations()) {
985 PrintTemplateParameters(Params, &I->getTemplateArgs());
991 return VisitRedeclarableTemplateDecl(D);
994 //----------------------------------------------------------------------------
995 // Objective-C declarations
996 //----------------------------------------------------------------------------
998 void DeclPrinter::PrintObjCMethodType(ASTContext &Ctx,
999 Decl::ObjCDeclQualifier Quals,
1002 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_In)
1004 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Inout)
1006 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Out)
1008 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Bycopy)
1010 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Byref)
1012 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Oneway)
1014 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_CSNullability) {
1015 if (auto nullability = AttributedType::stripOuterNullability(T))
1016 Out << getNullabilitySpelling(*nullability, true) << ' ';
1019 Out << Ctx.getUnqualifiedObjCPointerType(T).getAsString(Policy);
1023 void DeclPrinter::PrintObjCTypeParams(ObjCTypeParamList *Params) {
1025 unsigned First = true;
1026 for (auto *Param : *Params) {
1033 switch (Param->getVariance()) {
1034 case ObjCTypeParamVariance::Invariant:
1037 case ObjCTypeParamVariance::Covariant:
1038 Out << "__covariant ";
1041 case ObjCTypeParamVariance::Contravariant:
1042 Out << "__contravariant ";
1046 Out << Param->getDeclName().getAsString();
1048 if (Param->hasExplicitBound()) {
1049 Out << " : " << Param->getUnderlyingType().getAsString(Policy);
1055 void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) {
1056 if (OMD->isInstanceMethod())
1060 if (!OMD->getReturnType().isNull()) {
1061 PrintObjCMethodType(OMD->getASTContext(), OMD->getObjCDeclQualifier(),
1062 OMD->getReturnType());
1065 std::string name = OMD->getSelector().getAsString();
1066 std::string::size_type pos, lastPos = 0;
1067 for (const auto *PI : OMD->parameters()) {
1068 // FIXME: selector is missing here!
1069 pos = name.find_first_of(':', lastPos);
1070 Out << " " << name.substr(lastPos, pos - lastPos) << ':';
1071 PrintObjCMethodType(OMD->getASTContext(),
1072 PI->getObjCDeclQualifier(),
1078 if (OMD->param_begin() == OMD->param_end())
1081 if (OMD->isVariadic())
1084 prettyPrintAttributes(OMD);
1086 if (OMD->getBody() && !Policy.TerseOutput) {
1088 OMD->getBody()->printPretty(Out, nullptr, Policy);
1090 else if (Policy.PolishForDeclaration)
1094 void DeclPrinter::VisitObjCImplementationDecl(ObjCImplementationDecl *OID) {
1095 std::string I = OID->getNameAsString();
1096 ObjCInterfaceDecl *SID = OID->getSuperClass();
1098 bool eolnOut = false;
1100 Out << "@implementation " << I << " : " << *SID;
1102 Out << "@implementation " << I;
1104 if (OID->ivar_size() > 0) {
1107 Indentation += Policy.Indentation;
1108 for (const auto *I : OID->ivars()) {
1109 Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).
1110 getAsString(Policy) << ' ' << *I << ";\n";
1112 Indentation -= Policy.Indentation;
1115 else if (SID || (OID->decls_begin() != OID->decls_end())) {
1119 VisitDeclContext(OID, false);
1125 void DeclPrinter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *OID) {
1126 std::string I = OID->getNameAsString();
1127 ObjCInterfaceDecl *SID = OID->getSuperClass();
1129 if (!OID->isThisDeclarationADefinition()) {
1130 Out << "@class " << I;
1132 if (auto TypeParams = OID->getTypeParamListAsWritten()) {
1133 PrintObjCTypeParams(TypeParams);
1139 bool eolnOut = false;
1140 Out << "@interface " << I;
1142 if (auto TypeParams = OID->getTypeParamListAsWritten()) {
1143 PrintObjCTypeParams(TypeParams);
1147 Out << " : " << QualType(OID->getSuperClassType(), 0).getAsString(Policy);
1150 const ObjCList<ObjCProtocolDecl> &Protocols = OID->getReferencedProtocols();
1151 if (!Protocols.empty()) {
1152 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1153 E = Protocols.end(); I != E; ++I)
1154 Out << (I == Protocols.begin() ? '<' : ',') << **I;
1158 if (OID->ivar_size() > 0) {
1161 Indentation += Policy.Indentation;
1162 for (const auto *I : OID->ivars()) {
1163 Indent() << I->getASTContext()
1164 .getUnqualifiedObjCPointerType(I->getType())
1165 .getAsString(Policy) << ' ' << *I << ";\n";
1167 Indentation -= Policy.Indentation;
1170 else if (SID || (OID->decls_begin() != OID->decls_end())) {
1175 VisitDeclContext(OID, false);
1179 // FIXME: implement the rest...
1182 void DeclPrinter::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1183 if (!PID->isThisDeclarationADefinition()) {
1184 Out << "@protocol " << *PID << ";\n";
1188 const ObjCList<ObjCProtocolDecl> &Protocols = PID->getReferencedProtocols();
1189 if (!Protocols.empty()) {
1190 Out << "@protocol " << *PID;
1191 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1192 E = Protocols.end(); I != E; ++I)
1193 Out << (I == Protocols.begin() ? '<' : ',') << **I;
1196 Out << "@protocol " << *PID << '\n';
1197 VisitDeclContext(PID, false);
1201 void DeclPrinter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *PID) {
1202 Out << "@implementation " << *PID->getClassInterface() << '(' << *PID <<")\n";
1204 VisitDeclContext(PID, false);
1206 // FIXME: implement the rest...
1209 void DeclPrinter::VisitObjCCategoryDecl(ObjCCategoryDecl *PID) {
1210 Out << "@interface " << *PID->getClassInterface();
1211 if (auto TypeParams = PID->getTypeParamList()) {
1212 PrintObjCTypeParams(TypeParams);
1214 Out << "(" << *PID << ")\n";
1215 if (PID->ivar_size() > 0) {
1217 Indentation += Policy.Indentation;
1218 for (const auto *I : PID->ivars())
1219 Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).
1220 getAsString(Policy) << ' ' << *I << ";\n";
1221 Indentation -= Policy.Indentation;
1225 VisitDeclContext(PID, false);
1228 // FIXME: implement the rest...
1231 void DeclPrinter::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *AID) {
1232 Out << "@compatibility_alias " << *AID
1233 << ' ' << *AID->getClassInterface() << ";\n";
1236 /// PrintObjCPropertyDecl - print a property declaration.
1238 void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) {
1239 if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Required)
1240 Out << "@required\n";
1241 else if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Optional)
1242 Out << "@optional\n";
1244 QualType T = PDecl->getType();
1247 if (PDecl->getPropertyAttributes() != ObjCPropertyDecl::OBJC_PR_noattr) {
1250 if (PDecl->getPropertyAttributes() &
1251 ObjCPropertyDecl::OBJC_PR_readonly) {
1252 Out << (first ? ' ' : ',') << "readonly";
1256 if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
1257 Out << (first ? ' ' : ',') << "getter = ";
1258 PDecl->getGetterName().print(Out);
1261 if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
1262 Out << (first ? ' ' : ',') << "setter = ";
1263 PDecl->getSetterName().print(Out);
1267 if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_assign) {
1268 Out << (first ? ' ' : ',') << "assign";
1272 if (PDecl->getPropertyAttributes() &
1273 ObjCPropertyDecl::OBJC_PR_readwrite) {
1274 Out << (first ? ' ' : ',') << "readwrite";
1278 if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain) {
1279 Out << (first ? ' ' : ',') << "retain";
1283 if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_strong) {
1284 Out << (first ? ' ' : ',') << "strong";
1288 if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy) {
1289 Out << (first ? ' ' : ',') << "copy";
1293 if (PDecl->getPropertyAttributes() &
1294 ObjCPropertyDecl::OBJC_PR_nonatomic) {
1295 Out << (first ? ' ' : ',') << "nonatomic";
1298 if (PDecl->getPropertyAttributes() &
1299 ObjCPropertyDecl::OBJC_PR_atomic) {
1300 Out << (first ? ' ' : ',') << "atomic";
1304 if (PDecl->getPropertyAttributes() &
1305 ObjCPropertyDecl::OBJC_PR_nullability) {
1306 if (auto nullability = AttributedType::stripOuterNullability(T)) {
1307 if (*nullability == NullabilityKind::Unspecified &&
1308 (PDecl->getPropertyAttributes() &
1309 ObjCPropertyDecl::OBJC_PR_null_resettable)) {
1310 Out << (first ? ' ' : ',') << "null_resettable";
1312 Out << (first ? ' ' : ',')
1313 << getNullabilitySpelling(*nullability, true);
1319 if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_class) {
1320 Out << (first ? ' ' : ',') << "class";
1324 (void) first; // Silence dead store warning due to idiomatic code.
1327 Out << ' ' << PDecl->getASTContext().getUnqualifiedObjCPointerType(T).
1328 getAsString(Policy) << ' ' << *PDecl;
1329 if (Policy.PolishForDeclaration)
1333 void DeclPrinter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PID) {
1334 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize)
1335 Out << "@synthesize ";
1338 Out << *PID->getPropertyDecl();
1339 if (PID->getPropertyIvarDecl())
1340 Out << '=' << *PID->getPropertyIvarDecl();
1343 void DeclPrinter::VisitUsingDecl(UsingDecl *D) {
1344 if (!D->isAccessDeclaration())
1346 if (D->hasTypename())
1348 D->getQualifier()->print(Out, Policy);
1353 DeclPrinter::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
1354 Out << "using typename ";
1355 D->getQualifier()->print(Out, Policy);
1356 Out << D->getDeclName();
1359 void DeclPrinter::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1360 if (!D->isAccessDeclaration())
1362 D->getQualifier()->print(Out, Policy);
1363 Out << D->getDeclName();
1366 void DeclPrinter::VisitUsingShadowDecl(UsingShadowDecl *D) {
1370 void DeclPrinter::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
1371 Out << "#pragma omp threadprivate";
1372 if (!D->varlist_empty()) {
1373 for (OMPThreadPrivateDecl::varlist_iterator I = D->varlist_begin(),
1374 E = D->varlist_end();
1376 Out << (I == D->varlist_begin() ? '(' : ',');
1377 NamedDecl *ND = cast<NamedDecl>(cast<DeclRefExpr>(*I)->getDecl());
1378 ND->printQualifiedName(Out);
1384 void DeclPrinter::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
1385 if (!D->isInvalidDecl()) {
1386 Out << "#pragma omp declare reduction (";
1387 if (D->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) {
1388 static const char *const OperatorNames[NUM_OVERLOADED_OPERATORS] = {
1390 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
1392 #include "clang/Basic/OperatorKinds.def"
1394 const char *OpName =
1395 OperatorNames[D->getDeclName().getCXXOverloadedOperator()];
1396 assert(OpName && "not an overloaded operator");
1399 assert(D->getDeclName().isIdentifier());
1403 D->getType().print(Out, Policy);
1405 D->getCombiner()->printPretty(Out, nullptr, Policy, 0);
1407 if (auto *Init = D->getInitializer()) {
1408 Out << " initializer(";
1409 Init->printPretty(Out, nullptr, Policy, 0);
1415 void DeclPrinter::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
1416 D->getInit()->printPretty(Out, nullptr, Policy, Indentation);