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   } else {
744     Ty.print(Out, Policy, Proto);
745   }
746 
747   prettyPrintAttributes(D);
748 
749   if (D->isPure())
750     Out << " = 0";
751   else if (D->isDeletedAsWritten())
752     Out << " = delete";
753   else if (D->isExplicitlyDefaulted())
754     Out << " = default";
755   else if (D->doesThisDeclarationHaveABody()) {
756     if (!Policy.TerseOutput) {
757       if (!D->hasPrototype() && D->getNumParams()) {
758         // This is a K&R function definition, so we need to print the
759         // parameters.
760         Out << '\n';
761         DeclPrinter ParamPrinter(Out, SubPolicy, Context, Indentation);
762         Indentation += Policy.Indentation;
763         for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
764           Indent();
765           ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
766           Out << ";\n";
767         }
768         Indentation -= Policy.Indentation;
769       } else
770         Out << ' ';
771 
772       if (D->getBody())
773         D->getBody()->printPretty(Out, nullptr, SubPolicy, Indentation);
774     } else {
775       if (!Policy.TerseOutput && isa<CXXConstructorDecl>(*D))
776         Out << " {}";
777     }
778   }
779 }
780 
781 void DeclPrinter::VisitFriendDecl(FriendDecl *D) {
782   if (TypeSourceInfo *TSI = D->getFriendType()) {
783     unsigned NumTPLists = D->getFriendTypeNumTemplateParameterLists();
784     for (unsigned i = 0; i < NumTPLists; ++i)
785       printTemplateParameters(D->getFriendTypeTemplateParameterList(i));
786     Out << "friend ";
787     Out << " " << TSI->getType().getAsString(Policy);
788   }
789   else if (FunctionDecl *FD =
790       dyn_cast<FunctionDecl>(D->getFriendDecl())) {
791     Out << "friend ";
792     VisitFunctionDecl(FD);
793   }
794   else if (FunctionTemplateDecl *FTD =
795            dyn_cast<FunctionTemplateDecl>(D->getFriendDecl())) {
796     Out << "friend ";
797     VisitFunctionTemplateDecl(FTD);
798   }
799   else if (ClassTemplateDecl *CTD =
800            dyn_cast<ClassTemplateDecl>(D->getFriendDecl())) {
801     Out << "friend ";
802     VisitRedeclarableTemplateDecl(CTD);
803   }
804 }
805 
806 void DeclPrinter::VisitFieldDecl(FieldDecl *D) {
807   // FIXME: add printing of pragma attributes if required.
808   if (!Policy.SuppressSpecifiers && D->isMutable())
809     Out << "mutable ";
810   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
811     Out << "__module_private__ ";
812 
813   Out << D->getASTContext().getUnqualifiedObjCPointerType(D->getType()).
814          stream(Policy, D->getName(), Indentation);
815 
816   if (D->isBitField()) {
817     Out << " : ";
818     D->getBitWidth()->printPretty(Out, nullptr, Policy, Indentation);
819   }
820 
821   Expr *Init = D->getInClassInitializer();
822   if (!Policy.SuppressInitializers && Init) {
823     if (D->getInClassInitStyle() == ICIS_ListInit)
824       Out << " ";
825     else
826       Out << " = ";
827     Init->printPretty(Out, nullptr, Policy, Indentation);
828   }
829   prettyPrintAttributes(D);
830 }
831 
832 void DeclPrinter::VisitLabelDecl(LabelDecl *D) {
833   Out << *D << ":";
834 }
835 
836 void DeclPrinter::VisitVarDecl(VarDecl *D) {
837   prettyPrintPragmas(D);
838 
839   QualType T = D->getTypeSourceInfo()
840     ? D->getTypeSourceInfo()->getType()
841     : D->getASTContext().getUnqualifiedObjCPointerType(D->getType());
842 
843   if (!Policy.SuppressSpecifiers) {
844     StorageClass SC = D->getStorageClass();
845     if (SC != SC_None)
846       Out << VarDecl::getStorageClassSpecifierString(SC) << " ";
847 
848     switch (D->getTSCSpec()) {
849     case TSCS_unspecified:
850       break;
851     case TSCS___thread:
852       Out << "__thread ";
853       break;
854     case TSCS__Thread_local:
855       Out << "_Thread_local ";
856       break;
857     case TSCS_thread_local:
858       Out << "thread_local ";
859       break;
860     }
861 
862     if (D->isModulePrivate())
863       Out << "__module_private__ ";
864 
865     if (D->isConstexpr()) {
866       Out << "constexpr ";
867       T.removeLocalConst();
868     }
869   }
870 
871   printDeclType(T, D->getName());
872   Expr *Init = D->getInit();
873   if (!Policy.SuppressInitializers && Init) {
874     bool ImplicitInit = false;
875     if (CXXConstructExpr *Construct =
876             dyn_cast<CXXConstructExpr>(Init->IgnoreImplicit())) {
877       if (D->getInitStyle() == VarDecl::CallInit &&
878           !Construct->isListInitialization()) {
879         ImplicitInit = Construct->getNumArgs() == 0 ||
880           Construct->getArg(0)->isDefaultArgument();
881       }
882     }
883     if (!ImplicitInit) {
884       if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
885         Out << "(";
886       else if (D->getInitStyle() == VarDecl::CInit) {
887         Out << " = ";
888       }
889       PrintingPolicy SubPolicy(Policy);
890       SubPolicy.SuppressSpecifiers = false;
891       SubPolicy.IncludeTagDefinition = false;
892       Init->printPretty(Out, nullptr, SubPolicy, Indentation);
893       if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
894         Out << ")";
895     }
896   }
897   prettyPrintAttributes(D);
898 }
899 
900 void DeclPrinter::VisitParmVarDecl(ParmVarDecl *D) {
901   VisitVarDecl(D);
902 }
903 
904 void DeclPrinter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) {
905   Out << "__asm (";
906   D->getAsmString()->printPretty(Out, nullptr, Policy, Indentation);
907   Out << ")";
908 }
909 
910 void DeclPrinter::VisitImportDecl(ImportDecl *D) {
911   Out << "@import " << D->getImportedModule()->getFullModuleName()
912       << ";\n";
913 }
914 
915 void DeclPrinter::VisitStaticAssertDecl(StaticAssertDecl *D) {
916   Out << "static_assert(";
917   D->getAssertExpr()->printPretty(Out, nullptr, Policy, Indentation);
918   if (StringLiteral *SL = D->getMessage()) {
919     Out << ", ";
920     SL->printPretty(Out, nullptr, Policy, Indentation);
921   }
922   Out << ")";
923 }
924 
925 //----------------------------------------------------------------------------
926 // C++ declarations
927 //----------------------------------------------------------------------------
928 void DeclPrinter::VisitNamespaceDecl(NamespaceDecl *D) {
929   if (D->isInline())
930     Out << "inline ";
931   Out << "namespace " << *D << " {\n";
932   VisitDeclContext(D);
933   Indent() << "}";
934 }
935 
936 void DeclPrinter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
937   Out << "using namespace ";
938   if (D->getQualifier())
939     D->getQualifier()->print(Out, Policy);
940   Out << *D->getNominatedNamespaceAsWritten();
941 }
942 
943 void DeclPrinter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
944   Out << "namespace " << *D << " = ";
945   if (D->getQualifier())
946     D->getQualifier()->print(Out, Policy);
947   Out << *D->getAliasedNamespace();
948 }
949 
950 void DeclPrinter::VisitEmptyDecl(EmptyDecl *D) {
951   prettyPrintAttributes(D);
952 }
953 
954 void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) {
955   // FIXME: add printing of pragma attributes if required.
956   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
957     Out << "__module_private__ ";
958   Out << D->getKindName();
959 
960   prettyPrintAttributes(D);
961 
962   if (D->getIdentifier()) {
963     Out << ' ' << *D;
964 
965     if (auto S = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
966       ArrayRef<TemplateArgument> Args = S->getTemplateArgs().asArray();
967       if (!Policy.PrintCanonicalTypes)
968         if (const auto* TSI = S->getTypeAsWritten())
969           if (const auto *TST =
970                   dyn_cast<TemplateSpecializationType>(TSI->getType()))
971             Args = TST->template_arguments();
972       printTemplateArguments(Args);
973     }
974   }
975 
976   if (D->isCompleteDefinition()) {
977     // Print the base classes
978     if (D->getNumBases()) {
979       Out << " : ";
980       for (CXXRecordDecl::base_class_iterator Base = D->bases_begin(),
981              BaseEnd = D->bases_end(); Base != BaseEnd; ++Base) {
982         if (Base != D->bases_begin())
983           Out << ", ";
984 
985         if (Base->isVirtual())
986           Out << "virtual ";
987 
988         AccessSpecifier AS = Base->getAccessSpecifierAsWritten();
989         if (AS != AS_none) {
990           Print(AS);
991           Out << " ";
992         }
993         Out << Base->getType().getAsString(Policy);
994 
995         if (Base->isPackExpansion())
996           Out << "...";
997       }
998     }
999 
1000     // Print the class definition
1001     // FIXME: Doesn't print access specifiers, e.g., "public:"
1002     if (Policy.TerseOutput) {
1003       Out << " {}";
1004     } else {
1005       Out << " {\n";
1006       VisitDeclContext(D);
1007       Indent() << "}";
1008     }
1009   }
1010 }
1011 
1012 void DeclPrinter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1013   const char *l;
1014   if (D->getLanguage() == LinkageSpecDecl::lang_c)
1015     l = "C";
1016   else {
1017     assert(D->getLanguage() == LinkageSpecDecl::lang_cxx &&
1018            "unknown language in linkage specification");
1019     l = "C++";
1020   }
1021 
1022   Out << "extern \"" << l << "\" ";
1023   if (D->hasBraces()) {
1024     Out << "{\n";
1025     VisitDeclContext(D);
1026     Indent() << "}";
1027   } else
1028     Visit(*D->decls_begin());
1029 }
1030 
1031 void DeclPrinter::printTemplateParameters(const TemplateParameterList *Params,
1032                                           bool OmitTemplateKW) {
1033   assert(Params);
1034 
1035   if (!OmitTemplateKW)
1036     Out << "template ";
1037   Out << '<';
1038 
1039   bool NeedComma = false;
1040   for (const Decl *Param : *Params) {
1041     if (Param->isImplicit())
1042       continue;
1043 
1044     if (NeedComma)
1045       Out << ", ";
1046     else
1047       NeedComma = true;
1048 
1049     if (auto TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
1050 
1051       if (TTP->wasDeclaredWithTypename())
1052         Out << "typename";
1053       else
1054         Out << "class";
1055 
1056       if (TTP->isParameterPack())
1057         Out << " ...";
1058       else if (!TTP->getName().empty())
1059         Out << ' ';
1060 
1061       Out << *TTP;
1062 
1063       if (TTP->hasDefaultArgument()) {
1064         Out << " = ";
1065         Out << TTP->getDefaultArgument().getAsString(Policy);
1066       };
1067     } else if (auto NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1068       StringRef Name;
1069       if (IdentifierInfo *II = NTTP->getIdentifier())
1070         Name = II->getName();
1071       printDeclType(NTTP->getType(), Name, NTTP->isParameterPack());
1072 
1073       if (NTTP->hasDefaultArgument()) {
1074         Out << " = ";
1075         NTTP->getDefaultArgument()->printPretty(Out, nullptr, Policy,
1076                                                 Indentation);
1077       }
1078     } else if (auto TTPD = dyn_cast<TemplateTemplateParmDecl>(Param)) {
1079       VisitTemplateDecl(TTPD);
1080       // FIXME: print the default argument, if present.
1081     }
1082   }
1083 
1084   Out << '>';
1085   if (!OmitTemplateKW)
1086     Out << ' ';
1087 }
1088 
1089 void DeclPrinter::printTemplateArguments(ArrayRef<TemplateArgument> Args) {
1090   Out << "<";
1091   for (size_t I = 0, E = Args.size(); I < E; ++I) {
1092     if (I)
1093       Out << ", ";
1094     Args[I].print(Policy, Out);
1095   }
1096   Out << ">";
1097 }
1098 
1099 void DeclPrinter::printTemplateArguments(ArrayRef<TemplateArgumentLoc> Args) {
1100   Out << "<";
1101   for (size_t I = 0, E = Args.size(); I < E; ++I) {
1102     if (I)
1103       Out << ", ";
1104     Args[I].getArgument().print(Policy, Out);
1105   }
1106   Out << ">";
1107 }
1108 
1109 void DeclPrinter::VisitTemplateDecl(const TemplateDecl *D) {
1110   printTemplateParameters(D->getTemplateParameters());
1111 
1112   if (const TemplateTemplateParmDecl *TTP =
1113         dyn_cast<TemplateTemplateParmDecl>(D)) {
1114     Out << "class ";
1115     if (TTP->isParameterPack())
1116       Out << "...";
1117     Out << D->getName();
1118   } else if (auto *TD = D->getTemplatedDecl())
1119     Visit(TD);
1120   else if (const auto *Concept = dyn_cast<ConceptDecl>(D)) {
1121     Out << "concept " << Concept->getName() << " = " ;
1122     Concept->getConstraintExpr()->printPretty(Out, nullptr, Policy,
1123                                               Indentation);
1124     Out << ";";
1125   }
1126 }
1127 
1128 void DeclPrinter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1129   prettyPrintPragmas(D->getTemplatedDecl());
1130   // Print any leading template parameter lists.
1131   if (const FunctionDecl *FD = D->getTemplatedDecl()) {
1132     for (unsigned I = 0, NumTemplateParams = FD->getNumTemplateParameterLists();
1133          I < NumTemplateParams; ++I)
1134       printTemplateParameters(FD->getTemplateParameterList(I));
1135   }
1136   VisitRedeclarableTemplateDecl(D);
1137   // Declare target attribute is special one, natural spelling for the pragma
1138   // assumes "ending" construct so print it here.
1139   if (D->getTemplatedDecl()->hasAttr<OMPDeclareTargetDeclAttr>())
1140     Out << "#pragma omp end declare target\n";
1141 
1142   // Never print "instantiations" for deduction guides (they don't really
1143   // have them).
1144   if (PrintInstantiation &&
1145       !isa<CXXDeductionGuideDecl>(D->getTemplatedDecl())) {
1146     FunctionDecl *PrevDecl = D->getTemplatedDecl();
1147     const FunctionDecl *Def;
1148     if (PrevDecl->isDefined(Def) && Def != PrevDecl)
1149       return;
1150     for (auto *I : D->specializations())
1151       if (I->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) {
1152         if (!PrevDecl->isThisDeclarationADefinition())
1153           Out << ";\n";
1154         Indent();
1155         prettyPrintPragmas(I);
1156         Visit(I);
1157       }
1158   }
1159 }
1160 
1161 void DeclPrinter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1162   VisitRedeclarableTemplateDecl(D);
1163 
1164   if (PrintInstantiation) {
1165     for (auto *I : D->specializations())
1166       if (I->getSpecializationKind() == TSK_ImplicitInstantiation) {
1167         if (D->isThisDeclarationADefinition())
1168           Out << ";";
1169         Out << "\n";
1170         Visit(I);
1171       }
1172   }
1173 }
1174 
1175 void DeclPrinter::VisitClassTemplateSpecializationDecl(
1176                                            ClassTemplateSpecializationDecl *D) {
1177   Out << "template<> ";
1178   VisitCXXRecordDecl(D);
1179 }
1180 
1181 void DeclPrinter::VisitClassTemplatePartialSpecializationDecl(
1182                                     ClassTemplatePartialSpecializationDecl *D) {
1183   printTemplateParameters(D->getTemplateParameters());
1184   VisitCXXRecordDecl(D);
1185 }
1186 
1187 //----------------------------------------------------------------------------
1188 // Objective-C declarations
1189 //----------------------------------------------------------------------------
1190 
1191 void DeclPrinter::PrintObjCMethodType(ASTContext &Ctx,
1192                                       Decl::ObjCDeclQualifier Quals,
1193                                       QualType T) {
1194   Out << '(';
1195   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_In)
1196     Out << "in ";
1197   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Inout)
1198     Out << "inout ";
1199   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Out)
1200     Out << "out ";
1201   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Bycopy)
1202     Out << "bycopy ";
1203   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Byref)
1204     Out << "byref ";
1205   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Oneway)
1206     Out << "oneway ";
1207   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_CSNullability) {
1208     if (auto nullability = AttributedType::stripOuterNullability(T))
1209       Out << getNullabilitySpelling(*nullability, true) << ' ';
1210   }
1211 
1212   Out << Ctx.getUnqualifiedObjCPointerType(T).getAsString(Policy);
1213   Out << ')';
1214 }
1215 
1216 void DeclPrinter::PrintObjCTypeParams(ObjCTypeParamList *Params) {
1217   Out << "<";
1218   unsigned First = true;
1219   for (auto *Param : *Params) {
1220     if (First) {
1221       First = false;
1222     } else {
1223       Out << ", ";
1224     }
1225 
1226     switch (Param->getVariance()) {
1227     case ObjCTypeParamVariance::Invariant:
1228       break;
1229 
1230     case ObjCTypeParamVariance::Covariant:
1231       Out << "__covariant ";
1232       break;
1233 
1234     case ObjCTypeParamVariance::Contravariant:
1235       Out << "__contravariant ";
1236       break;
1237     }
1238 
1239     Out << Param->getDeclName().getAsString();
1240 
1241     if (Param->hasExplicitBound()) {
1242       Out << " : " << Param->getUnderlyingType().getAsString(Policy);
1243     }
1244   }
1245   Out << ">";
1246 }
1247 
1248 void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) {
1249   if (OMD->isInstanceMethod())
1250     Out << "- ";
1251   else
1252     Out << "+ ";
1253   if (!OMD->getReturnType().isNull()) {
1254     PrintObjCMethodType(OMD->getASTContext(), OMD->getObjCDeclQualifier(),
1255                         OMD->getReturnType());
1256   }
1257 
1258   std::string name = OMD->getSelector().getAsString();
1259   std::string::size_type pos, lastPos = 0;
1260   for (const auto *PI : OMD->parameters()) {
1261     // FIXME: selector is missing here!
1262     pos = name.find_first_of(':', lastPos);
1263     if (lastPos != 0)
1264       Out << " ";
1265     Out << name.substr(lastPos, pos - lastPos) << ':';
1266     PrintObjCMethodType(OMD->getASTContext(),
1267                         PI->getObjCDeclQualifier(),
1268                         PI->getType());
1269     Out << *PI;
1270     lastPos = pos + 1;
1271   }
1272 
1273   if (OMD->param_begin() == OMD->param_end())
1274     Out << name;
1275 
1276   if (OMD->isVariadic())
1277       Out << ", ...";
1278 
1279   prettyPrintAttributes(OMD);
1280 
1281   if (OMD->getBody() && !Policy.TerseOutput) {
1282     Out << ' ';
1283     OMD->getBody()->printPretty(Out, nullptr, Policy);
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 " << *PID->getClassInterface() << '(' << *PID <<")\n";
1398 
1399   VisitDeclContext(PID, false);
1400   Out << "@end";
1401   // FIXME: implement the rest...
1402 }
1403 
1404 void DeclPrinter::VisitObjCCategoryDecl(ObjCCategoryDecl *PID) {
1405   Out << "@interface " << *PID->getClassInterface();
1406   if (auto TypeParams = PID->getTypeParamList()) {
1407     PrintObjCTypeParams(TypeParams);
1408   }
1409   Out << "(" << *PID << ")\n";
1410   if (PID->ivar_size() > 0) {
1411     Out << "{\n";
1412     Indentation += Policy.Indentation;
1413     for (const auto *I : PID->ivars())
1414       Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).
1415                     getAsString(Policy) << ' ' << *I << ";\n";
1416     Indentation -= Policy.Indentation;
1417     Out << "}\n";
1418   }
1419 
1420   VisitDeclContext(PID, false);
1421   Out << "@end";
1422 
1423   // FIXME: implement the rest...
1424 }
1425 
1426 void DeclPrinter::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *AID) {
1427   Out << "@compatibility_alias " << *AID
1428       << ' ' << *AID->getClassInterface() << ";\n";
1429 }
1430 
1431 /// PrintObjCPropertyDecl - print a property declaration.
1432 ///
1433 /// Print attributes in the following order:
1434 /// - class
1435 /// - nonatomic | atomic
1436 /// - assign | retain | strong | copy | weak | unsafe_unretained
1437 /// - readwrite | readonly
1438 /// - getter & setter
1439 /// - nullability
1440 void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) {
1441   if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Required)
1442     Out << "@required\n";
1443   else if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Optional)
1444     Out << "@optional\n";
1445 
1446   QualType T = PDecl->getType();
1447 
1448   Out << "@property";
1449   if (PDecl->getPropertyAttributes() != ObjCPropertyDecl::OBJC_PR_noattr) {
1450     bool first = true;
1451     Out << "(";
1452     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_class) {
1453       Out << (first ? "" : ", ") << "class";
1454       first = false;
1455     }
1456 
1457     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_direct) {
1458       Out << (first ? "" : ", ") << "direct";
1459       first = false;
1460     }
1461 
1462     if (PDecl->getPropertyAttributes() &
1463         ObjCPropertyDecl::OBJC_PR_nonatomic) {
1464       Out << (first ? "" : ", ") << "nonatomic";
1465       first = false;
1466     }
1467     if (PDecl->getPropertyAttributes() &
1468         ObjCPropertyDecl::OBJC_PR_atomic) {
1469       Out << (first ? "" : ", ") << "atomic";
1470       first = false;
1471     }
1472 
1473     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_assign) {
1474       Out << (first ? "" : ", ") << "assign";
1475       first = false;
1476     }
1477     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain) {
1478       Out << (first ? "" : ", ") << "retain";
1479       first = false;
1480     }
1481 
1482     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_strong) {
1483       Out << (first ? "" : ", ") << "strong";
1484       first = false;
1485     }
1486     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy) {
1487       Out << (first ? "" : ", ") << "copy";
1488       first = false;
1489     }
1490     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak) {
1491       Out << (first ? "" : ", ") << "weak";
1492       first = false;
1493     }
1494     if (PDecl->getPropertyAttributes()
1495         & ObjCPropertyDecl::OBJC_PR_unsafe_unretained) {
1496       Out << (first ? "" : ", ") << "unsafe_unretained";
1497       first = false;
1498     }
1499 
1500     if (PDecl->getPropertyAttributes() &
1501         ObjCPropertyDecl::OBJC_PR_readwrite) {
1502       Out << (first ? "" : ", ") << "readwrite";
1503       first = false;
1504     }
1505     if (PDecl->getPropertyAttributes() &
1506         ObjCPropertyDecl::OBJC_PR_readonly) {
1507       Out << (first ? "" : ", ") << "readonly";
1508       first = false;
1509     }
1510 
1511     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
1512       Out << (first ? "" : ", ") << "getter = ";
1513       PDecl->getGetterName().print(Out);
1514       first = false;
1515     }
1516     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
1517       Out << (first ? "" : ", ") << "setter = ";
1518       PDecl->getSetterName().print(Out);
1519       first = false;
1520     }
1521 
1522     if (PDecl->getPropertyAttributes() &
1523         ObjCPropertyDecl::OBJC_PR_nullability) {
1524       if (auto nullability = AttributedType::stripOuterNullability(T)) {
1525         if (*nullability == NullabilityKind::Unspecified &&
1526             (PDecl->getPropertyAttributes() &
1527                ObjCPropertyDecl::OBJC_PR_null_resettable)) {
1528           Out << (first ? "" : ", ") << "null_resettable";
1529         } else {
1530           Out << (first ? "" : ", ")
1531               << getNullabilitySpelling(*nullability, true);
1532         }
1533         first = false;
1534       }
1535     }
1536 
1537     (void) first; // Silence dead store warning due to idiomatic code.
1538     Out << ")";
1539   }
1540   std::string TypeStr = PDecl->getASTContext().getUnqualifiedObjCPointerType(T).
1541       getAsString(Policy);
1542   Out << ' ' << TypeStr;
1543   if (!StringRef(TypeStr).endswith("*"))
1544     Out << ' ';
1545   Out << *PDecl;
1546   if (Policy.PolishForDeclaration)
1547     Out << ';';
1548 }
1549 
1550 void DeclPrinter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PID) {
1551   if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize)
1552     Out << "@synthesize ";
1553   else
1554     Out << "@dynamic ";
1555   Out << *PID->getPropertyDecl();
1556   if (PID->getPropertyIvarDecl())
1557     Out << '=' << *PID->getPropertyIvarDecl();
1558 }
1559 
1560 void DeclPrinter::VisitUsingDecl(UsingDecl *D) {
1561   if (!D->isAccessDeclaration())
1562     Out << "using ";
1563   if (D->hasTypename())
1564     Out << "typename ";
1565   D->getQualifier()->print(Out, Policy);
1566 
1567   // Use the correct record name when the using declaration is used for
1568   // inheriting constructors.
1569   for (const auto *Shadow : D->shadows()) {
1570     if (const auto *ConstructorShadow =
1571             dyn_cast<ConstructorUsingShadowDecl>(Shadow)) {
1572       assert(Shadow->getDeclContext() == ConstructorShadow->getDeclContext());
1573       Out << *ConstructorShadow->getNominatedBaseClass();
1574       return;
1575     }
1576   }
1577   Out << *D;
1578 }
1579 
1580 void
1581 DeclPrinter::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
1582   Out << "using typename ";
1583   D->getQualifier()->print(Out, Policy);
1584   Out << D->getDeclName();
1585 }
1586 
1587 void DeclPrinter::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1588   if (!D->isAccessDeclaration())
1589     Out << "using ";
1590   D->getQualifier()->print(Out, Policy);
1591   Out << D->getDeclName();
1592 }
1593 
1594 void DeclPrinter::VisitUsingShadowDecl(UsingShadowDecl *D) {
1595   // ignore
1596 }
1597 
1598 void DeclPrinter::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
1599   Out << "#pragma omp threadprivate";
1600   if (!D->varlist_empty()) {
1601     for (OMPThreadPrivateDecl::varlist_iterator I = D->varlist_begin(),
1602                                                 E = D->varlist_end();
1603                                                 I != E; ++I) {
1604       Out << (I == D->varlist_begin() ? '(' : ',');
1605       NamedDecl *ND = cast<DeclRefExpr>(*I)->getDecl();
1606       ND->printQualifiedName(Out);
1607     }
1608     Out << ")";
1609   }
1610 }
1611 
1612 void DeclPrinter::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
1613   Out << "#pragma omp allocate";
1614   if (!D->varlist_empty()) {
1615     for (OMPAllocateDecl::varlist_iterator I = D->varlist_begin(),
1616                                            E = D->varlist_end();
1617          I != E; ++I) {
1618       Out << (I == D->varlist_begin() ? '(' : ',');
1619       NamedDecl *ND = cast<DeclRefExpr>(*I)->getDecl();
1620       ND->printQualifiedName(Out);
1621     }
1622     Out << ")";
1623   }
1624   if (!D->clauselist_empty()) {
1625     Out << " ";
1626     OMPClausePrinter Printer(Out, Policy);
1627     for (OMPClause *C : D->clauselists())
1628       Printer.Visit(C);
1629   }
1630 }
1631 
1632 void DeclPrinter::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
1633   Out << "#pragma omp requires ";
1634   if (!D->clauselist_empty()) {
1635     OMPClausePrinter Printer(Out, Policy);
1636     for (auto I = D->clauselist_begin(), E = D->clauselist_end(); I != E; ++I)
1637       Printer.Visit(*I);
1638   }
1639 }
1640 
1641 void DeclPrinter::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
1642   if (!D->isInvalidDecl()) {
1643     Out << "#pragma omp declare reduction (";
1644     if (D->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) {
1645       const char *OpName =
1646           getOperatorSpelling(D->getDeclName().getCXXOverloadedOperator());
1647       assert(OpName && "not an overloaded operator");
1648       Out << OpName;
1649     } else {
1650       assert(D->getDeclName().isIdentifier());
1651       D->printName(Out);
1652     }
1653     Out << " : ";
1654     D->getType().print(Out, Policy);
1655     Out << " : ";
1656     D->getCombiner()->printPretty(Out, nullptr, Policy, 0);
1657     Out << ")";
1658     if (auto *Init = D->getInitializer()) {
1659       Out << " initializer(";
1660       switch (D->getInitializerKind()) {
1661       case OMPDeclareReductionDecl::DirectInit:
1662         Out << "omp_priv(";
1663         break;
1664       case OMPDeclareReductionDecl::CopyInit:
1665         Out << "omp_priv = ";
1666         break;
1667       case OMPDeclareReductionDecl::CallInit:
1668         break;
1669       }
1670       Init->printPretty(Out, nullptr, Policy, 0);
1671       if (D->getInitializerKind() == OMPDeclareReductionDecl::DirectInit)
1672         Out << ")";
1673       Out << ")";
1674     }
1675   }
1676 }
1677 
1678 void DeclPrinter::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
1679   if (!D->isInvalidDecl()) {
1680     Out << "#pragma omp declare mapper (";
1681     D->printName(Out);
1682     Out << " : ";
1683     D->getType().print(Out, Policy);
1684     Out << " ";
1685     Out << D->getVarName();
1686     Out << ")";
1687     if (!D->clauselist_empty()) {
1688       OMPClausePrinter Printer(Out, Policy);
1689       for (auto *C : D->clauselists()) {
1690         Out << " ";
1691         Printer.Visit(C);
1692       }
1693     }
1694   }
1695 }
1696 
1697 void DeclPrinter::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
1698   D->getInit()->printPretty(Out, nullptr, Policy, Indentation);
1699 }
1700 
1701