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,
48 DeclPrinter(raw_ostream &Out, const PrintingPolicy &Policy,
49 unsigned Indentation = 0, bool PrintInstantiation = false)
50 : Out(Out), Policy(Policy), Indentation(Indentation),
51 PrintInstantiation(PrintInstantiation) { }
53 void VisitDeclContext(DeclContext *DC, bool Indent = true);
55 void VisitTranslationUnitDecl(TranslationUnitDecl *D);
56 void VisitTypedefDecl(TypedefDecl *D);
57 void VisitTypeAliasDecl(TypeAliasDecl *D);
58 void VisitEnumDecl(EnumDecl *D);
59 void VisitRecordDecl(RecordDecl *D);
60 void VisitEnumConstantDecl(EnumConstantDecl *D);
61 void VisitEmptyDecl(EmptyDecl *D);
62 void VisitFunctionDecl(FunctionDecl *D);
63 void VisitFriendDecl(FriendDecl *D);
64 void VisitFieldDecl(FieldDecl *D);
65 void VisitVarDecl(VarDecl *D);
66 void VisitLabelDecl(LabelDecl *D);
67 void VisitParmVarDecl(ParmVarDecl *D);
68 void VisitFileScopeAsmDecl(FileScopeAsmDecl *D);
69 void VisitImportDecl(ImportDecl *D);
70 void VisitStaticAssertDecl(StaticAssertDecl *D);
71 void VisitNamespaceDecl(NamespaceDecl *D);
72 void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
73 void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
74 void VisitCXXRecordDecl(CXXRecordDecl *D);
75 void VisitLinkageSpecDecl(LinkageSpecDecl *D);
76 void VisitTemplateDecl(const TemplateDecl *D);
77 void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
78 void VisitClassTemplateDecl(ClassTemplateDecl *D);
79 void VisitObjCMethodDecl(ObjCMethodDecl *D);
80 void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
81 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
82 void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
83 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
84 void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
85 void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
86 void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
87 void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
88 void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
89 void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
90 void VisitUsingDecl(UsingDecl *D);
91 void VisitUsingShadowDecl(UsingShadowDecl *D);
92 void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
94 void PrintTemplateParameters(const TemplateParameterList *Params,
95 const TemplateArgumentList *Args = nullptr);
96 void prettyPrintAttributes(Decl *D);
97 void printDeclType(QualType T, StringRef DeclName, bool Pack = false);
101 void Decl::print(raw_ostream &Out, unsigned Indentation,
102 bool PrintInstantiation) const {
103 print(Out, getASTContext().getPrintingPolicy(), Indentation, PrintInstantiation);
106 void Decl::print(raw_ostream &Out, const PrintingPolicy &Policy,
107 unsigned Indentation, bool PrintInstantiation) const {
108 DeclPrinter Printer(Out, Policy, Indentation, PrintInstantiation);
109 Printer.Visit(const_cast<Decl*>(this));
112 static QualType GetBaseType(QualType T) {
113 // FIXME: This should be on the Type class!
114 QualType BaseType = T;
115 while (!BaseType->isSpecifierType()) {
116 if (isa<TypedefType>(BaseType))
118 else if (const PointerType* PTy = BaseType->getAs<PointerType>())
119 BaseType = PTy->getPointeeType();
120 else if (const BlockPointerType *BPy = BaseType->getAs<BlockPointerType>())
121 BaseType = BPy->getPointeeType();
122 else if (const ArrayType* ATy = dyn_cast<ArrayType>(BaseType))
123 BaseType = ATy->getElementType();
124 else if (const FunctionType* FTy = BaseType->getAs<FunctionType>())
125 BaseType = FTy->getReturnType();
126 else if (const VectorType *VTy = BaseType->getAs<VectorType>())
127 BaseType = VTy->getElementType();
128 else if (const ReferenceType *RTy = BaseType->getAs<ReferenceType>())
129 BaseType = RTy->getPointeeType();
131 llvm_unreachable("Unknown declarator!");
136 static QualType getDeclType(Decl* D) {
137 if (TypedefNameDecl* TDD = dyn_cast<TypedefNameDecl>(D))
138 return TDD->getUnderlyingType();
139 if (ValueDecl* VD = dyn_cast<ValueDecl>(D))
140 return VD->getType();
144 void Decl::printGroup(Decl** Begin, unsigned NumDecls,
145 raw_ostream &Out, const PrintingPolicy &Policy,
146 unsigned Indentation) {
148 (*Begin)->print(Out, Policy, Indentation);
152 Decl** End = Begin + NumDecls;
153 TagDecl* TD = dyn_cast<TagDecl>(*Begin);
157 PrintingPolicy SubPolicy(Policy);
158 if (TD && TD->isCompleteDefinition()) {
159 TD->print(Out, Policy, Indentation);
161 SubPolicy.SuppressTag = true;
165 for ( ; Begin != End; ++Begin) {
167 SubPolicy.SuppressSpecifiers = false;
170 if (!isFirst) Out << ", ";
171 SubPolicy.SuppressSpecifiers = true;
174 (*Begin)->print(Out, SubPolicy, Indentation);
178 LLVM_DUMP_METHOD void DeclContext::dumpDeclContext() const {
179 // Get the translation unit
180 const DeclContext *DC = this;
181 while (!DC->isTranslationUnit())
182 DC = DC->getParent();
184 ASTContext &Ctx = cast<TranslationUnitDecl>(DC)->getASTContext();
185 DeclPrinter Printer(llvm::errs(), Ctx.getPrintingPolicy(), 0);
186 Printer.VisitDeclContext(const_cast<DeclContext *>(this), /*Indent=*/false);
189 raw_ostream& DeclPrinter::Indent(unsigned Indentation) {
190 for (unsigned i = 0; i != Indentation; ++i)
195 void DeclPrinter::prettyPrintAttributes(Decl *D) {
196 if (Policy.PolishForDeclaration)
200 AttrVec &Attrs = D->getAttrs();
201 for (AttrVec::const_iterator i=Attrs.begin(), e=Attrs.end(); i!=e; ++i) {
203 A->printPretty(Out, Policy);
208 void DeclPrinter::printDeclType(QualType T, StringRef DeclName, bool Pack) {
209 // Normally, a PackExpansionType is written as T[3]... (for instance, as a
210 // template argument), but if it is the type of a declaration, the ellipsis
211 // is placed before the name being declared.
212 if (auto *PET = T->getAs<PackExpansionType>()) {
214 T = PET->getPattern();
216 T.print(Out, Policy, (Pack ? "..." : "") + DeclName);
219 void DeclPrinter::ProcessDeclGroup(SmallVectorImpl<Decl*>& Decls) {
221 Decl::printGroup(Decls.data(), Decls.size(), Out, Policy, Indentation);
227 void DeclPrinter::Print(AccessSpecifier AS) {
229 case AS_none: llvm_unreachable("No access specifier!");
230 case AS_public: Out << "public"; break;
231 case AS_protected: Out << "protected"; break;
232 case AS_private: Out << "private"; break;
236 //----------------------------------------------------------------------------
237 // Common C declarations
238 //----------------------------------------------------------------------------
240 void DeclPrinter::VisitDeclContext(DeclContext *DC, bool Indent) {
241 if (Policy.TerseOutput)
245 Indentation += Policy.Indentation;
247 SmallVector<Decl*, 2> Decls;
248 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
251 // Don't print ObjCIvarDecls, as they are printed when visiting the
252 // containing ObjCInterfaceDecl.
253 if (isa<ObjCIvarDecl>(*D))
256 // Skip over implicit declarations in pretty-printing mode.
260 // The next bits of code handles stuff like "struct {int x;} a,b"; we're
261 // forced to merge the declarations because there's no other way to
262 // refer to the struct in question. This limited merging is safe without
263 // a bunch of other checks because it only merges declarations directly
264 // referring to the tag, not typedefs.
266 // Check whether the current declaration should be grouped with a previous
268 QualType CurDeclType = getDeclType(*D);
269 if (!Decls.empty() && !CurDeclType.isNull()) {
270 QualType BaseType = GetBaseType(CurDeclType);
271 if (!BaseType.isNull() && isa<ElaboratedType>(BaseType))
272 BaseType = cast<ElaboratedType>(BaseType)->getNamedType();
273 if (!BaseType.isNull() && isa<TagType>(BaseType) &&
274 cast<TagType>(BaseType)->getDecl() == Decls[0]) {
280 // If we have a merged group waiting to be handled, handle it now.
282 ProcessDeclGroup(Decls);
284 // If the current declaration is an unnamed tag type, save it
285 // so we can merge it with the subsequent declaration(s) using it.
286 if (isa<TagDecl>(*D) && !cast<TagDecl>(*D)->getIdentifier()) {
291 if (isa<AccessSpecDecl>(*D)) {
292 Indentation -= Policy.Indentation;
294 Print(D->getAccess());
296 Indentation += Policy.Indentation;
303 // FIXME: Need to be able to tell the DeclPrinter when
304 const char *Terminator = nullptr;
305 if (isa<OMPThreadPrivateDecl>(*D))
306 Terminator = nullptr;
307 else if (isa<FunctionDecl>(*D) &&
308 cast<FunctionDecl>(*D)->isThisDeclarationADefinition())
309 Terminator = nullptr;
310 else if (isa<ObjCMethodDecl>(*D) && cast<ObjCMethodDecl>(*D)->getBody())
311 Terminator = nullptr;
312 else if (isa<NamespaceDecl>(*D) || isa<LinkageSpecDecl>(*D) ||
313 isa<ObjCImplementationDecl>(*D) ||
314 isa<ObjCInterfaceDecl>(*D) ||
315 isa<ObjCProtocolDecl>(*D) ||
316 isa<ObjCCategoryImplDecl>(*D) ||
317 isa<ObjCCategoryDecl>(*D))
318 Terminator = nullptr;
319 else if (isa<EnumConstantDecl>(*D)) {
320 DeclContext::decl_iterator Next = D;
333 ProcessDeclGroup(Decls);
336 Indentation -= Policy.Indentation;
339 void DeclPrinter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
340 VisitDeclContext(D, false);
343 void DeclPrinter::VisitTypedefDecl(TypedefDecl *D) {
344 if (!Policy.SuppressSpecifiers) {
347 if (D->isModulePrivate())
348 Out << "__module_private__ ";
350 D->getTypeSourceInfo()->getType().print(Out, Policy, D->getName());
351 prettyPrintAttributes(D);
354 void DeclPrinter::VisitTypeAliasDecl(TypeAliasDecl *D) {
355 Out << "using " << *D;
356 prettyPrintAttributes(D);
357 Out << " = " << D->getTypeSourceInfo()->getType().getAsString(Policy);
360 void DeclPrinter::VisitEnumDecl(EnumDecl *D) {
361 if (!Policy.SuppressSpecifiers && D->isModulePrivate())
362 Out << "__module_private__ ";
365 if (D->isScopedUsingClassTag())
373 Out << " : " << D->getIntegerType().stream(Policy);
375 if (D->isCompleteDefinition()) {
380 prettyPrintAttributes(D);
383 void DeclPrinter::VisitRecordDecl(RecordDecl *D) {
384 if (!Policy.SuppressSpecifiers && D->isModulePrivate())
385 Out << "__module_private__ ";
386 Out << D->getKindName();
388 prettyPrintAttributes(D);
390 if (D->getIdentifier())
393 if (D->isCompleteDefinition()) {
400 void DeclPrinter::VisitEnumConstantDecl(EnumConstantDecl *D) {
402 if (Expr *Init = D->getInitExpr()) {
404 Init->printPretty(Out, nullptr, Policy, Indentation);
408 void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) {
409 CXXConstructorDecl *CDecl = dyn_cast<CXXConstructorDecl>(D);
410 CXXConversionDecl *ConversionDecl = dyn_cast<CXXConversionDecl>(D);
411 if (!Policy.SuppressSpecifiers) {
412 switch (D->getStorageClass()) {
414 case SC_Extern: Out << "extern "; break;
415 case SC_Static: Out << "static "; break;
416 case SC_PrivateExtern: Out << "__private_extern__ "; break;
417 case SC_Auto: case SC_Register: case SC_OpenCLWorkGroupLocal:
418 llvm_unreachable("invalid for functions");
421 if (D->isInlineSpecified()) Out << "inline ";
422 if (D->isVirtualAsWritten()) Out << "virtual ";
423 if (D->isModulePrivate()) Out << "__module_private__ ";
424 if (D->isConstexpr() && !D->isExplicitlyDefaulted()) Out << "constexpr ";
425 if ((CDecl && CDecl->isExplicitSpecified()) ||
426 (ConversionDecl && ConversionDecl->isExplicit()))
430 PrintingPolicy SubPolicy(Policy);
431 SubPolicy.SuppressSpecifiers = false;
432 std::string Proto = D->getNameInfo().getAsString();
434 QualType Ty = D->getType();
435 while (const ParenType *PT = dyn_cast<ParenType>(Ty)) {
436 Proto = '(' + Proto + ')';
437 Ty = PT->getInnerType();
440 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
441 const FunctionProtoType *FT = nullptr;
442 if (D->hasWrittenPrototype())
443 FT = dyn_cast<FunctionProtoType>(AFT);
447 llvm::raw_string_ostream POut(Proto);
448 DeclPrinter ParamPrinter(POut, SubPolicy, Indentation);
449 for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
451 ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
454 if (FT->isVariadic()) {
455 if (D->getNumParams()) POut << ", ";
458 } else if (D->doesThisDeclarationHaveABody() && !D->hasPrototype()) {
459 for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
462 Proto += D->getParamDecl(i)->getNameAsString();
471 if (FT->isVolatile())
472 Proto += " volatile";
473 if (FT->isRestrict())
474 Proto += " restrict";
476 switch (FT->getRefQualifier()) {
488 if (FT && FT->hasDynamicExceptionSpec()) {
490 if (FT->getExceptionSpecType() == EST_MSAny)
493 for (unsigned I = 0, N = FT->getNumExceptions(); I != N; ++I) {
497 Proto += FT->getExceptionType(I).getAsString(SubPolicy);
500 } else if (FT && isNoexceptExceptionSpec(FT->getExceptionSpecType())) {
501 Proto += " noexcept";
502 if (FT->getExceptionSpecType() == EST_ComputedNoexcept) {
504 llvm::raw_string_ostream EOut(Proto);
505 FT->getNoexceptExpr()->printPretty(EOut, nullptr, SubPolicy,
514 bool HasInitializerList = false;
515 for (const auto *BMInitializer : CDecl->inits()) {
516 if (BMInitializer->isInClassMemberInitializer())
519 if (!HasInitializerList) {
523 HasInitializerList = true;
527 if (BMInitializer->isAnyMemberInitializer()) {
528 FieldDecl *FD = BMInitializer->getAnyMember();
531 Out << QualType(BMInitializer->getBaseClass(), 0).getAsString(Policy);
535 if (!BMInitializer->getInit()) {
538 Expr *Init = BMInitializer->getInit();
539 if (ExprWithCleanups *Tmp = dyn_cast<ExprWithCleanups>(Init))
540 Init = Tmp->getSubExpr();
542 Init = Init->IgnoreParens();
544 Expr *SimpleInit = nullptr;
545 Expr **Args = nullptr;
546 unsigned NumArgs = 0;
547 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
548 Args = ParenList->getExprs();
549 NumArgs = ParenList->getNumExprs();
550 } else if (CXXConstructExpr *Construct
551 = dyn_cast<CXXConstructExpr>(Init)) {
552 Args = Construct->getArgs();
553 NumArgs = Construct->getNumArgs();
558 SimpleInit->printPretty(Out, nullptr, Policy, Indentation);
560 for (unsigned I = 0; I != NumArgs; ++I) {
561 assert(Args[I] != nullptr && "Expected non-null Expr");
562 if (isa<CXXDefaultArgExpr>(Args[I]))
567 Args[I]->printPretty(Out, nullptr, Policy, Indentation);
572 if (BMInitializer->isPackExpansion())
575 } else if (!ConversionDecl && !isa<CXXDestructorDecl>(D)) {
576 if (FT && FT->hasTrailingReturn()) {
577 Out << "auto " << Proto << " -> ";
580 AFT->getReturnType().print(Out, Policy, Proto);
585 Ty.print(Out, Policy, Proto);
588 prettyPrintAttributes(D);
592 else if (D->isDeletedAsWritten())
594 else if (D->isExplicitlyDefaulted())
596 else if (D->doesThisDeclarationHaveABody() && !Policy.TerseOutput) {
597 if (!D->hasPrototype() && D->getNumParams()) {
598 // This is a K&R function definition, so we need to print the
601 DeclPrinter ParamPrinter(Out, SubPolicy, Indentation);
602 Indentation += Policy.Indentation;
603 for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
605 ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
608 Indentation -= Policy.Indentation;
613 D->getBody()->printPretty(Out, nullptr, SubPolicy, Indentation);
618 void DeclPrinter::VisitFriendDecl(FriendDecl *D) {
619 if (TypeSourceInfo *TSI = D->getFriendType()) {
620 unsigned NumTPLists = D->getFriendTypeNumTemplateParameterLists();
621 for (unsigned i = 0; i < NumTPLists; ++i)
622 PrintTemplateParameters(D->getFriendTypeTemplateParameterList(i));
624 Out << " " << TSI->getType().getAsString(Policy);
626 else if (FunctionDecl *FD =
627 dyn_cast<FunctionDecl>(D->getFriendDecl())) {
629 VisitFunctionDecl(FD);
631 else if (FunctionTemplateDecl *FTD =
632 dyn_cast<FunctionTemplateDecl>(D->getFriendDecl())) {
634 VisitFunctionTemplateDecl(FTD);
636 else if (ClassTemplateDecl *CTD =
637 dyn_cast<ClassTemplateDecl>(D->getFriendDecl())) {
639 VisitRedeclarableTemplateDecl(CTD);
643 void DeclPrinter::VisitFieldDecl(FieldDecl *D) {
644 if (!Policy.SuppressSpecifiers && D->isMutable())
646 if (!Policy.SuppressSpecifiers && D->isModulePrivate())
647 Out << "__module_private__ ";
649 Out << D->getASTContext().getUnqualifiedObjCPointerType(D->getType()).
650 stream(Policy, D->getName());
652 if (D->isBitField()) {
654 D->getBitWidth()->printPretty(Out, nullptr, Policy, Indentation);
657 Expr *Init = D->getInClassInitializer();
658 if (!Policy.SuppressInitializers && Init) {
659 if (D->getInClassInitStyle() == ICIS_ListInit)
663 Init->printPretty(Out, nullptr, Policy, Indentation);
665 prettyPrintAttributes(D);
668 void DeclPrinter::VisitLabelDecl(LabelDecl *D) {
672 void DeclPrinter::VisitVarDecl(VarDecl *D) {
673 if (!Policy.SuppressSpecifiers) {
674 StorageClass SC = D->getStorageClass();
676 Out << VarDecl::getStorageClassSpecifierString(SC) << " ";
678 switch (D->getTSCSpec()) {
679 case TSCS_unspecified:
684 case TSCS__Thread_local:
685 Out << "_Thread_local ";
687 case TSCS_thread_local:
688 Out << "thread_local ";
692 if (D->isModulePrivate())
693 Out << "__module_private__ ";
696 QualType T = D->getTypeSourceInfo()
697 ? D->getTypeSourceInfo()->getType()
698 : D->getASTContext().getUnqualifiedObjCPointerType(D->getType());
699 printDeclType(T, D->getName());
700 Expr *Init = D->getInit();
701 if (!Policy.SuppressInitializers && Init) {
702 bool ImplicitInit = false;
703 if (CXXConstructExpr *Construct =
704 dyn_cast<CXXConstructExpr>(Init->IgnoreImplicit())) {
705 if (D->getInitStyle() == VarDecl::CallInit &&
706 !Construct->isListInitialization()) {
707 ImplicitInit = Construct->getNumArgs() == 0 ||
708 Construct->getArg(0)->isDefaultArgument();
712 if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
714 else if (D->getInitStyle() == VarDecl::CInit) {
717 Init->printPretty(Out, nullptr, Policy, Indentation);
718 if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
722 prettyPrintAttributes(D);
725 void DeclPrinter::VisitParmVarDecl(ParmVarDecl *D) {
729 void DeclPrinter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) {
731 D->getAsmString()->printPretty(Out, nullptr, Policy, Indentation);
735 void DeclPrinter::VisitImportDecl(ImportDecl *D) {
736 Out << "@import " << D->getImportedModule()->getFullModuleName()
740 void DeclPrinter::VisitStaticAssertDecl(StaticAssertDecl *D) {
741 Out << "static_assert(";
742 D->getAssertExpr()->printPretty(Out, nullptr, Policy, Indentation);
743 if (StringLiteral *SL = D->getMessage()) {
745 SL->printPretty(Out, nullptr, Policy, Indentation);
750 //----------------------------------------------------------------------------
752 //----------------------------------------------------------------------------
753 void DeclPrinter::VisitNamespaceDecl(NamespaceDecl *D) {
756 Out << "namespace " << *D << " {\n";
761 void DeclPrinter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
762 Out << "using namespace ";
763 if (D->getQualifier())
764 D->getQualifier()->print(Out, Policy);
765 Out << *D->getNominatedNamespaceAsWritten();
768 void DeclPrinter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
769 Out << "namespace " << *D << " = ";
770 if (D->getQualifier())
771 D->getQualifier()->print(Out, Policy);
772 Out << *D->getAliasedNamespace();
775 void DeclPrinter::VisitEmptyDecl(EmptyDecl *D) {
776 prettyPrintAttributes(D);
779 void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) {
780 if (!Policy.SuppressSpecifiers && D->isModulePrivate())
781 Out << "__module_private__ ";
782 Out << D->getKindName();
784 prettyPrintAttributes(D);
786 if (D->getIdentifier())
789 if (D->isCompleteDefinition()) {
790 // Print the base classes
791 if (D->getNumBases()) {
793 for (CXXRecordDecl::base_class_iterator Base = D->bases_begin(),
794 BaseEnd = D->bases_end(); Base != BaseEnd; ++Base) {
795 if (Base != D->bases_begin())
798 if (Base->isVirtual())
801 AccessSpecifier AS = Base->getAccessSpecifierAsWritten();
806 Out << Base->getType().getAsString(Policy);
808 if (Base->isPackExpansion())
813 // Print the class definition
814 // FIXME: Doesn't print access specifiers, e.g., "public:"
821 void DeclPrinter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
823 if (D->getLanguage() == LinkageSpecDecl::lang_c)
826 assert(D->getLanguage() == LinkageSpecDecl::lang_cxx &&
827 "unknown language in linkage specification");
831 Out << "extern \"" << l << "\" ";
832 if (D->hasBraces()) {
837 Visit(*D->decls_begin());
840 void DeclPrinter::PrintTemplateParameters(const TemplateParameterList *Params,
841 const TemplateArgumentList *Args) {
843 assert(!Args || Params->size() == Args->size());
847 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
851 const Decl *Param = Params->getParam(i);
852 if (const TemplateTypeParmDecl *TTP =
853 dyn_cast<TemplateTypeParmDecl>(Param)) {
855 if (TTP->wasDeclaredWithTypename())
860 if (TTP->isParameterPack())
867 Args->get(i).print(Policy, Out);
868 } else if (TTP->hasDefaultArgument()) {
870 Out << TTP->getDefaultArgument().getAsString(Policy);
872 } else if (const NonTypeTemplateParmDecl *NTTP =
873 dyn_cast<NonTypeTemplateParmDecl>(Param)) {
875 if (IdentifierInfo *II = NTTP->getIdentifier())
876 Name = II->getName();
877 printDeclType(NTTP->getType(), Name, NTTP->isParameterPack());
881 Args->get(i).print(Policy, Out);
882 } else if (NTTP->hasDefaultArgument()) {
884 NTTP->getDefaultArgument()->printPretty(Out, nullptr, Policy,
887 } else if (const TemplateTemplateParmDecl *TTPD =
888 dyn_cast<TemplateTemplateParmDecl>(Param)) {
889 VisitTemplateDecl(TTPD);
890 // FIXME: print the default argument, if present.
897 void DeclPrinter::VisitTemplateDecl(const TemplateDecl *D) {
898 PrintTemplateParameters(D->getTemplateParameters());
900 if (const TemplateTemplateParmDecl *TTP =
901 dyn_cast<TemplateTemplateParmDecl>(D)) {
903 if (TTP->isParameterPack())
907 Visit(D->getTemplatedDecl());
911 void DeclPrinter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
912 if (PrintInstantiation) {
913 TemplateParameterList *Params = D->getTemplateParameters();
914 for (auto *I : D->specializations()) {
915 PrintTemplateParameters(Params, I->getTemplateSpecializationArgs());
920 return VisitRedeclarableTemplateDecl(D);
923 void DeclPrinter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
924 if (PrintInstantiation) {
925 TemplateParameterList *Params = D->getTemplateParameters();
926 for (auto *I : D->specializations()) {
927 PrintTemplateParameters(Params, &I->getTemplateArgs());
933 return VisitRedeclarableTemplateDecl(D);
936 //----------------------------------------------------------------------------
937 // Objective-C declarations
938 //----------------------------------------------------------------------------
940 void DeclPrinter::PrintObjCMethodType(ASTContext &Ctx,
941 Decl::ObjCDeclQualifier Quals,
944 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_In)
946 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Inout)
948 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Out)
950 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Bycopy)
952 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Byref)
954 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Oneway)
956 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_CSNullability) {
957 if (auto nullability = AttributedType::stripOuterNullability(T))
958 Out << getNullabilitySpelling(*nullability, true) << ' ';
961 Out << Ctx.getUnqualifiedObjCPointerType(T).getAsString(Policy);
965 void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) {
966 if (OMD->isInstanceMethod())
970 if (!OMD->getReturnType().isNull()) {
971 PrintObjCMethodType(OMD->getASTContext(), OMD->getObjCDeclQualifier(),
972 OMD->getReturnType());
975 std::string name = OMD->getSelector().getAsString();
976 std::string::size_type pos, lastPos = 0;
977 for (const auto *PI : OMD->params()) {
978 // FIXME: selector is missing here!
979 pos = name.find_first_of(':', lastPos);
980 Out << " " << name.substr(lastPos, pos - lastPos) << ':';
981 PrintObjCMethodType(OMD->getASTContext(),
982 PI->getObjCDeclQualifier(),
988 if (OMD->param_begin() == OMD->param_end())
991 if (OMD->isVariadic())
994 prettyPrintAttributes(OMD);
996 if (OMD->getBody() && !Policy.TerseOutput) {
998 OMD->getBody()->printPretty(Out, nullptr, Policy);
1000 else if (Policy.PolishForDeclaration)
1004 void DeclPrinter::VisitObjCImplementationDecl(ObjCImplementationDecl *OID) {
1005 std::string I = OID->getNameAsString();
1006 ObjCInterfaceDecl *SID = OID->getSuperClass();
1008 bool eolnOut = false;
1010 Out << "@implementation " << I << " : " << *SID;
1012 Out << "@implementation " << I;
1014 if (OID->ivar_size() > 0) {
1017 Indentation += Policy.Indentation;
1018 for (const auto *I : OID->ivars()) {
1019 Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).
1020 getAsString(Policy) << ' ' << *I << ";\n";
1022 Indentation -= Policy.Indentation;
1025 else if (SID || (OID->decls_begin() != OID->decls_end())) {
1029 VisitDeclContext(OID, false);
1035 void DeclPrinter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *OID) {
1036 std::string I = OID->getNameAsString();
1037 ObjCInterfaceDecl *SID = OID->getSuperClass();
1039 if (!OID->isThisDeclarationADefinition()) {
1040 Out << "@class " << I << ";";
1043 bool eolnOut = false;
1045 Out << "@interface " << I << " : " << *SID;
1047 Out << "@interface " << I;
1050 const ObjCList<ObjCProtocolDecl> &Protocols = OID->getReferencedProtocols();
1051 if (!Protocols.empty()) {
1052 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1053 E = Protocols.end(); I != E; ++I)
1054 Out << (I == Protocols.begin() ? '<' : ',') << **I;
1058 if (OID->ivar_size() > 0) {
1061 Indentation += Policy.Indentation;
1062 for (const auto *I : OID->ivars()) {
1063 Indent() << I->getASTContext()
1064 .getUnqualifiedObjCPointerType(I->getType())
1065 .getAsString(Policy) << ' ' << *I << ";\n";
1067 Indentation -= Policy.Indentation;
1070 else if (SID || (OID->decls_begin() != OID->decls_end())) {
1075 VisitDeclContext(OID, false);
1079 // FIXME: implement the rest...
1082 void DeclPrinter::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1083 if (!PID->isThisDeclarationADefinition()) {
1084 Out << "@protocol " << *PID << ";\n";
1088 const ObjCList<ObjCProtocolDecl> &Protocols = PID->getReferencedProtocols();
1089 if (!Protocols.empty()) {
1090 Out << "@protocol " << *PID;
1091 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1092 E = Protocols.end(); I != E; ++I)
1093 Out << (I == Protocols.begin() ? '<' : ',') << **I;
1096 Out << "@protocol " << *PID << '\n';
1097 VisitDeclContext(PID, false);
1101 void DeclPrinter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *PID) {
1102 Out << "@implementation " << *PID->getClassInterface() << '(' << *PID <<")\n";
1104 VisitDeclContext(PID, false);
1106 // FIXME: implement the rest...
1109 void DeclPrinter::VisitObjCCategoryDecl(ObjCCategoryDecl *PID) {
1110 Out << "@interface " << *PID->getClassInterface() << '(' << *PID << ")\n";
1111 if (PID->ivar_size() > 0) {
1113 Indentation += Policy.Indentation;
1114 for (const auto *I : PID->ivars())
1115 Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).
1116 getAsString(Policy) << ' ' << *I << ";\n";
1117 Indentation -= Policy.Indentation;
1121 VisitDeclContext(PID, false);
1124 // FIXME: implement the rest...
1127 void DeclPrinter::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *AID) {
1128 Out << "@compatibility_alias " << *AID
1129 << ' ' << *AID->getClassInterface() << ";\n";
1132 /// PrintObjCPropertyDecl - print a property declaration.
1134 void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) {
1135 if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Required)
1136 Out << "@required\n";
1137 else if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Optional)
1138 Out << "@optional\n";
1140 QualType T = PDecl->getType();
1143 if (PDecl->getPropertyAttributes() != ObjCPropertyDecl::OBJC_PR_noattr) {
1146 if (PDecl->getPropertyAttributes() &
1147 ObjCPropertyDecl::OBJC_PR_readonly) {
1148 Out << (first ? ' ' : ',') << "readonly";
1152 if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
1153 Out << (first ? ' ' : ',') << "getter = ";
1154 PDecl->getGetterName().print(Out);
1157 if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
1158 Out << (first ? ' ' : ',') << "setter = ";
1159 PDecl->getSetterName().print(Out);
1163 if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_assign) {
1164 Out << (first ? ' ' : ',') << "assign";
1168 if (PDecl->getPropertyAttributes() &
1169 ObjCPropertyDecl::OBJC_PR_readwrite) {
1170 Out << (first ? ' ' : ',') << "readwrite";
1174 if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain) {
1175 Out << (first ? ' ' : ',') << "retain";
1179 if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_strong) {
1180 Out << (first ? ' ' : ',') << "strong";
1184 if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy) {
1185 Out << (first ? ' ' : ',') << "copy";
1189 if (PDecl->getPropertyAttributes() &
1190 ObjCPropertyDecl::OBJC_PR_nonatomic) {
1191 Out << (first ? ' ' : ',') << "nonatomic";
1194 if (PDecl->getPropertyAttributes() &
1195 ObjCPropertyDecl::OBJC_PR_atomic) {
1196 Out << (first ? ' ' : ',') << "atomic";
1200 if (PDecl->getPropertyAttributes() &
1201 ObjCPropertyDecl::OBJC_PR_nullability) {
1202 if (auto nullability = AttributedType::stripOuterNullability(T)) {
1203 if (*nullability == NullabilityKind::Unspecified &&
1204 (PDecl->getPropertyAttributes() &
1205 ObjCPropertyDecl::OBJC_PR_null_resettable)) {
1206 Out << (first ? ' ' : ',') << "null_resettable";
1208 Out << (first ? ' ' : ',')
1209 << getNullabilitySpelling(*nullability, true);
1215 (void) first; // Silence dead store warning due to idiomatic code.
1218 Out << ' ' << PDecl->getASTContext().getUnqualifiedObjCPointerType(T).
1219 getAsString(Policy) << ' ' << *PDecl;
1220 if (Policy.PolishForDeclaration)
1224 void DeclPrinter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PID) {
1225 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize)
1226 Out << "@synthesize ";
1229 Out << *PID->getPropertyDecl();
1230 if (PID->getPropertyIvarDecl())
1231 Out << '=' << *PID->getPropertyIvarDecl();
1234 void DeclPrinter::VisitUsingDecl(UsingDecl *D) {
1235 if (!D->isAccessDeclaration())
1237 if (D->hasTypename())
1239 D->getQualifier()->print(Out, Policy);
1244 DeclPrinter::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
1245 Out << "using typename ";
1246 D->getQualifier()->print(Out, Policy);
1247 Out << D->getDeclName();
1250 void DeclPrinter::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1251 if (!D->isAccessDeclaration())
1253 D->getQualifier()->print(Out, Policy);
1254 Out << D->getName();
1257 void DeclPrinter::VisitUsingShadowDecl(UsingShadowDecl *D) {
1261 void DeclPrinter::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
1262 Out << "#pragma omp threadprivate";
1263 if (!D->varlist_empty()) {
1264 for (OMPThreadPrivateDecl::varlist_iterator I = D->varlist_begin(),
1265 E = D->varlist_end();
1267 Out << (I == D->varlist_begin() ? '(' : ',');
1268 NamedDecl *ND = cast<NamedDecl>(cast<DeclRefExpr>(*I)->getDecl());
1269 ND->printQualifiedName(Out);