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);
96 void PrintTemplateParameters(const TemplateParameterList *Params,
97 const TemplateArgumentList *Args = nullptr);
98 void prettyPrintAttributes(Decl *D);
99 void printDeclType(QualType T, StringRef DeclName, bool Pack = false);
103 void Decl::print(raw_ostream &Out, unsigned Indentation,
104 bool PrintInstantiation) const {
105 print(Out, getASTContext().getPrintingPolicy(), Indentation, PrintInstantiation);
108 void Decl::print(raw_ostream &Out, const PrintingPolicy &Policy,
109 unsigned Indentation, bool PrintInstantiation) const {
110 DeclPrinter Printer(Out, Policy, Indentation, PrintInstantiation);
111 Printer.Visit(const_cast<Decl*>(this));
114 static QualType GetBaseType(QualType T) {
115 // FIXME: This should be on the Type class!
116 QualType BaseType = T;
117 while (!BaseType->isSpecifierType()) {
118 if (isa<TypedefType>(BaseType))
120 else if (const PointerType* PTy = BaseType->getAs<PointerType>())
121 BaseType = PTy->getPointeeType();
122 else if (const BlockPointerType *BPy = BaseType->getAs<BlockPointerType>())
123 BaseType = BPy->getPointeeType();
124 else if (const ArrayType* ATy = dyn_cast<ArrayType>(BaseType))
125 BaseType = ATy->getElementType();
126 else if (const FunctionType* FTy = BaseType->getAs<FunctionType>())
127 BaseType = FTy->getReturnType();
128 else if (const VectorType *VTy = BaseType->getAs<VectorType>())
129 BaseType = VTy->getElementType();
130 else if (const ReferenceType *RTy = BaseType->getAs<ReferenceType>())
131 BaseType = RTy->getPointeeType();
133 llvm_unreachable("Unknown declarator!");
138 static QualType getDeclType(Decl* D) {
139 if (TypedefNameDecl* TDD = dyn_cast<TypedefNameDecl>(D))
140 return TDD->getUnderlyingType();
141 if (ValueDecl* VD = dyn_cast<ValueDecl>(D))
142 return VD->getType();
146 void Decl::printGroup(Decl** Begin, unsigned NumDecls,
147 raw_ostream &Out, const PrintingPolicy &Policy,
148 unsigned Indentation) {
150 (*Begin)->print(Out, Policy, Indentation);
154 Decl** End = Begin + NumDecls;
155 TagDecl* TD = dyn_cast<TagDecl>(*Begin);
159 PrintingPolicy SubPolicy(Policy);
160 if (TD && TD->isCompleteDefinition()) {
161 TD->print(Out, Policy, Indentation);
163 SubPolicy.SuppressTag = true;
167 for ( ; Begin != End; ++Begin) {
169 SubPolicy.SuppressSpecifiers = false;
172 if (!isFirst) Out << ", ";
173 SubPolicy.SuppressSpecifiers = true;
176 (*Begin)->print(Out, SubPolicy, Indentation);
180 LLVM_DUMP_METHOD void DeclContext::dumpDeclContext() const {
181 // Get the translation unit
182 const DeclContext *DC = this;
183 while (!DC->isTranslationUnit())
184 DC = DC->getParent();
186 ASTContext &Ctx = cast<TranslationUnitDecl>(DC)->getASTContext();
187 DeclPrinter Printer(llvm::errs(), Ctx.getPrintingPolicy(), 0);
188 Printer.VisitDeclContext(const_cast<DeclContext *>(this), /*Indent=*/false);
191 raw_ostream& DeclPrinter::Indent(unsigned Indentation) {
192 for (unsigned i = 0; i != Indentation; ++i)
197 void DeclPrinter::prettyPrintAttributes(Decl *D) {
198 if (Policy.PolishForDeclaration)
202 AttrVec &Attrs = D->getAttrs();
203 for (AttrVec::const_iterator i=Attrs.begin(), e=Attrs.end(); i!=e; ++i) {
205 A->printPretty(Out, Policy);
210 void DeclPrinter::printDeclType(QualType T, StringRef DeclName, bool Pack) {
211 // Normally, a PackExpansionType is written as T[3]... (for instance, as a
212 // template argument), but if it is the type of a declaration, the ellipsis
213 // is placed before the name being declared.
214 if (auto *PET = T->getAs<PackExpansionType>()) {
216 T = PET->getPattern();
218 T.print(Out, Policy, (Pack ? "..." : "") + DeclName);
221 void DeclPrinter::ProcessDeclGroup(SmallVectorImpl<Decl*>& Decls) {
223 Decl::printGroup(Decls.data(), Decls.size(), Out, Policy, Indentation);
229 void DeclPrinter::Print(AccessSpecifier AS) {
231 case AS_none: llvm_unreachable("No access specifier!");
232 case AS_public: Out << "public"; break;
233 case AS_protected: Out << "protected"; break;
234 case AS_private: Out << "private"; break;
238 //----------------------------------------------------------------------------
239 // Common C declarations
240 //----------------------------------------------------------------------------
242 void DeclPrinter::VisitDeclContext(DeclContext *DC, bool Indent) {
243 if (Policy.TerseOutput)
247 Indentation += Policy.Indentation;
249 SmallVector<Decl*, 2> Decls;
250 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
253 // Don't print ObjCIvarDecls, as they are printed when visiting the
254 // containing ObjCInterfaceDecl.
255 if (isa<ObjCIvarDecl>(*D))
258 // Skip over implicit declarations in pretty-printing mode.
262 // The next bits of code handles stuff like "struct {int x;} a,b"; we're
263 // forced to merge the declarations because there's no other way to
264 // refer to the struct in question. This limited merging is safe without
265 // a bunch of other checks because it only merges declarations directly
266 // referring to the tag, not typedefs.
268 // Check whether the current declaration should be grouped with a previous
270 QualType CurDeclType = getDeclType(*D);
271 if (!Decls.empty() && !CurDeclType.isNull()) {
272 QualType BaseType = GetBaseType(CurDeclType);
273 if (!BaseType.isNull() && isa<ElaboratedType>(BaseType))
274 BaseType = cast<ElaboratedType>(BaseType)->getNamedType();
275 if (!BaseType.isNull() && isa<TagType>(BaseType) &&
276 cast<TagType>(BaseType)->getDecl() == Decls[0]) {
282 // If we have a merged group waiting to be handled, handle it now.
284 ProcessDeclGroup(Decls);
286 // If the current declaration is an unnamed tag type, save it
287 // so we can merge it with the subsequent declaration(s) using it.
288 if (isa<TagDecl>(*D) && !cast<TagDecl>(*D)->getIdentifier()) {
293 if (isa<AccessSpecDecl>(*D)) {
294 Indentation -= Policy.Indentation;
296 Print(D->getAccess());
298 Indentation += Policy.Indentation;
305 // FIXME: Need to be able to tell the DeclPrinter when
306 const char *Terminator = nullptr;
307 if (isa<OMPThreadPrivateDecl>(*D))
308 Terminator = nullptr;
309 else if (isa<FunctionDecl>(*D) &&
310 cast<FunctionDecl>(*D)->isThisDeclarationADefinition())
311 Terminator = nullptr;
312 else if (isa<ObjCMethodDecl>(*D) && cast<ObjCMethodDecl>(*D)->getBody())
313 Terminator = nullptr;
314 else if (isa<NamespaceDecl>(*D) || isa<LinkageSpecDecl>(*D) ||
315 isa<ObjCImplementationDecl>(*D) ||
316 isa<ObjCInterfaceDecl>(*D) ||
317 isa<ObjCProtocolDecl>(*D) ||
318 isa<ObjCCategoryImplDecl>(*D) ||
319 isa<ObjCCategoryDecl>(*D))
320 Terminator = nullptr;
321 else if (isa<EnumConstantDecl>(*D)) {
322 DeclContext::decl_iterator Next = D;
335 ProcessDeclGroup(Decls);
338 Indentation -= Policy.Indentation;
341 void DeclPrinter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
342 VisitDeclContext(D, false);
345 void DeclPrinter::VisitTypedefDecl(TypedefDecl *D) {
346 if (!Policy.SuppressSpecifiers) {
349 if (D->isModulePrivate())
350 Out << "__module_private__ ";
352 D->getTypeSourceInfo()->getType().print(Out, Policy, D->getName());
353 prettyPrintAttributes(D);
356 void DeclPrinter::VisitTypeAliasDecl(TypeAliasDecl *D) {
357 Out << "using " << *D;
358 prettyPrintAttributes(D);
359 Out << " = " << D->getTypeSourceInfo()->getType().getAsString(Policy);
362 void DeclPrinter::VisitEnumDecl(EnumDecl *D) {
363 if (!Policy.SuppressSpecifiers && D->isModulePrivate())
364 Out << "__module_private__ ";
367 if (D->isScopedUsingClassTag())
375 Out << " : " << D->getIntegerType().stream(Policy);
377 if (D->isCompleteDefinition()) {
382 prettyPrintAttributes(D);
385 void DeclPrinter::VisitRecordDecl(RecordDecl *D) {
386 if (!Policy.SuppressSpecifiers && D->isModulePrivate())
387 Out << "__module_private__ ";
388 Out << D->getKindName();
390 prettyPrintAttributes(D);
392 if (D->getIdentifier())
395 if (D->isCompleteDefinition()) {
402 void DeclPrinter::VisitEnumConstantDecl(EnumConstantDecl *D) {
404 if (Expr *Init = D->getInitExpr()) {
406 Init->printPretty(Out, nullptr, Policy, Indentation);
410 void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) {
411 CXXConstructorDecl *CDecl = dyn_cast<CXXConstructorDecl>(D);
412 CXXConversionDecl *ConversionDecl = dyn_cast<CXXConversionDecl>(D);
413 if (!Policy.SuppressSpecifiers) {
414 switch (D->getStorageClass()) {
416 case SC_Extern: Out << "extern "; break;
417 case SC_Static: Out << "static "; break;
418 case SC_PrivateExtern: Out << "__private_extern__ "; break;
419 case SC_Auto: case SC_Register: case SC_OpenCLWorkGroupLocal:
420 llvm_unreachable("invalid for functions");
423 if (D->isInlineSpecified()) Out << "inline ";
424 if (D->isVirtualAsWritten()) Out << "virtual ";
425 if (D->isModulePrivate()) Out << "__module_private__ ";
426 if (D->isConstexpr() && !D->isExplicitlyDefaulted()) Out << "constexpr ";
427 if ((CDecl && CDecl->isExplicitSpecified()) ||
428 (ConversionDecl && ConversionDecl->isExplicit()))
432 PrintingPolicy SubPolicy(Policy);
433 SubPolicy.SuppressSpecifiers = false;
434 std::string Proto = D->getNameInfo().getAsString();
436 QualType Ty = D->getType();
437 while (const ParenType *PT = dyn_cast<ParenType>(Ty)) {
438 Proto = '(' + Proto + ')';
439 Ty = PT->getInnerType();
442 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
443 const FunctionProtoType *FT = nullptr;
444 if (D->hasWrittenPrototype())
445 FT = dyn_cast<FunctionProtoType>(AFT);
449 llvm::raw_string_ostream POut(Proto);
450 DeclPrinter ParamPrinter(POut, SubPolicy, Indentation);
451 for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
453 ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
456 if (FT->isVariadic()) {
457 if (D->getNumParams()) POut << ", ";
460 } else if (D->doesThisDeclarationHaveABody() && !D->hasPrototype()) {
461 for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
464 Proto += D->getParamDecl(i)->getNameAsString();
473 if (FT->isVolatile())
474 Proto += " volatile";
475 if (FT->isRestrict())
476 Proto += " restrict";
478 switch (FT->getRefQualifier()) {
490 if (FT && FT->hasDynamicExceptionSpec()) {
492 if (FT->getExceptionSpecType() == EST_MSAny)
495 for (unsigned I = 0, N = FT->getNumExceptions(); I != N; ++I) {
499 Proto += FT->getExceptionType(I).getAsString(SubPolicy);
502 } else if (FT && isNoexceptExceptionSpec(FT->getExceptionSpecType())) {
503 Proto += " noexcept";
504 if (FT->getExceptionSpecType() == EST_ComputedNoexcept) {
506 llvm::raw_string_ostream EOut(Proto);
507 FT->getNoexceptExpr()->printPretty(EOut, nullptr, SubPolicy,
516 bool HasInitializerList = false;
517 for (const auto *BMInitializer : CDecl->inits()) {
518 if (BMInitializer->isInClassMemberInitializer())
521 if (!HasInitializerList) {
525 HasInitializerList = true;
529 if (BMInitializer->isAnyMemberInitializer()) {
530 FieldDecl *FD = BMInitializer->getAnyMember();
533 Out << QualType(BMInitializer->getBaseClass(), 0).getAsString(Policy);
537 if (!BMInitializer->getInit()) {
540 Expr *Init = BMInitializer->getInit();
541 if (ExprWithCleanups *Tmp = dyn_cast<ExprWithCleanups>(Init))
542 Init = Tmp->getSubExpr();
544 Init = Init->IgnoreParens();
546 Expr *SimpleInit = nullptr;
547 Expr **Args = nullptr;
548 unsigned NumArgs = 0;
549 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
550 Args = ParenList->getExprs();
551 NumArgs = ParenList->getNumExprs();
552 } else if (CXXConstructExpr *Construct
553 = dyn_cast<CXXConstructExpr>(Init)) {
554 Args = Construct->getArgs();
555 NumArgs = Construct->getNumArgs();
560 SimpleInit->printPretty(Out, nullptr, Policy, Indentation);
562 for (unsigned I = 0; I != NumArgs; ++I) {
563 assert(Args[I] != nullptr && "Expected non-null Expr");
564 if (isa<CXXDefaultArgExpr>(Args[I]))
569 Args[I]->printPretty(Out, nullptr, Policy, Indentation);
574 if (BMInitializer->isPackExpansion())
577 } else if (!ConversionDecl && !isa<CXXDestructorDecl>(D)) {
578 if (FT && FT->hasTrailingReturn()) {
579 Out << "auto " << Proto << " -> ";
582 AFT->getReturnType().print(Out, Policy, Proto);
587 Ty.print(Out, Policy, Proto);
590 prettyPrintAttributes(D);
594 else if (D->isDeletedAsWritten())
596 else if (D->isExplicitlyDefaulted())
598 else if (D->doesThisDeclarationHaveABody() && !Policy.TerseOutput) {
599 if (!D->hasPrototype() && D->getNumParams()) {
600 // This is a K&R function definition, so we need to print the
603 DeclPrinter ParamPrinter(Out, SubPolicy, Indentation);
604 Indentation += Policy.Indentation;
605 for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
607 ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
610 Indentation -= Policy.Indentation;
615 D->getBody()->printPretty(Out, nullptr, SubPolicy, Indentation);
620 void DeclPrinter::VisitFriendDecl(FriendDecl *D) {
621 if (TypeSourceInfo *TSI = D->getFriendType()) {
622 unsigned NumTPLists = D->getFriendTypeNumTemplateParameterLists();
623 for (unsigned i = 0; i < NumTPLists; ++i)
624 PrintTemplateParameters(D->getFriendTypeTemplateParameterList(i));
626 Out << " " << TSI->getType().getAsString(Policy);
628 else if (FunctionDecl *FD =
629 dyn_cast<FunctionDecl>(D->getFriendDecl())) {
631 VisitFunctionDecl(FD);
633 else if (FunctionTemplateDecl *FTD =
634 dyn_cast<FunctionTemplateDecl>(D->getFriendDecl())) {
636 VisitFunctionTemplateDecl(FTD);
638 else if (ClassTemplateDecl *CTD =
639 dyn_cast<ClassTemplateDecl>(D->getFriendDecl())) {
641 VisitRedeclarableTemplateDecl(CTD);
645 void DeclPrinter::VisitFieldDecl(FieldDecl *D) {
646 if (!Policy.SuppressSpecifiers && D->isMutable())
648 if (!Policy.SuppressSpecifiers && D->isModulePrivate())
649 Out << "__module_private__ ";
651 Out << D->getASTContext().getUnqualifiedObjCPointerType(D->getType()).
652 stream(Policy, D->getName());
654 if (D->isBitField()) {
656 D->getBitWidth()->printPretty(Out, nullptr, Policy, Indentation);
659 Expr *Init = D->getInClassInitializer();
660 if (!Policy.SuppressInitializers && Init) {
661 if (D->getInClassInitStyle() == ICIS_ListInit)
665 Init->printPretty(Out, nullptr, Policy, Indentation);
667 prettyPrintAttributes(D);
670 void DeclPrinter::VisitLabelDecl(LabelDecl *D) {
674 void DeclPrinter::VisitVarDecl(VarDecl *D) {
675 if (!Policy.SuppressSpecifiers) {
676 StorageClass SC = D->getStorageClass();
678 Out << VarDecl::getStorageClassSpecifierString(SC) << " ";
680 switch (D->getTSCSpec()) {
681 case TSCS_unspecified:
686 case TSCS__Thread_local:
687 Out << "_Thread_local ";
689 case TSCS_thread_local:
690 Out << "thread_local ";
694 if (D->isModulePrivate())
695 Out << "__module_private__ ";
698 QualType T = D->getTypeSourceInfo()
699 ? D->getTypeSourceInfo()->getType()
700 : D->getASTContext().getUnqualifiedObjCPointerType(D->getType());
701 printDeclType(T, D->getName());
702 Expr *Init = D->getInit();
703 if (!Policy.SuppressInitializers && Init) {
704 bool ImplicitInit = false;
705 if (CXXConstructExpr *Construct =
706 dyn_cast<CXXConstructExpr>(Init->IgnoreImplicit())) {
707 if (D->getInitStyle() == VarDecl::CallInit &&
708 !Construct->isListInitialization()) {
709 ImplicitInit = Construct->getNumArgs() == 0 ||
710 Construct->getArg(0)->isDefaultArgument();
714 if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
716 else if (D->getInitStyle() == VarDecl::CInit) {
719 Init->printPretty(Out, nullptr, Policy, Indentation);
720 if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
724 prettyPrintAttributes(D);
727 void DeclPrinter::VisitParmVarDecl(ParmVarDecl *D) {
731 void DeclPrinter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) {
733 D->getAsmString()->printPretty(Out, nullptr, Policy, Indentation);
737 void DeclPrinter::VisitImportDecl(ImportDecl *D) {
738 Out << "@import " << D->getImportedModule()->getFullModuleName()
742 void DeclPrinter::VisitStaticAssertDecl(StaticAssertDecl *D) {
743 Out << "static_assert(";
744 D->getAssertExpr()->printPretty(Out, nullptr, Policy, Indentation);
745 if (StringLiteral *SL = D->getMessage()) {
747 SL->printPretty(Out, nullptr, Policy, Indentation);
752 //----------------------------------------------------------------------------
754 //----------------------------------------------------------------------------
755 void DeclPrinter::VisitNamespaceDecl(NamespaceDecl *D) {
758 Out << "namespace " << *D << " {\n";
763 void DeclPrinter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
764 Out << "using namespace ";
765 if (D->getQualifier())
766 D->getQualifier()->print(Out, Policy);
767 Out << *D->getNominatedNamespaceAsWritten();
770 void DeclPrinter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
771 Out << "namespace " << *D << " = ";
772 if (D->getQualifier())
773 D->getQualifier()->print(Out, Policy);
774 Out << *D->getAliasedNamespace();
777 void DeclPrinter::VisitEmptyDecl(EmptyDecl *D) {
778 prettyPrintAttributes(D);
781 void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) {
782 if (!Policy.SuppressSpecifiers && D->isModulePrivate())
783 Out << "__module_private__ ";
784 Out << D->getKindName();
786 prettyPrintAttributes(D);
788 if (D->getIdentifier())
791 if (D->isCompleteDefinition()) {
792 // Print the base classes
793 if (D->getNumBases()) {
795 for (CXXRecordDecl::base_class_iterator Base = D->bases_begin(),
796 BaseEnd = D->bases_end(); Base != BaseEnd; ++Base) {
797 if (Base != D->bases_begin())
800 if (Base->isVirtual())
803 AccessSpecifier AS = Base->getAccessSpecifierAsWritten();
808 Out << Base->getType().getAsString(Policy);
810 if (Base->isPackExpansion())
815 // Print the class definition
816 // FIXME: Doesn't print access specifiers, e.g., "public:"
823 void DeclPrinter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
825 if (D->getLanguage() == LinkageSpecDecl::lang_c)
828 assert(D->getLanguage() == LinkageSpecDecl::lang_cxx &&
829 "unknown language in linkage specification");
833 Out << "extern \"" << l << "\" ";
834 if (D->hasBraces()) {
839 Visit(*D->decls_begin());
842 void DeclPrinter::PrintTemplateParameters(const TemplateParameterList *Params,
843 const TemplateArgumentList *Args) {
845 assert(!Args || Params->size() == Args->size());
849 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
853 const Decl *Param = Params->getParam(i);
854 if (const TemplateTypeParmDecl *TTP =
855 dyn_cast<TemplateTypeParmDecl>(Param)) {
857 if (TTP->wasDeclaredWithTypename())
862 if (TTP->isParameterPack())
869 Args->get(i).print(Policy, Out);
870 } else if (TTP->hasDefaultArgument()) {
872 Out << TTP->getDefaultArgument().getAsString(Policy);
874 } else if (const NonTypeTemplateParmDecl *NTTP =
875 dyn_cast<NonTypeTemplateParmDecl>(Param)) {
877 if (IdentifierInfo *II = NTTP->getIdentifier())
878 Name = II->getName();
879 printDeclType(NTTP->getType(), Name, NTTP->isParameterPack());
883 Args->get(i).print(Policy, Out);
884 } else if (NTTP->hasDefaultArgument()) {
886 NTTP->getDefaultArgument()->printPretty(Out, nullptr, Policy,
889 } else if (const TemplateTemplateParmDecl *TTPD =
890 dyn_cast<TemplateTemplateParmDecl>(Param)) {
891 VisitTemplateDecl(TTPD);
892 // FIXME: print the default argument, if present.
899 void DeclPrinter::VisitTemplateDecl(const TemplateDecl *D) {
900 PrintTemplateParameters(D->getTemplateParameters());
902 if (const TemplateTemplateParmDecl *TTP =
903 dyn_cast<TemplateTemplateParmDecl>(D)) {
905 if (TTP->isParameterPack())
909 Visit(D->getTemplatedDecl());
913 void DeclPrinter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
914 if (PrintInstantiation) {
915 TemplateParameterList *Params = D->getTemplateParameters();
916 for (auto *I : D->specializations()) {
917 PrintTemplateParameters(Params, I->getTemplateSpecializationArgs());
922 return VisitRedeclarableTemplateDecl(D);
925 void DeclPrinter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
926 if (PrintInstantiation) {
927 TemplateParameterList *Params = D->getTemplateParameters();
928 for (auto *I : D->specializations()) {
929 PrintTemplateParameters(Params, &I->getTemplateArgs());
935 return VisitRedeclarableTemplateDecl(D);
938 //----------------------------------------------------------------------------
939 // Objective-C declarations
940 //----------------------------------------------------------------------------
942 void DeclPrinter::PrintObjCMethodType(ASTContext &Ctx,
943 Decl::ObjCDeclQualifier Quals,
946 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_In)
948 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Inout)
950 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Out)
952 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Bycopy)
954 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Byref)
956 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Oneway)
958 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_CSNullability) {
959 if (auto nullability = AttributedType::stripOuterNullability(T))
960 Out << getNullabilitySpelling(*nullability, true) << ' ';
963 Out << Ctx.getUnqualifiedObjCPointerType(T).getAsString(Policy);
967 void DeclPrinter::PrintObjCTypeParams(ObjCTypeParamList *Params) {
969 unsigned First = true;
970 for (auto *Param : *Params) {
977 switch (Param->getVariance()) {
978 case ObjCTypeParamVariance::Invariant:
981 case ObjCTypeParamVariance::Covariant:
982 Out << "__covariant ";
985 case ObjCTypeParamVariance::Contravariant:
986 Out << "__contravariant ";
990 Out << Param->getDeclName().getAsString();
992 if (Param->hasExplicitBound()) {
993 Out << " : " << Param->getUnderlyingType().getAsString(Policy);
999 void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) {
1000 if (OMD->isInstanceMethod())
1004 if (!OMD->getReturnType().isNull()) {
1005 PrintObjCMethodType(OMD->getASTContext(), OMD->getObjCDeclQualifier(),
1006 OMD->getReturnType());
1009 std::string name = OMD->getSelector().getAsString();
1010 std::string::size_type pos, lastPos = 0;
1011 for (const auto *PI : OMD->params()) {
1012 // FIXME: selector is missing here!
1013 pos = name.find_first_of(':', lastPos);
1014 Out << " " << name.substr(lastPos, pos - lastPos) << ':';
1015 PrintObjCMethodType(OMD->getASTContext(),
1016 PI->getObjCDeclQualifier(),
1022 if (OMD->param_begin() == OMD->param_end())
1025 if (OMD->isVariadic())
1028 prettyPrintAttributes(OMD);
1030 if (OMD->getBody() && !Policy.TerseOutput) {
1032 OMD->getBody()->printPretty(Out, nullptr, Policy);
1034 else if (Policy.PolishForDeclaration)
1038 void DeclPrinter::VisitObjCImplementationDecl(ObjCImplementationDecl *OID) {
1039 std::string I = OID->getNameAsString();
1040 ObjCInterfaceDecl *SID = OID->getSuperClass();
1042 bool eolnOut = false;
1044 Out << "@implementation " << I << " : " << *SID;
1046 Out << "@implementation " << I;
1048 if (OID->ivar_size() > 0) {
1051 Indentation += Policy.Indentation;
1052 for (const auto *I : OID->ivars()) {
1053 Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).
1054 getAsString(Policy) << ' ' << *I << ";\n";
1056 Indentation -= Policy.Indentation;
1059 else if (SID || (OID->decls_begin() != OID->decls_end())) {
1063 VisitDeclContext(OID, false);
1069 void DeclPrinter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *OID) {
1070 std::string I = OID->getNameAsString();
1071 ObjCInterfaceDecl *SID = OID->getSuperClass();
1073 if (!OID->isThisDeclarationADefinition()) {
1074 Out << "@class " << I;
1076 if (auto TypeParams = OID->getTypeParamListAsWritten()) {
1077 PrintObjCTypeParams(TypeParams);
1083 bool eolnOut = false;
1084 Out << "@interface " << I;
1086 if (auto TypeParams = OID->getTypeParamListAsWritten()) {
1087 PrintObjCTypeParams(TypeParams);
1091 Out << " : " << OID->getSuperClass()->getName();
1094 const ObjCList<ObjCProtocolDecl> &Protocols = OID->getReferencedProtocols();
1095 if (!Protocols.empty()) {
1096 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1097 E = Protocols.end(); I != E; ++I)
1098 Out << (I == Protocols.begin() ? '<' : ',') << **I;
1102 if (OID->ivar_size() > 0) {
1105 Indentation += Policy.Indentation;
1106 for (const auto *I : OID->ivars()) {
1107 Indent() << I->getASTContext()
1108 .getUnqualifiedObjCPointerType(I->getType())
1109 .getAsString(Policy) << ' ' << *I << ";\n";
1111 Indentation -= Policy.Indentation;
1114 else if (SID || (OID->decls_begin() != OID->decls_end())) {
1119 VisitDeclContext(OID, false);
1123 // FIXME: implement the rest...
1126 void DeclPrinter::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1127 if (!PID->isThisDeclarationADefinition()) {
1128 Out << "@protocol " << *PID << ";\n";
1132 const ObjCList<ObjCProtocolDecl> &Protocols = PID->getReferencedProtocols();
1133 if (!Protocols.empty()) {
1134 Out << "@protocol " << *PID;
1135 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1136 E = Protocols.end(); I != E; ++I)
1137 Out << (I == Protocols.begin() ? '<' : ',') << **I;
1140 Out << "@protocol " << *PID << '\n';
1141 VisitDeclContext(PID, false);
1145 void DeclPrinter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *PID) {
1146 Out << "@implementation " << *PID->getClassInterface() << '(' << *PID <<")\n";
1148 VisitDeclContext(PID, false);
1150 // FIXME: implement the rest...
1153 void DeclPrinter::VisitObjCCategoryDecl(ObjCCategoryDecl *PID) {
1154 Out << "@interface " << *PID->getClassInterface();
1155 if (auto TypeParams = PID->getTypeParamList()) {
1156 PrintObjCTypeParams(TypeParams);
1158 Out << "(" << *PID << ")\n";
1159 if (PID->ivar_size() > 0) {
1161 Indentation += Policy.Indentation;
1162 for (const auto *I : PID->ivars())
1163 Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).
1164 getAsString(Policy) << ' ' << *I << ";\n";
1165 Indentation -= Policy.Indentation;
1169 VisitDeclContext(PID, false);
1172 // FIXME: implement the rest...
1175 void DeclPrinter::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *AID) {
1176 Out << "@compatibility_alias " << *AID
1177 << ' ' << *AID->getClassInterface() << ";\n";
1180 /// PrintObjCPropertyDecl - print a property declaration.
1182 void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) {
1183 if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Required)
1184 Out << "@required\n";
1185 else if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Optional)
1186 Out << "@optional\n";
1188 QualType T = PDecl->getType();
1191 if (PDecl->getPropertyAttributes() != ObjCPropertyDecl::OBJC_PR_noattr) {
1194 if (PDecl->getPropertyAttributes() &
1195 ObjCPropertyDecl::OBJC_PR_readonly) {
1196 Out << (first ? ' ' : ',') << "readonly";
1200 if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
1201 Out << (first ? ' ' : ',') << "getter = ";
1202 PDecl->getGetterName().print(Out);
1205 if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
1206 Out << (first ? ' ' : ',') << "setter = ";
1207 PDecl->getSetterName().print(Out);
1211 if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_assign) {
1212 Out << (first ? ' ' : ',') << "assign";
1216 if (PDecl->getPropertyAttributes() &
1217 ObjCPropertyDecl::OBJC_PR_readwrite) {
1218 Out << (first ? ' ' : ',') << "readwrite";
1222 if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain) {
1223 Out << (first ? ' ' : ',') << "retain";
1227 if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_strong) {
1228 Out << (first ? ' ' : ',') << "strong";
1232 if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy) {
1233 Out << (first ? ' ' : ',') << "copy";
1237 if (PDecl->getPropertyAttributes() &
1238 ObjCPropertyDecl::OBJC_PR_nonatomic) {
1239 Out << (first ? ' ' : ',') << "nonatomic";
1242 if (PDecl->getPropertyAttributes() &
1243 ObjCPropertyDecl::OBJC_PR_atomic) {
1244 Out << (first ? ' ' : ',') << "atomic";
1248 if (PDecl->getPropertyAttributes() &
1249 ObjCPropertyDecl::OBJC_PR_nullability) {
1250 if (auto nullability = AttributedType::stripOuterNullability(T)) {
1251 if (*nullability == NullabilityKind::Unspecified &&
1252 (PDecl->getPropertyAttributes() &
1253 ObjCPropertyDecl::OBJC_PR_null_resettable)) {
1254 Out << (first ? ' ' : ',') << "null_resettable";
1256 Out << (first ? ' ' : ',')
1257 << getNullabilitySpelling(*nullability, true);
1263 (void) first; // Silence dead store warning due to idiomatic code.
1266 Out << ' ' << PDecl->getASTContext().getUnqualifiedObjCPointerType(T).
1267 getAsString(Policy) << ' ' << *PDecl;
1268 if (Policy.PolishForDeclaration)
1272 void DeclPrinter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PID) {
1273 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize)
1274 Out << "@synthesize ";
1277 Out << *PID->getPropertyDecl();
1278 if (PID->getPropertyIvarDecl())
1279 Out << '=' << *PID->getPropertyIvarDecl();
1282 void DeclPrinter::VisitUsingDecl(UsingDecl *D) {
1283 if (!D->isAccessDeclaration())
1285 if (D->hasTypename())
1287 D->getQualifier()->print(Out, Policy);
1292 DeclPrinter::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
1293 Out << "using typename ";
1294 D->getQualifier()->print(Out, Policy);
1295 Out << D->getDeclName();
1298 void DeclPrinter::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1299 if (!D->isAccessDeclaration())
1301 D->getQualifier()->print(Out, Policy);
1302 Out << D->getName();
1305 void DeclPrinter::VisitUsingShadowDecl(UsingShadowDecl *D) {
1309 void DeclPrinter::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
1310 Out << "#pragma omp threadprivate";
1311 if (!D->varlist_empty()) {
1312 for (OMPThreadPrivateDecl::varlist_iterator I = D->varlist_begin(),
1313 E = D->varlist_end();
1315 Out << (I == D->varlist_begin() ? '(' : ',');
1316 NamedDecl *ND = cast<NamedDecl>(cast<DeclRefExpr>(*I)->getDecl());
1317 ND->printQualifiedName(Out);