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