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