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