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