xref: /freebsd/contrib/llvm-project/clang/lib/AST/DeclPrinter.cpp (revision 4824e7fd18a1223177218d4aec1b3c6c5c4a444e)
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 << EOut.str();
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       }
684     } else if (D->doesThisDeclarationHaveABody() && !D->hasPrototype()) {
685       for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
686         if (i)
687           Proto += ", ";
688         Proto += D->getParamDecl(i)->getNameAsString();
689       }
690     }
691 
692     Proto += ")";
693 
694     if (FT) {
695       if (FT->isConst())
696         Proto += " const";
697       if (FT->isVolatile())
698         Proto += " volatile";
699       if (FT->isRestrict())
700         Proto += " restrict";
701 
702       switch (FT->getRefQualifier()) {
703       case RQ_None:
704         break;
705       case RQ_LValue:
706         Proto += " &";
707         break;
708       case RQ_RValue:
709         Proto += " &&";
710         break;
711       }
712     }
713 
714     if (FT && FT->hasDynamicExceptionSpec()) {
715       Proto += " throw(";
716       if (FT->getExceptionSpecType() == EST_MSAny)
717         Proto += "...";
718       else
719         for (unsigned I = 0, N = FT->getNumExceptions(); I != N; ++I) {
720           if (I)
721             Proto += ", ";
722 
723           Proto += FT->getExceptionType(I).getAsString(SubPolicy);
724         }
725       Proto += ")";
726     } else if (FT && isNoexceptExceptionSpec(FT->getExceptionSpecType())) {
727       Proto += " noexcept";
728       if (isComputedNoexcept(FT->getExceptionSpecType())) {
729         Proto += "(";
730         llvm::raw_string_ostream EOut(Proto);
731         FT->getNoexceptExpr()->printPretty(EOut, nullptr, SubPolicy,
732                                            Indentation, "\n", &Context);
733         EOut.flush();
734         Proto += EOut.str();
735         Proto += ")";
736       }
737     }
738 
739     if (CDecl) {
740       if (!Policy.TerseOutput)
741         PrintConstructorInitializers(CDecl, Proto);
742     } else if (!ConversionDecl && !isa<CXXDestructorDecl>(D)) {
743       if (FT && FT->hasTrailingReturn()) {
744         if (!GuideDecl)
745           Out << "auto ";
746         Out << Proto << " -> ";
747         Proto.clear();
748       }
749       AFT->getReturnType().print(Out, Policy, Proto);
750       Proto.clear();
751     }
752     Out << Proto;
753 
754     if (Expr *TrailingRequiresClause = D->getTrailingRequiresClause()) {
755       Out << " requires ";
756       TrailingRequiresClause->printPretty(Out, nullptr, SubPolicy, Indentation,
757                                           "\n", &Context);
758     }
759   } else {
760     Ty.print(Out, Policy, Proto);
761   }
762 
763   prettyPrintAttributes(D);
764 
765   if (D->isPure())
766     Out << " = 0";
767   else if (D->isDeletedAsWritten())
768     Out << " = delete";
769   else if (D->isExplicitlyDefaulted())
770     Out << " = default";
771   else if (D->doesThisDeclarationHaveABody()) {
772     if (!Policy.TerseOutput) {
773       if (!D->hasPrototype() && D->getNumParams()) {
774         // This is a K&R function definition, so we need to print the
775         // parameters.
776         Out << '\n';
777         DeclPrinter ParamPrinter(Out, SubPolicy, Context, Indentation);
778         Indentation += Policy.Indentation;
779         for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
780           Indent();
781           ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
782           Out << ";\n";
783         }
784         Indentation -= Policy.Indentation;
785       }
786 
787       if (D->getBody())
788         D->getBody()->printPrettyControlled(Out, nullptr, SubPolicy, Indentation, "\n",
789                                   &Context);
790     } else {
791       if (!Policy.TerseOutput && isa<CXXConstructorDecl>(*D))
792         Out << " {}";
793     }
794   }
795 }
796 
797 void DeclPrinter::VisitFriendDecl(FriendDecl *D) {
798   if (TypeSourceInfo *TSI = D->getFriendType()) {
799     unsigned NumTPLists = D->getFriendTypeNumTemplateParameterLists();
800     for (unsigned i = 0; i < NumTPLists; ++i)
801       printTemplateParameters(D->getFriendTypeTemplateParameterList(i));
802     Out << "friend ";
803     Out << " " << TSI->getType().getAsString(Policy);
804   }
805   else if (FunctionDecl *FD =
806       dyn_cast<FunctionDecl>(D->getFriendDecl())) {
807     Out << "friend ";
808     VisitFunctionDecl(FD);
809   }
810   else if (FunctionTemplateDecl *FTD =
811            dyn_cast<FunctionTemplateDecl>(D->getFriendDecl())) {
812     Out << "friend ";
813     VisitFunctionTemplateDecl(FTD);
814   }
815   else if (ClassTemplateDecl *CTD =
816            dyn_cast<ClassTemplateDecl>(D->getFriendDecl())) {
817     Out << "friend ";
818     VisitRedeclarableTemplateDecl(CTD);
819   }
820 }
821 
822 void DeclPrinter::VisitFieldDecl(FieldDecl *D) {
823   // FIXME: add printing of pragma attributes if required.
824   if (!Policy.SuppressSpecifiers && D->isMutable())
825     Out << "mutable ";
826   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
827     Out << "__module_private__ ";
828 
829   Out << D->getASTContext().getUnqualifiedObjCPointerType(D->getType()).
830          stream(Policy, D->getName(), Indentation);
831 
832   if (D->isBitField()) {
833     Out << " : ";
834     D->getBitWidth()->printPretty(Out, nullptr, Policy, Indentation, "\n",
835                                   &Context);
836   }
837 
838   Expr *Init = D->getInClassInitializer();
839   if (!Policy.SuppressInitializers && Init) {
840     if (D->getInClassInitStyle() == ICIS_ListInit)
841       Out << " ";
842     else
843       Out << " = ";
844     Init->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context);
845   }
846   prettyPrintAttributes(D);
847 }
848 
849 void DeclPrinter::VisitLabelDecl(LabelDecl *D) {
850   Out << *D << ":";
851 }
852 
853 void DeclPrinter::VisitVarDecl(VarDecl *D) {
854   prettyPrintPragmas(D);
855 
856   QualType T = D->getTypeSourceInfo()
857     ? D->getTypeSourceInfo()->getType()
858     : D->getASTContext().getUnqualifiedObjCPointerType(D->getType());
859 
860   if (!Policy.SuppressSpecifiers) {
861     StorageClass SC = D->getStorageClass();
862     if (SC != SC_None)
863       Out << VarDecl::getStorageClassSpecifierString(SC) << " ";
864 
865     switch (D->getTSCSpec()) {
866     case TSCS_unspecified:
867       break;
868     case TSCS___thread:
869       Out << "__thread ";
870       break;
871     case TSCS__Thread_local:
872       Out << "_Thread_local ";
873       break;
874     case TSCS_thread_local:
875       Out << "thread_local ";
876       break;
877     }
878 
879     if (D->isModulePrivate())
880       Out << "__module_private__ ";
881 
882     if (D->isConstexpr()) {
883       Out << "constexpr ";
884       T.removeLocalConst();
885     }
886   }
887 
888   printDeclType(T, D->getName());
889   Expr *Init = D->getInit();
890   if (!Policy.SuppressInitializers && Init) {
891     bool ImplicitInit = false;
892     if (CXXConstructExpr *Construct =
893             dyn_cast<CXXConstructExpr>(Init->IgnoreImplicit())) {
894       if (D->getInitStyle() == VarDecl::CallInit &&
895           !Construct->isListInitialization()) {
896         ImplicitInit = Construct->getNumArgs() == 0 ||
897           Construct->getArg(0)->isDefaultArgument();
898       }
899     }
900     if (!ImplicitInit) {
901       if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
902         Out << "(";
903       else if (D->getInitStyle() == VarDecl::CInit) {
904         Out << " = ";
905       }
906       PrintingPolicy SubPolicy(Policy);
907       SubPolicy.SuppressSpecifiers = false;
908       SubPolicy.IncludeTagDefinition = false;
909       Init->printPretty(Out, nullptr, SubPolicy, Indentation, "\n", &Context);
910       if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
911         Out << ")";
912     }
913   }
914   prettyPrintAttributes(D);
915 }
916 
917 void DeclPrinter::VisitParmVarDecl(ParmVarDecl *D) {
918   VisitVarDecl(D);
919 }
920 
921 void DeclPrinter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) {
922   Out << "__asm (";
923   D->getAsmString()->printPretty(Out, nullptr, Policy, Indentation, "\n",
924                                  &Context);
925   Out << ")";
926 }
927 
928 void DeclPrinter::VisitImportDecl(ImportDecl *D) {
929   Out << "@import " << D->getImportedModule()->getFullModuleName()
930       << ";\n";
931 }
932 
933 void DeclPrinter::VisitStaticAssertDecl(StaticAssertDecl *D) {
934   Out << "static_assert(";
935   D->getAssertExpr()->printPretty(Out, nullptr, Policy, Indentation, "\n",
936                                   &Context);
937   if (StringLiteral *SL = D->getMessage()) {
938     Out << ", ";
939     SL->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context);
940   }
941   Out << ")";
942 }
943 
944 //----------------------------------------------------------------------------
945 // C++ declarations
946 //----------------------------------------------------------------------------
947 void DeclPrinter::VisitNamespaceDecl(NamespaceDecl *D) {
948   if (D->isInline())
949     Out << "inline ";
950 
951   Out << "namespace ";
952   if (D->getDeclName())
953     Out << D->getDeclName() << ' ';
954   Out << "{\n";
955 
956   VisitDeclContext(D);
957   Indent() << "}";
958 }
959 
960 void DeclPrinter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
961   Out << "using namespace ";
962   if (D->getQualifier())
963     D->getQualifier()->print(Out, Policy);
964   Out << *D->getNominatedNamespaceAsWritten();
965 }
966 
967 void DeclPrinter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
968   Out << "namespace " << *D << " = ";
969   if (D->getQualifier())
970     D->getQualifier()->print(Out, Policy);
971   Out << *D->getAliasedNamespace();
972 }
973 
974 void DeclPrinter::VisitEmptyDecl(EmptyDecl *D) {
975   prettyPrintAttributes(D);
976 }
977 
978 void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) {
979   // FIXME: add printing of pragma attributes if required.
980   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
981     Out << "__module_private__ ";
982   Out << D->getKindName();
983 
984   prettyPrintAttributes(D);
985 
986   if (D->getIdentifier()) {
987     Out << ' ' << *D;
988 
989     if (auto S = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
990       ArrayRef<TemplateArgument> Args = S->getTemplateArgs().asArray();
991       if (!Policy.PrintCanonicalTypes)
992         if (const auto* TSI = S->getTypeAsWritten())
993           if (const auto *TST =
994                   dyn_cast<TemplateSpecializationType>(TSI->getType()))
995             Args = TST->template_arguments();
996       printTemplateArguments(
997           Args, S->getSpecializedTemplate()->getTemplateParameters());
998     }
999   }
1000 
1001   if (D->isCompleteDefinition()) {
1002     // Print the base classes
1003     if (D->getNumBases()) {
1004       Out << " : ";
1005       for (CXXRecordDecl::base_class_iterator Base = D->bases_begin(),
1006              BaseEnd = D->bases_end(); Base != BaseEnd; ++Base) {
1007         if (Base != D->bases_begin())
1008           Out << ", ";
1009 
1010         if (Base->isVirtual())
1011           Out << "virtual ";
1012 
1013         AccessSpecifier AS = Base->getAccessSpecifierAsWritten();
1014         if (AS != AS_none) {
1015           Print(AS);
1016           Out << " ";
1017         }
1018         Out << Base->getType().getAsString(Policy);
1019 
1020         if (Base->isPackExpansion())
1021           Out << "...";
1022       }
1023     }
1024 
1025     // Print the class definition
1026     // FIXME: Doesn't print access specifiers, e.g., "public:"
1027     if (Policy.TerseOutput) {
1028       Out << " {}";
1029     } else {
1030       Out << " {\n";
1031       VisitDeclContext(D);
1032       Indent() << "}";
1033     }
1034   }
1035 }
1036 
1037 void DeclPrinter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1038   const char *l;
1039   if (D->getLanguage() == LinkageSpecDecl::lang_c)
1040     l = "C";
1041   else {
1042     assert(D->getLanguage() == LinkageSpecDecl::lang_cxx &&
1043            "unknown language in linkage specification");
1044     l = "C++";
1045   }
1046 
1047   Out << "extern \"" << l << "\" ";
1048   if (D->hasBraces()) {
1049     Out << "{\n";
1050     VisitDeclContext(D);
1051     Indent() << "}";
1052   } else
1053     Visit(*D->decls_begin());
1054 }
1055 
1056 void DeclPrinter::printTemplateParameters(const TemplateParameterList *Params,
1057                                           bool OmitTemplateKW) {
1058   assert(Params);
1059 
1060   if (!OmitTemplateKW)
1061     Out << "template ";
1062   Out << '<';
1063 
1064   bool NeedComma = false;
1065   for (const Decl *Param : *Params) {
1066     if (Param->isImplicit())
1067       continue;
1068 
1069     if (NeedComma)
1070       Out << ", ";
1071     else
1072       NeedComma = true;
1073 
1074     if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
1075       VisitTemplateTypeParmDecl(TTP);
1076     } else if (auto NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1077       VisitNonTypeTemplateParmDecl(NTTP);
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                                          const TemplateParameterList *Params) {
1091   Out << "<";
1092   for (size_t I = 0, E = Args.size(); I < E; ++I) {
1093     if (I)
1094       Out << ", ";
1095     if (!Params)
1096       Args[I].print(Policy, Out, /*IncludeType*/ true);
1097     else
1098       Args[I].print(Policy, Out,
1099                     TemplateParameterList::shouldIncludeTypeForArgument(
1100                         Policy, Params, I));
1101   }
1102   Out << ">";
1103 }
1104 
1105 void DeclPrinter::printTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
1106                                          const TemplateParameterList *Params) {
1107   Out << "<";
1108   for (size_t I = 0, E = Args.size(); I < E; ++I) {
1109     if (I)
1110       Out << ", ";
1111     if (!Params)
1112       Args[I].getArgument().print(Policy, Out, /*IncludeType*/ true);
1113     else
1114       Args[I].getArgument().print(
1115           Policy, Out,
1116           TemplateParameterList::shouldIncludeTypeForArgument(Policy, Params,
1117                                                               I));
1118   }
1119   Out << ">";
1120 }
1121 
1122 void DeclPrinter::VisitTemplateDecl(const TemplateDecl *D) {
1123   printTemplateParameters(D->getTemplateParameters());
1124 
1125   if (const TemplateTemplateParmDecl *TTP =
1126         dyn_cast<TemplateTemplateParmDecl>(D)) {
1127     Out << "class";
1128 
1129     if (TTP->isParameterPack())
1130       Out << " ...";
1131     else if (TTP->getDeclName())
1132       Out << ' ';
1133 
1134     if (TTP->getDeclName())
1135       Out << TTP->getDeclName();
1136   } else if (auto *TD = D->getTemplatedDecl())
1137     Visit(TD);
1138   else if (const auto *Concept = dyn_cast<ConceptDecl>(D)) {
1139     Out << "concept " << Concept->getName() << " = " ;
1140     Concept->getConstraintExpr()->printPretty(Out, nullptr, Policy, Indentation,
1141                                               "\n", &Context);
1142   }
1143 }
1144 
1145 void DeclPrinter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1146   prettyPrintPragmas(D->getTemplatedDecl());
1147   // Print any leading template parameter lists.
1148   if (const FunctionDecl *FD = D->getTemplatedDecl()) {
1149     for (unsigned I = 0, NumTemplateParams = FD->getNumTemplateParameterLists();
1150          I < NumTemplateParams; ++I)
1151       printTemplateParameters(FD->getTemplateParameterList(I));
1152   }
1153   VisitRedeclarableTemplateDecl(D);
1154   // Declare target attribute is special one, natural spelling for the pragma
1155   // assumes "ending" construct so print it here.
1156   if (D->getTemplatedDecl()->hasAttr<OMPDeclareTargetDeclAttr>())
1157     Out << "#pragma omp end declare target\n";
1158 
1159   // Never print "instantiations" for deduction guides (they don't really
1160   // have them).
1161   if (PrintInstantiation &&
1162       !isa<CXXDeductionGuideDecl>(D->getTemplatedDecl())) {
1163     FunctionDecl *PrevDecl = D->getTemplatedDecl();
1164     const FunctionDecl *Def;
1165     if (PrevDecl->isDefined(Def) && Def != PrevDecl)
1166       return;
1167     for (auto *I : D->specializations())
1168       if (I->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) {
1169         if (!PrevDecl->isThisDeclarationADefinition())
1170           Out << ";\n";
1171         Indent();
1172         prettyPrintPragmas(I);
1173         Visit(I);
1174       }
1175   }
1176 }
1177 
1178 void DeclPrinter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1179   VisitRedeclarableTemplateDecl(D);
1180 
1181   if (PrintInstantiation) {
1182     for (auto *I : D->specializations())
1183       if (I->getSpecializationKind() == TSK_ImplicitInstantiation) {
1184         if (D->isThisDeclarationADefinition())
1185           Out << ";";
1186         Out << "\n";
1187         Indent();
1188         Visit(I);
1189       }
1190   }
1191 }
1192 
1193 void DeclPrinter::VisitClassTemplateSpecializationDecl(
1194                                            ClassTemplateSpecializationDecl *D) {
1195   Out << "template<> ";
1196   VisitCXXRecordDecl(D);
1197 }
1198 
1199 void DeclPrinter::VisitClassTemplatePartialSpecializationDecl(
1200                                     ClassTemplatePartialSpecializationDecl *D) {
1201   printTemplateParameters(D->getTemplateParameters());
1202   VisitCXXRecordDecl(D);
1203 }
1204 
1205 //----------------------------------------------------------------------------
1206 // Objective-C declarations
1207 //----------------------------------------------------------------------------
1208 
1209 void DeclPrinter::PrintObjCMethodType(ASTContext &Ctx,
1210                                       Decl::ObjCDeclQualifier Quals,
1211                                       QualType T) {
1212   Out << '(';
1213   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_In)
1214     Out << "in ";
1215   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Inout)
1216     Out << "inout ";
1217   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Out)
1218     Out << "out ";
1219   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Bycopy)
1220     Out << "bycopy ";
1221   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Byref)
1222     Out << "byref ";
1223   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Oneway)
1224     Out << "oneway ";
1225   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_CSNullability) {
1226     if (auto nullability = AttributedType::stripOuterNullability(T))
1227       Out << getNullabilitySpelling(*nullability, true) << ' ';
1228   }
1229 
1230   Out << Ctx.getUnqualifiedObjCPointerType(T).getAsString(Policy);
1231   Out << ')';
1232 }
1233 
1234 void DeclPrinter::PrintObjCTypeParams(ObjCTypeParamList *Params) {
1235   Out << "<";
1236   unsigned First = true;
1237   for (auto *Param : *Params) {
1238     if (First) {
1239       First = false;
1240     } else {
1241       Out << ", ";
1242     }
1243 
1244     switch (Param->getVariance()) {
1245     case ObjCTypeParamVariance::Invariant:
1246       break;
1247 
1248     case ObjCTypeParamVariance::Covariant:
1249       Out << "__covariant ";
1250       break;
1251 
1252     case ObjCTypeParamVariance::Contravariant:
1253       Out << "__contravariant ";
1254       break;
1255     }
1256 
1257     Out << Param->getDeclName();
1258 
1259     if (Param->hasExplicitBound()) {
1260       Out << " : " << Param->getUnderlyingType().getAsString(Policy);
1261     }
1262   }
1263   Out << ">";
1264 }
1265 
1266 void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) {
1267   if (OMD->isInstanceMethod())
1268     Out << "- ";
1269   else
1270     Out << "+ ";
1271   if (!OMD->getReturnType().isNull()) {
1272     PrintObjCMethodType(OMD->getASTContext(), OMD->getObjCDeclQualifier(),
1273                         OMD->getReturnType());
1274   }
1275 
1276   std::string name = OMD->getSelector().getAsString();
1277   std::string::size_type pos, lastPos = 0;
1278   for (const auto *PI : OMD->parameters()) {
1279     // FIXME: selector is missing here!
1280     pos = name.find_first_of(':', lastPos);
1281     if (lastPos != 0)
1282       Out << " ";
1283     Out << name.substr(lastPos, pos - lastPos) << ':';
1284     PrintObjCMethodType(OMD->getASTContext(),
1285                         PI->getObjCDeclQualifier(),
1286                         PI->getType());
1287     Out << *PI;
1288     lastPos = pos + 1;
1289   }
1290 
1291   if (OMD->param_begin() == OMD->param_end())
1292     Out << name;
1293 
1294   if (OMD->isVariadic())
1295       Out << ", ...";
1296 
1297   prettyPrintAttributes(OMD);
1298 
1299   if (OMD->getBody() && !Policy.TerseOutput) {
1300     Out << ' ';
1301     OMD->getBody()->printPretty(Out, nullptr, Policy, Indentation, "\n",
1302                                 &Context);
1303   }
1304   else if (Policy.PolishForDeclaration)
1305     Out << ';';
1306 }
1307 
1308 void DeclPrinter::VisitObjCImplementationDecl(ObjCImplementationDecl *OID) {
1309   std::string I = OID->getNameAsString();
1310   ObjCInterfaceDecl *SID = OID->getSuperClass();
1311 
1312   bool eolnOut = false;
1313   if (SID)
1314     Out << "@implementation " << I << " : " << *SID;
1315   else
1316     Out << "@implementation " << I;
1317 
1318   if (OID->ivar_size() > 0) {
1319     Out << "{\n";
1320     eolnOut = true;
1321     Indentation += Policy.Indentation;
1322     for (const auto *I : OID->ivars()) {
1323       Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).
1324                     getAsString(Policy) << ' ' << *I << ";\n";
1325     }
1326     Indentation -= Policy.Indentation;
1327     Out << "}\n";
1328   }
1329   else if (SID || (OID->decls_begin() != OID->decls_end())) {
1330     Out << "\n";
1331     eolnOut = true;
1332   }
1333   VisitDeclContext(OID, false);
1334   if (!eolnOut)
1335     Out << "\n";
1336   Out << "@end";
1337 }
1338 
1339 void DeclPrinter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *OID) {
1340   std::string I = OID->getNameAsString();
1341   ObjCInterfaceDecl *SID = OID->getSuperClass();
1342 
1343   if (!OID->isThisDeclarationADefinition()) {
1344     Out << "@class " << I;
1345 
1346     if (auto TypeParams = OID->getTypeParamListAsWritten()) {
1347       PrintObjCTypeParams(TypeParams);
1348     }
1349 
1350     Out << ";";
1351     return;
1352   }
1353   bool eolnOut = false;
1354   Out << "@interface " << I;
1355 
1356   if (auto TypeParams = OID->getTypeParamListAsWritten()) {
1357     PrintObjCTypeParams(TypeParams);
1358   }
1359 
1360   if (SID)
1361     Out << " : " << QualType(OID->getSuperClassType(), 0).getAsString(Policy);
1362 
1363   // Protocols?
1364   const ObjCList<ObjCProtocolDecl> &Protocols = OID->getReferencedProtocols();
1365   if (!Protocols.empty()) {
1366     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1367          E = Protocols.end(); I != E; ++I)
1368       Out << (I == Protocols.begin() ? '<' : ',') << **I;
1369     Out << "> ";
1370   }
1371 
1372   if (OID->ivar_size() > 0) {
1373     Out << "{\n";
1374     eolnOut = true;
1375     Indentation += Policy.Indentation;
1376     for (const auto *I : OID->ivars()) {
1377       Indent() << I->getASTContext()
1378                       .getUnqualifiedObjCPointerType(I->getType())
1379                       .getAsString(Policy) << ' ' << *I << ";\n";
1380     }
1381     Indentation -= Policy.Indentation;
1382     Out << "}\n";
1383   }
1384   else if (SID || (OID->decls_begin() != OID->decls_end())) {
1385     Out << "\n";
1386     eolnOut = true;
1387   }
1388 
1389   VisitDeclContext(OID, false);
1390   if (!eolnOut)
1391     Out << "\n";
1392   Out << "@end";
1393   // FIXME: implement the rest...
1394 }
1395 
1396 void DeclPrinter::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1397   if (!PID->isThisDeclarationADefinition()) {
1398     Out << "@protocol " << *PID << ";\n";
1399     return;
1400   }
1401   // Protocols?
1402   const ObjCList<ObjCProtocolDecl> &Protocols = PID->getReferencedProtocols();
1403   if (!Protocols.empty()) {
1404     Out << "@protocol " << *PID;
1405     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1406          E = Protocols.end(); I != E; ++I)
1407       Out << (I == Protocols.begin() ? '<' : ',') << **I;
1408     Out << ">\n";
1409   } else
1410     Out << "@protocol " << *PID << '\n';
1411   VisitDeclContext(PID, false);
1412   Out << "@end";
1413 }
1414 
1415 void DeclPrinter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *PID) {
1416   Out << "@implementation ";
1417   if (const auto *CID = PID->getClassInterface())
1418     Out << *CID;
1419   else
1420     Out << "<<error-type>>";
1421   Out << '(' << *PID << ")\n";
1422 
1423   VisitDeclContext(PID, false);
1424   Out << "@end";
1425   // FIXME: implement the rest...
1426 }
1427 
1428 void DeclPrinter::VisitObjCCategoryDecl(ObjCCategoryDecl *PID) {
1429   Out << "@interface ";
1430   if (const auto *CID = PID->getClassInterface())
1431     Out << *CID;
1432   else
1433     Out << "<<error-type>>";
1434   if (auto TypeParams = PID->getTypeParamList()) {
1435     PrintObjCTypeParams(TypeParams);
1436   }
1437   Out << "(" << *PID << ")\n";
1438   if (PID->ivar_size() > 0) {
1439     Out << "{\n";
1440     Indentation += Policy.Indentation;
1441     for (const auto *I : PID->ivars())
1442       Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).
1443                     getAsString(Policy) << ' ' << *I << ";\n";
1444     Indentation -= Policy.Indentation;
1445     Out << "}\n";
1446   }
1447 
1448   VisitDeclContext(PID, false);
1449   Out << "@end";
1450 
1451   // FIXME: implement the rest...
1452 }
1453 
1454 void DeclPrinter::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *AID) {
1455   Out << "@compatibility_alias " << *AID
1456       << ' ' << *AID->getClassInterface() << ";\n";
1457 }
1458 
1459 /// PrintObjCPropertyDecl - print a property declaration.
1460 ///
1461 /// Print attributes in the following order:
1462 /// - class
1463 /// - nonatomic | atomic
1464 /// - assign | retain | strong | copy | weak | unsafe_unretained
1465 /// - readwrite | readonly
1466 /// - getter & setter
1467 /// - nullability
1468 void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) {
1469   if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Required)
1470     Out << "@required\n";
1471   else if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Optional)
1472     Out << "@optional\n";
1473 
1474   QualType T = PDecl->getType();
1475 
1476   Out << "@property";
1477   if (PDecl->getPropertyAttributes() != ObjCPropertyAttribute::kind_noattr) {
1478     bool first = true;
1479     Out << "(";
1480     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_class) {
1481       Out << (first ? "" : ", ") << "class";
1482       first = false;
1483     }
1484 
1485     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_direct) {
1486       Out << (first ? "" : ", ") << "direct";
1487       first = false;
1488     }
1489 
1490     if (PDecl->getPropertyAttributes() &
1491         ObjCPropertyAttribute::kind_nonatomic) {
1492       Out << (first ? "" : ", ") << "nonatomic";
1493       first = false;
1494     }
1495     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_atomic) {
1496       Out << (first ? "" : ", ") << "atomic";
1497       first = false;
1498     }
1499 
1500     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_assign) {
1501       Out << (first ? "" : ", ") << "assign";
1502       first = false;
1503     }
1504     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain) {
1505       Out << (first ? "" : ", ") << "retain";
1506       first = false;
1507     }
1508 
1509     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_strong) {
1510       Out << (first ? "" : ", ") << "strong";
1511       first = false;
1512     }
1513     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy) {
1514       Out << (first ? "" : ", ") << "copy";
1515       first = false;
1516     }
1517     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak) {
1518       Out << (first ? "" : ", ") << "weak";
1519       first = false;
1520     }
1521     if (PDecl->getPropertyAttributes() &
1522         ObjCPropertyAttribute::kind_unsafe_unretained) {
1523       Out << (first ? "" : ", ") << "unsafe_unretained";
1524       first = false;
1525     }
1526 
1527     if (PDecl->getPropertyAttributes() &
1528         ObjCPropertyAttribute::kind_readwrite) {
1529       Out << (first ? "" : ", ") << "readwrite";
1530       first = false;
1531     }
1532     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_readonly) {
1533       Out << (first ? "" : ", ") << "readonly";
1534       first = false;
1535     }
1536 
1537     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
1538       Out << (first ? "" : ", ") << "getter = ";
1539       PDecl->getGetterName().print(Out);
1540       first = false;
1541     }
1542     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
1543       Out << (first ? "" : ", ") << "setter = ";
1544       PDecl->getSetterName().print(Out);
1545       first = false;
1546     }
1547 
1548     if (PDecl->getPropertyAttributes() &
1549         ObjCPropertyAttribute::kind_nullability) {
1550       if (auto nullability = AttributedType::stripOuterNullability(T)) {
1551         if (*nullability == NullabilityKind::Unspecified &&
1552             (PDecl->getPropertyAttributes() &
1553              ObjCPropertyAttribute::kind_null_resettable)) {
1554           Out << (first ? "" : ", ") << "null_resettable";
1555         } else {
1556           Out << (first ? "" : ", ")
1557               << getNullabilitySpelling(*nullability, true);
1558         }
1559         first = false;
1560       }
1561     }
1562 
1563     (void) first; // Silence dead store warning due to idiomatic code.
1564     Out << ")";
1565   }
1566   std::string TypeStr = PDecl->getASTContext().getUnqualifiedObjCPointerType(T).
1567       getAsString(Policy);
1568   Out << ' ' << TypeStr;
1569   if (!StringRef(TypeStr).endswith("*"))
1570     Out << ' ';
1571   Out << *PDecl;
1572   if (Policy.PolishForDeclaration)
1573     Out << ';';
1574 }
1575 
1576 void DeclPrinter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PID) {
1577   if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize)
1578     Out << "@synthesize ";
1579   else
1580     Out << "@dynamic ";
1581   Out << *PID->getPropertyDecl();
1582   if (PID->getPropertyIvarDecl())
1583     Out << '=' << *PID->getPropertyIvarDecl();
1584 }
1585 
1586 void DeclPrinter::VisitUsingDecl(UsingDecl *D) {
1587   if (!D->isAccessDeclaration())
1588     Out << "using ";
1589   if (D->hasTypename())
1590     Out << "typename ";
1591   D->getQualifier()->print(Out, Policy);
1592 
1593   // Use the correct record name when the using declaration is used for
1594   // inheriting constructors.
1595   for (const auto *Shadow : D->shadows()) {
1596     if (const auto *ConstructorShadow =
1597             dyn_cast<ConstructorUsingShadowDecl>(Shadow)) {
1598       assert(Shadow->getDeclContext() == ConstructorShadow->getDeclContext());
1599       Out << *ConstructorShadow->getNominatedBaseClass();
1600       return;
1601     }
1602   }
1603   Out << *D;
1604 }
1605 
1606 void DeclPrinter::VisitUsingEnumDecl(UsingEnumDecl *D) {
1607   Out << "using enum " << D->getEnumDecl();
1608 }
1609 
1610 void
1611 DeclPrinter::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
1612   Out << "using typename ";
1613   D->getQualifier()->print(Out, Policy);
1614   Out << D->getDeclName();
1615 }
1616 
1617 void DeclPrinter::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1618   if (!D->isAccessDeclaration())
1619     Out << "using ";
1620   D->getQualifier()->print(Out, Policy);
1621   Out << D->getDeclName();
1622 }
1623 
1624 void DeclPrinter::VisitUsingShadowDecl(UsingShadowDecl *D) {
1625   // ignore
1626 }
1627 
1628 void DeclPrinter::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
1629   Out << "#pragma omp threadprivate";
1630   if (!D->varlist_empty()) {
1631     for (OMPThreadPrivateDecl::varlist_iterator I = D->varlist_begin(),
1632                                                 E = D->varlist_end();
1633                                                 I != E; ++I) {
1634       Out << (I == D->varlist_begin() ? '(' : ',');
1635       NamedDecl *ND = cast<DeclRefExpr>(*I)->getDecl();
1636       ND->printQualifiedName(Out);
1637     }
1638     Out << ")";
1639   }
1640 }
1641 
1642 void DeclPrinter::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
1643   Out << "#pragma omp allocate";
1644   if (!D->varlist_empty()) {
1645     for (OMPAllocateDecl::varlist_iterator I = D->varlist_begin(),
1646                                            E = D->varlist_end();
1647          I != E; ++I) {
1648       Out << (I == D->varlist_begin() ? '(' : ',');
1649       NamedDecl *ND = cast<DeclRefExpr>(*I)->getDecl();
1650       ND->printQualifiedName(Out);
1651     }
1652     Out << ")";
1653   }
1654   if (!D->clauselist_empty()) {
1655     OMPClausePrinter Printer(Out, Policy);
1656     for (OMPClause *C : D->clauselists()) {
1657       Out << " ";
1658       Printer.Visit(C);
1659     }
1660   }
1661 }
1662 
1663 void DeclPrinter::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
1664   Out << "#pragma omp requires ";
1665   if (!D->clauselist_empty()) {
1666     OMPClausePrinter Printer(Out, Policy);
1667     for (auto I = D->clauselist_begin(), E = D->clauselist_end(); I != E; ++I)
1668       Printer.Visit(*I);
1669   }
1670 }
1671 
1672 void DeclPrinter::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
1673   if (!D->isInvalidDecl()) {
1674     Out << "#pragma omp declare reduction (";
1675     if (D->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) {
1676       const char *OpName =
1677           getOperatorSpelling(D->getDeclName().getCXXOverloadedOperator());
1678       assert(OpName && "not an overloaded operator");
1679       Out << OpName;
1680     } else {
1681       assert(D->getDeclName().isIdentifier());
1682       D->printName(Out);
1683     }
1684     Out << " : ";
1685     D->getType().print(Out, Policy);
1686     Out << " : ";
1687     D->getCombiner()->printPretty(Out, nullptr, Policy, 0, "\n", &Context);
1688     Out << ")";
1689     if (auto *Init = D->getInitializer()) {
1690       Out << " initializer(";
1691       switch (D->getInitializerKind()) {
1692       case OMPDeclareReductionDecl::DirectInit:
1693         Out << "omp_priv(";
1694         break;
1695       case OMPDeclareReductionDecl::CopyInit:
1696         Out << "omp_priv = ";
1697         break;
1698       case OMPDeclareReductionDecl::CallInit:
1699         break;
1700       }
1701       Init->printPretty(Out, nullptr, Policy, 0, "\n", &Context);
1702       if (D->getInitializerKind() == OMPDeclareReductionDecl::DirectInit)
1703         Out << ")";
1704       Out << ")";
1705     }
1706   }
1707 }
1708 
1709 void DeclPrinter::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
1710   if (!D->isInvalidDecl()) {
1711     Out << "#pragma omp declare mapper (";
1712     D->printName(Out);
1713     Out << " : ";
1714     D->getType().print(Out, Policy);
1715     Out << " ";
1716     Out << D->getVarName();
1717     Out << ")";
1718     if (!D->clauselist_empty()) {
1719       OMPClausePrinter Printer(Out, Policy);
1720       for (auto *C : D->clauselists()) {
1721         Out << " ";
1722         Printer.Visit(C);
1723       }
1724     }
1725   }
1726 }
1727 
1728 void DeclPrinter::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
1729   D->getInit()->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context);
1730 }
1731 
1732 void DeclPrinter::VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *TTP) {
1733   if (const TypeConstraint *TC = TTP->getTypeConstraint())
1734     TC->print(Out, Policy);
1735   else if (TTP->wasDeclaredWithTypename())
1736     Out << "typename";
1737   else
1738     Out << "class";
1739 
1740   if (TTP->isParameterPack())
1741     Out << " ...";
1742   else if (TTP->getDeclName())
1743     Out << ' ';
1744 
1745   if (TTP->getDeclName())
1746     Out << TTP->getDeclName();
1747 
1748   if (TTP->hasDefaultArgument()) {
1749     Out << " = ";
1750     Out << TTP->getDefaultArgument().getAsString(Policy);
1751   }
1752 }
1753 
1754 void DeclPrinter::VisitNonTypeTemplateParmDecl(
1755     const NonTypeTemplateParmDecl *NTTP) {
1756   StringRef Name;
1757   if (IdentifierInfo *II = NTTP->getIdentifier())
1758     Name = II->getName();
1759   printDeclType(NTTP->getType(), Name, NTTP->isParameterPack());
1760 
1761   if (NTTP->hasDefaultArgument()) {
1762     Out << " = ";
1763     NTTP->getDefaultArgument()->printPretty(Out, nullptr, Policy, Indentation,
1764                                             "\n", &Context);
1765   }
1766 }
1767