xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/AST/DeclPrinter.cpp (revision e038c9c4676b0f19b1b7dd08a940c6ed64a6d5ae)
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 VisitUsingShadowDecl(UsingShadowDecl *D);
102     void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
103     void VisitOMPAllocateDecl(OMPAllocateDecl *D);
104     void VisitOMPRequiresDecl(OMPRequiresDecl *D);
105     void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D);
106     void VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D);
107     void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D);
108     void VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *TTP);
109     void VisitNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *NTTP);
110 
111     void printTemplateParameters(const TemplateParameterList *Params,
112                                  bool OmitTemplateKW = false);
113     void printTemplateArguments(llvm::ArrayRef<TemplateArgument> Args,
114                                 const TemplateParameterList *Params,
115                                 bool TemplOverloaded);
116     void printTemplateArguments(llvm::ArrayRef<TemplateArgumentLoc> Args,
117                                 const TemplateParameterList *Params,
118                                 bool TemplOverloaded);
119     void prettyPrintAttributes(Decl *D);
120     void prettyPrintPragmas(Decl *D);
121     void printDeclType(QualType T, StringRef DeclName, bool Pack = false);
122   };
123 }
124 
print(raw_ostream & Out,unsigned Indentation,bool PrintInstantiation) const125 void Decl::print(raw_ostream &Out, unsigned Indentation,
126                  bool PrintInstantiation) const {
127   print(Out, getASTContext().getPrintingPolicy(), Indentation, PrintInstantiation);
128 }
129 
print(raw_ostream & Out,const PrintingPolicy & Policy,unsigned Indentation,bool PrintInstantiation) const130 void Decl::print(raw_ostream &Out, const PrintingPolicy &Policy,
131                  unsigned Indentation, bool PrintInstantiation) const {
132   DeclPrinter Printer(Out, Policy, getASTContext(), Indentation,
133                       PrintInstantiation);
134   Printer.Visit(const_cast<Decl*>(this));
135 }
136 
print(raw_ostream & Out,const ASTContext & Context,bool OmitTemplateKW) const137 void TemplateParameterList::print(raw_ostream &Out, const ASTContext &Context,
138                                   bool OmitTemplateKW) const {
139   print(Out, Context, Context.getPrintingPolicy(), OmitTemplateKW);
140 }
141 
print(raw_ostream & Out,const ASTContext & Context,const PrintingPolicy & Policy,bool OmitTemplateKW) const142 void TemplateParameterList::print(raw_ostream &Out, const ASTContext &Context,
143                                   const PrintingPolicy &Policy,
144                                   bool OmitTemplateKW) const {
145   DeclPrinter Printer(Out, Policy, Context);
146   Printer.printTemplateParameters(this, OmitTemplateKW);
147 }
148 
GetBaseType(QualType T)149 static QualType GetBaseType(QualType T) {
150   // FIXME: This should be on the Type class!
151   QualType BaseType = T;
152   while (!BaseType->isSpecifierType()) {
153     if (const PointerType *PTy = BaseType->getAs<PointerType>())
154       BaseType = PTy->getPointeeType();
155     else if (const BlockPointerType *BPy = BaseType->getAs<BlockPointerType>())
156       BaseType = BPy->getPointeeType();
157     else if (const ArrayType* ATy = dyn_cast<ArrayType>(BaseType))
158       BaseType = ATy->getElementType();
159     else if (const FunctionType* FTy = BaseType->getAs<FunctionType>())
160       BaseType = FTy->getReturnType();
161     else if (const VectorType *VTy = BaseType->getAs<VectorType>())
162       BaseType = VTy->getElementType();
163     else if (const ReferenceType *RTy = BaseType->getAs<ReferenceType>())
164       BaseType = RTy->getPointeeType();
165     else if (const AutoType *ATy = BaseType->getAs<AutoType>())
166       BaseType = ATy->getDeducedType();
167     else if (const ParenType *PTy = BaseType->getAs<ParenType>())
168       BaseType = PTy->desugar();
169     else
170       // This must be a syntax error.
171       break;
172   }
173   return BaseType;
174 }
175 
getDeclType(Decl * D)176 static QualType getDeclType(Decl* D) {
177   if (TypedefNameDecl* TDD = dyn_cast<TypedefNameDecl>(D))
178     return TDD->getUnderlyingType();
179   if (ValueDecl* VD = dyn_cast<ValueDecl>(D))
180     return VD->getType();
181   return QualType();
182 }
183 
printGroup(Decl ** Begin,unsigned NumDecls,raw_ostream & Out,const PrintingPolicy & Policy,unsigned Indentation)184 void Decl::printGroup(Decl** Begin, unsigned NumDecls,
185                       raw_ostream &Out, const PrintingPolicy &Policy,
186                       unsigned Indentation) {
187   if (NumDecls == 1) {
188     (*Begin)->print(Out, Policy, Indentation);
189     return;
190   }
191 
192   Decl** End = Begin + NumDecls;
193   TagDecl* TD = dyn_cast<TagDecl>(*Begin);
194   if (TD)
195     ++Begin;
196 
197   PrintingPolicy SubPolicy(Policy);
198 
199   bool isFirst = true;
200   for ( ; Begin != End; ++Begin) {
201     if (isFirst) {
202       if(TD)
203         SubPolicy.IncludeTagDefinition = true;
204       SubPolicy.SuppressSpecifiers = false;
205       isFirst = false;
206     } else {
207       if (!isFirst) Out << ", ";
208       SubPolicy.IncludeTagDefinition = false;
209       SubPolicy.SuppressSpecifiers = true;
210     }
211 
212     (*Begin)->print(Out, SubPolicy, Indentation);
213   }
214 }
215 
dumpDeclContext() const216 LLVM_DUMP_METHOD void DeclContext::dumpDeclContext() const {
217   // Get the translation unit
218   const DeclContext *DC = this;
219   while (!DC->isTranslationUnit())
220     DC = DC->getParent();
221 
222   ASTContext &Ctx = cast<TranslationUnitDecl>(DC)->getASTContext();
223   DeclPrinter Printer(llvm::errs(), Ctx.getPrintingPolicy(), Ctx, 0);
224   Printer.VisitDeclContext(const_cast<DeclContext *>(this), /*Indent=*/false);
225 }
226 
Indent(unsigned Indentation)227 raw_ostream& DeclPrinter::Indent(unsigned Indentation) {
228   for (unsigned i = 0; i != Indentation; ++i)
229     Out << "  ";
230   return Out;
231 }
232 
prettyPrintAttributes(Decl * D)233 void DeclPrinter::prettyPrintAttributes(Decl *D) {
234   if (Policy.PolishForDeclaration)
235     return;
236 
237   if (D->hasAttrs()) {
238     AttrVec &Attrs = D->getAttrs();
239     for (auto *A : Attrs) {
240       if (A->isInherited() || A->isImplicit())
241         continue;
242       switch (A->getKind()) {
243 #define ATTR(X)
244 #define PRAGMA_SPELLING_ATTR(X) case attr::X:
245 #include "clang/Basic/AttrList.inc"
246         break;
247       default:
248         A->printPretty(Out, Policy);
249         break;
250       }
251     }
252   }
253 }
254 
prettyPrintPragmas(Decl * D)255 void DeclPrinter::prettyPrintPragmas(Decl *D) {
256   if (Policy.PolishForDeclaration)
257     return;
258 
259   if (D->hasAttrs()) {
260     AttrVec &Attrs = D->getAttrs();
261     for (auto *A : Attrs) {
262       switch (A->getKind()) {
263 #define ATTR(X)
264 #define PRAGMA_SPELLING_ATTR(X) case attr::X:
265 #include "clang/Basic/AttrList.inc"
266         A->printPretty(Out, Policy);
267         Indent();
268         break;
269       default:
270         break;
271       }
272     }
273   }
274 }
275 
printDeclType(QualType T,StringRef DeclName,bool Pack)276 void DeclPrinter::printDeclType(QualType T, StringRef DeclName, bool Pack) {
277   // Normally, a PackExpansionType is written as T[3]... (for instance, as a
278   // template argument), but if it is the type of a declaration, the ellipsis
279   // is placed before the name being declared.
280   if (auto *PET = T->getAs<PackExpansionType>()) {
281     Pack = true;
282     T = PET->getPattern();
283   }
284   T.print(Out, Policy, (Pack ? "..." : "") + DeclName, Indentation);
285 }
286 
ProcessDeclGroup(SmallVectorImpl<Decl * > & Decls)287 void DeclPrinter::ProcessDeclGroup(SmallVectorImpl<Decl*>& Decls) {
288   this->Indent();
289   Decl::printGroup(Decls.data(), Decls.size(), Out, Policy, Indentation);
290   Out << ";\n";
291   Decls.clear();
292 
293 }
294 
Print(AccessSpecifier AS)295 void DeclPrinter::Print(AccessSpecifier AS) {
296   const auto AccessSpelling = getAccessSpelling(AS);
297   if (AccessSpelling.empty())
298     llvm_unreachable("No access specifier!");
299   Out << AccessSpelling;
300 }
301 
PrintConstructorInitializers(CXXConstructorDecl * CDecl,std::string & Proto)302 void DeclPrinter::PrintConstructorInitializers(CXXConstructorDecl *CDecl,
303                                                std::string &Proto) {
304   bool HasInitializerList = false;
305   for (const auto *BMInitializer : CDecl->inits()) {
306     if (BMInitializer->isInClassMemberInitializer())
307       continue;
308 
309     if (!HasInitializerList) {
310       Proto += " : ";
311       Out << Proto;
312       Proto.clear();
313       HasInitializerList = true;
314     } else
315       Out << ", ";
316 
317     if (BMInitializer->isAnyMemberInitializer()) {
318       FieldDecl *FD = BMInitializer->getAnyMember();
319       Out << *FD;
320     } else {
321       Out << QualType(BMInitializer->getBaseClass(), 0).getAsString(Policy);
322     }
323 
324     Out << "(";
325     if (!BMInitializer->getInit()) {
326       // Nothing to print
327     } else {
328       Expr *Init = BMInitializer->getInit();
329       if (ExprWithCleanups *Tmp = dyn_cast<ExprWithCleanups>(Init))
330         Init = Tmp->getSubExpr();
331 
332       Init = Init->IgnoreParens();
333 
334       Expr *SimpleInit = nullptr;
335       Expr **Args = nullptr;
336       unsigned NumArgs = 0;
337       if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
338         Args = ParenList->getExprs();
339         NumArgs = ParenList->getNumExprs();
340       } else if (CXXConstructExpr *Construct =
341                      dyn_cast<CXXConstructExpr>(Init)) {
342         Args = Construct->getArgs();
343         NumArgs = Construct->getNumArgs();
344       } else
345         SimpleInit = Init;
346 
347       if (SimpleInit)
348         SimpleInit->printPretty(Out, nullptr, Policy, Indentation, "\n",
349                                 &Context);
350       else {
351         for (unsigned I = 0; I != NumArgs; ++I) {
352           assert(Args[I] != nullptr && "Expected non-null Expr");
353           if (isa<CXXDefaultArgExpr>(Args[I]))
354             break;
355 
356           if (I)
357             Out << ", ";
358           Args[I]->printPretty(Out, nullptr, Policy, Indentation, "\n",
359                                &Context);
360         }
361       }
362     }
363     Out << ")";
364     if (BMInitializer->isPackExpansion())
365       Out << "...";
366   }
367 }
368 
369 //----------------------------------------------------------------------------
370 // Common C declarations
371 //----------------------------------------------------------------------------
372 
VisitDeclContext(DeclContext * DC,bool Indent)373 void DeclPrinter::VisitDeclContext(DeclContext *DC, bool Indent) {
374   if (Policy.TerseOutput)
375     return;
376 
377   if (Indent)
378     Indentation += Policy.Indentation;
379 
380   SmallVector<Decl*, 2> Decls;
381   for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
382        D != DEnd; ++D) {
383 
384     // Don't print ObjCIvarDecls, as they are printed when visiting the
385     // containing ObjCInterfaceDecl.
386     if (isa<ObjCIvarDecl>(*D))
387       continue;
388 
389     // Skip over implicit declarations in pretty-printing mode.
390     if (D->isImplicit())
391       continue;
392 
393     // Don't print implicit specializations, as they are printed when visiting
394     // corresponding templates.
395     if (auto FD = dyn_cast<FunctionDecl>(*D))
396       if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
397           !isa<ClassTemplateSpecializationDecl>(DC))
398         continue;
399 
400     // The next bits of code handle stuff like "struct {int x;} a,b"; we're
401     // forced to merge the declarations because there's no other way to
402     // refer to the struct in question.  When that struct is named instead, we
403     // also need to merge to avoid splitting off a stand-alone struct
404     // declaration that produces the warning ext_no_declarators in some
405     // contexts.
406     //
407     // This limited merging is safe without a bunch of other checks because it
408     // only merges declarations directly referring to the tag, not typedefs.
409     //
410     // Check whether the current declaration should be grouped with a previous
411     // non-free-standing tag declaration.
412     QualType CurDeclType = getDeclType(*D);
413     if (!Decls.empty() && !CurDeclType.isNull()) {
414       QualType BaseType = GetBaseType(CurDeclType);
415       if (!BaseType.isNull() && isa<ElaboratedType>(BaseType) &&
416           cast<ElaboratedType>(BaseType)->getOwnedTagDecl() == Decls[0]) {
417         Decls.push_back(*D);
418         continue;
419       }
420     }
421 
422     // If we have a merged group waiting to be handled, handle it now.
423     if (!Decls.empty())
424       ProcessDeclGroup(Decls);
425 
426     // If the current declaration is not a free standing declaration, save it
427     // so we can merge it with the subsequent declaration(s) using it.
428     if (isa<TagDecl>(*D) && !cast<TagDecl>(*D)->isFreeStanding()) {
429       Decls.push_back(*D);
430       continue;
431     }
432 
433     if (isa<AccessSpecDecl>(*D)) {
434       Indentation -= Policy.Indentation;
435       this->Indent();
436       Print(D->getAccess());
437       Out << ":\n";
438       Indentation += Policy.Indentation;
439       continue;
440     }
441 
442     this->Indent();
443     Visit(*D);
444 
445     // FIXME: Need to be able to tell the DeclPrinter when
446     const char *Terminator = nullptr;
447     if (isa<OMPThreadPrivateDecl>(*D) || isa<OMPDeclareReductionDecl>(*D) ||
448         isa<OMPDeclareMapperDecl>(*D) || isa<OMPRequiresDecl>(*D) ||
449         isa<OMPAllocateDecl>(*D))
450       Terminator = nullptr;
451     else if (isa<ObjCMethodDecl>(*D) && cast<ObjCMethodDecl>(*D)->hasBody())
452       Terminator = nullptr;
453     else if (auto FD = dyn_cast<FunctionDecl>(*D)) {
454       if (FD->isThisDeclarationADefinition())
455         Terminator = nullptr;
456       else
457         Terminator = ";";
458     } else if (auto TD = dyn_cast<FunctionTemplateDecl>(*D)) {
459       if (TD->getTemplatedDecl()->isThisDeclarationADefinition())
460         Terminator = nullptr;
461       else
462         Terminator = ";";
463     } else if (isa<NamespaceDecl>(*D) || isa<LinkageSpecDecl>(*D) ||
464              isa<ObjCImplementationDecl>(*D) ||
465              isa<ObjCInterfaceDecl>(*D) ||
466              isa<ObjCProtocolDecl>(*D) ||
467              isa<ObjCCategoryImplDecl>(*D) ||
468              isa<ObjCCategoryDecl>(*D))
469       Terminator = nullptr;
470     else if (isa<EnumConstantDecl>(*D)) {
471       DeclContext::decl_iterator Next = D;
472       ++Next;
473       if (Next != DEnd)
474         Terminator = ",";
475     } else
476       Terminator = ";";
477 
478     if (Terminator)
479       Out << Terminator;
480     if (!Policy.TerseOutput &&
481         ((isa<FunctionDecl>(*D) &&
482           cast<FunctionDecl>(*D)->doesThisDeclarationHaveABody()) ||
483          (isa<FunctionTemplateDecl>(*D) &&
484           cast<FunctionTemplateDecl>(*D)->getTemplatedDecl()->doesThisDeclarationHaveABody())))
485       ; // StmtPrinter already added '\n' after CompoundStmt.
486     else
487       Out << "\n";
488 
489     // Declare target attribute is special one, natural spelling for the pragma
490     // assumes "ending" construct so print it here.
491     if (D->hasAttr<OMPDeclareTargetDeclAttr>())
492       Out << "#pragma omp end declare target\n";
493   }
494 
495   if (!Decls.empty())
496     ProcessDeclGroup(Decls);
497 
498   if (Indent)
499     Indentation -= Policy.Indentation;
500 }
501 
VisitTranslationUnitDecl(TranslationUnitDecl * D)502 void DeclPrinter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
503   VisitDeclContext(D, false);
504 }
505 
VisitTypedefDecl(TypedefDecl * D)506 void DeclPrinter::VisitTypedefDecl(TypedefDecl *D) {
507   if (!Policy.SuppressSpecifiers) {
508     Out << "typedef ";
509 
510     if (D->isModulePrivate())
511       Out << "__module_private__ ";
512   }
513   QualType Ty = D->getTypeSourceInfo()->getType();
514   Ty.print(Out, Policy, D->getName(), Indentation);
515   prettyPrintAttributes(D);
516 }
517 
VisitTypeAliasDecl(TypeAliasDecl * D)518 void DeclPrinter::VisitTypeAliasDecl(TypeAliasDecl *D) {
519   Out << "using " << *D;
520   prettyPrintAttributes(D);
521   Out << " = " << D->getTypeSourceInfo()->getType().getAsString(Policy);
522 }
523 
VisitEnumDecl(EnumDecl * D)524 void DeclPrinter::VisitEnumDecl(EnumDecl *D) {
525   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
526     Out << "__module_private__ ";
527   Out << "enum";
528   if (D->isScoped()) {
529     if (D->isScopedUsingClassTag())
530       Out << " class";
531     else
532       Out << " struct";
533   }
534 
535   prettyPrintAttributes(D);
536 
537   if (D->getDeclName())
538     Out << ' ' << D->getDeclName();
539 
540   if (D->isFixed())
541     Out << " : " << D->getIntegerType().stream(Policy);
542 
543   if (D->isCompleteDefinition()) {
544     Out << " {\n";
545     VisitDeclContext(D);
546     Indent() << "}";
547   }
548 }
549 
VisitRecordDecl(RecordDecl * D)550 void DeclPrinter::VisitRecordDecl(RecordDecl *D) {
551   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
552     Out << "__module_private__ ";
553   Out << D->getKindName();
554 
555   prettyPrintAttributes(D);
556 
557   if (D->getIdentifier())
558     Out << ' ' << *D;
559 
560   if (D->isCompleteDefinition()) {
561     Out << " {\n";
562     VisitDeclContext(D);
563     Indent() << "}";
564   }
565 }
566 
VisitEnumConstantDecl(EnumConstantDecl * D)567 void DeclPrinter::VisitEnumConstantDecl(EnumConstantDecl *D) {
568   Out << *D;
569   prettyPrintAttributes(D);
570   if (Expr *Init = D->getInitExpr()) {
571     Out << " = ";
572     Init->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context);
573   }
574 }
575 
printExplicitSpecifier(ExplicitSpecifier ES,llvm::raw_ostream & Out,PrintingPolicy & Policy,unsigned Indentation,const ASTContext & Context)576 static void printExplicitSpecifier(ExplicitSpecifier ES, llvm::raw_ostream &Out,
577                                    PrintingPolicy &Policy, unsigned Indentation,
578                                    const ASTContext &Context) {
579   std::string Proto = "explicit";
580   llvm::raw_string_ostream EOut(Proto);
581   if (ES.getExpr()) {
582     EOut << "(";
583     ES.getExpr()->printPretty(EOut, nullptr, Policy, Indentation, "\n",
584                               &Context);
585     EOut << ")";
586   }
587   EOut << " ";
588   EOut.flush();
589   Out << EOut.str();
590 }
591 
VisitFunctionDecl(FunctionDecl * D)592 void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) {
593   if (!D->getDescribedFunctionTemplate() &&
594       !D->isFunctionTemplateSpecialization())
595     prettyPrintPragmas(D);
596 
597   if (D->isFunctionTemplateSpecialization())
598     Out << "template<> ";
599   else if (!D->getDescribedFunctionTemplate()) {
600     for (unsigned I = 0, NumTemplateParams = D->getNumTemplateParameterLists();
601          I < NumTemplateParams; ++I)
602       printTemplateParameters(D->getTemplateParameterList(I));
603   }
604 
605   CXXConstructorDecl *CDecl = dyn_cast<CXXConstructorDecl>(D);
606   CXXConversionDecl *ConversionDecl = dyn_cast<CXXConversionDecl>(D);
607   CXXDeductionGuideDecl *GuideDecl = dyn_cast<CXXDeductionGuideDecl>(D);
608   if (!Policy.SuppressSpecifiers) {
609     switch (D->getStorageClass()) {
610     case SC_None: break;
611     case SC_Extern: Out << "extern "; break;
612     case SC_Static: Out << "static "; break;
613     case SC_PrivateExtern: Out << "__private_extern__ "; break;
614     case SC_Auto: case SC_Register:
615       llvm_unreachable("invalid for functions");
616     }
617 
618     if (D->isInlineSpecified())  Out << "inline ";
619     if (D->isVirtualAsWritten()) Out << "virtual ";
620     if (D->isModulePrivate())    Out << "__module_private__ ";
621     if (D->isConstexprSpecified() && !D->isExplicitlyDefaulted())
622       Out << "constexpr ";
623     if (D->isConsteval())        Out << "consteval ";
624     ExplicitSpecifier ExplicitSpec = ExplicitSpecifier::getFromDecl(D);
625     if (ExplicitSpec.isSpecified())
626       printExplicitSpecifier(ExplicitSpec, Out, Policy, Indentation, Context);
627   }
628 
629   PrintingPolicy SubPolicy(Policy);
630   SubPolicy.SuppressSpecifiers = false;
631   std::string Proto;
632 
633   if (Policy.FullyQualifiedName) {
634     Proto += D->getQualifiedNameAsString();
635   } else {
636     llvm::raw_string_ostream OS(Proto);
637     if (!Policy.SuppressScope) {
638       if (const NestedNameSpecifier *NS = D->getQualifier()) {
639         NS->print(OS, Policy);
640       }
641     }
642     D->getNameInfo().printName(OS, Policy);
643   }
644 
645   if (GuideDecl)
646     Proto = GuideDecl->getDeducedTemplate()->getDeclName().getAsString();
647   if (D->isFunctionTemplateSpecialization()) {
648     llvm::raw_string_ostream POut(Proto);
649     DeclPrinter TArgPrinter(POut, SubPolicy, Context, Indentation);
650     const auto *TArgAsWritten = D->getTemplateSpecializationArgsAsWritten();
651     const TemplateParameterList *TPL = D->getTemplateSpecializationInfo()
652                                            ->getTemplate()
653                                            ->getTemplateParameters();
654     if (TArgAsWritten && !Policy.PrintCanonicalTypes)
655       TArgPrinter.printTemplateArguments(TArgAsWritten->arguments(), TPL,
656                                          /*TemplOverloaded*/ true);
657     else if (const TemplateArgumentList *TArgs =
658                  D->getTemplateSpecializationArgs())
659       TArgPrinter.printTemplateArguments(TArgs->asArray(), TPL,
660                                          /*TemplOverloaded*/ true);
661   }
662 
663   QualType Ty = D->getType();
664   while (const ParenType *PT = dyn_cast<ParenType>(Ty)) {
665     Proto = '(' + Proto + ')';
666     Ty = PT->getInnerType();
667   }
668 
669   if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
670     const FunctionProtoType *FT = nullptr;
671     if (D->hasWrittenPrototype())
672       FT = dyn_cast<FunctionProtoType>(AFT);
673 
674     Proto += "(";
675     if (FT) {
676       llvm::raw_string_ostream POut(Proto);
677       DeclPrinter ParamPrinter(POut, SubPolicy, Context, Indentation);
678       for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
679         if (i) POut << ", ";
680         ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
681       }
682 
683       if (FT->isVariadic()) {
684         if (D->getNumParams()) POut << ", ";
685         POut << "...";
686       }
687     } else if (D->doesThisDeclarationHaveABody() && !D->hasPrototype()) {
688       for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
689         if (i)
690           Proto += ", ";
691         Proto += D->getParamDecl(i)->getNameAsString();
692       }
693     }
694 
695     Proto += ")";
696 
697     if (FT) {
698       if (FT->isConst())
699         Proto += " const";
700       if (FT->isVolatile())
701         Proto += " volatile";
702       if (FT->isRestrict())
703         Proto += " restrict";
704 
705       switch (FT->getRefQualifier()) {
706       case RQ_None:
707         break;
708       case RQ_LValue:
709         Proto += " &";
710         break;
711       case RQ_RValue:
712         Proto += " &&";
713         break;
714       }
715     }
716 
717     if (FT && FT->hasDynamicExceptionSpec()) {
718       Proto += " throw(";
719       if (FT->getExceptionSpecType() == EST_MSAny)
720         Proto += "...";
721       else
722         for (unsigned I = 0, N = FT->getNumExceptions(); I != N; ++I) {
723           if (I)
724             Proto += ", ";
725 
726           Proto += FT->getExceptionType(I).getAsString(SubPolicy);
727         }
728       Proto += ")";
729     } else if (FT && isNoexceptExceptionSpec(FT->getExceptionSpecType())) {
730       Proto += " noexcept";
731       if (isComputedNoexcept(FT->getExceptionSpecType())) {
732         Proto += "(";
733         llvm::raw_string_ostream EOut(Proto);
734         FT->getNoexceptExpr()->printPretty(EOut, nullptr, SubPolicy,
735                                            Indentation, "\n", &Context);
736         EOut.flush();
737         Proto += EOut.str();
738         Proto += ")";
739       }
740     }
741 
742     if (CDecl) {
743       if (!Policy.TerseOutput)
744         PrintConstructorInitializers(CDecl, Proto);
745     } else if (!ConversionDecl && !isa<CXXDestructorDecl>(D)) {
746       if (FT && FT->hasTrailingReturn()) {
747         if (!GuideDecl)
748           Out << "auto ";
749         Out << Proto << " -> ";
750         Proto.clear();
751       }
752       AFT->getReturnType().print(Out, Policy, Proto);
753       Proto.clear();
754     }
755     Out << Proto;
756 
757     if (Expr *TrailingRequiresClause = D->getTrailingRequiresClause()) {
758       Out << " requires ";
759       TrailingRequiresClause->printPretty(Out, nullptr, SubPolicy, Indentation,
760                                           "\n", &Context);
761     }
762   } else {
763     Ty.print(Out, Policy, Proto);
764   }
765 
766   prettyPrintAttributes(D);
767 
768   if (D->isPure())
769     Out << " = 0";
770   else if (D->isDeletedAsWritten())
771     Out << " = delete";
772   else if (D->isExplicitlyDefaulted())
773     Out << " = default";
774   else if (D->doesThisDeclarationHaveABody()) {
775     if (!Policy.TerseOutput) {
776       if (!D->hasPrototype() && D->getNumParams()) {
777         // This is a K&R function definition, so we need to print the
778         // parameters.
779         Out << '\n';
780         DeclPrinter ParamPrinter(Out, SubPolicy, Context, Indentation);
781         Indentation += Policy.Indentation;
782         for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
783           Indent();
784           ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
785           Out << ";\n";
786         }
787         Indentation -= Policy.Indentation;
788       } else
789         Out << ' ';
790 
791       if (D->getBody())
792         D->getBody()->printPretty(Out, nullptr, SubPolicy, Indentation, "\n",
793                                   &Context);
794     } else {
795       if (!Policy.TerseOutput && isa<CXXConstructorDecl>(*D))
796         Out << " {}";
797     }
798   }
799 }
800 
VisitFriendDecl(FriendDecl * D)801 void DeclPrinter::VisitFriendDecl(FriendDecl *D) {
802   if (TypeSourceInfo *TSI = D->getFriendType()) {
803     unsigned NumTPLists = D->getFriendTypeNumTemplateParameterLists();
804     for (unsigned i = 0; i < NumTPLists; ++i)
805       printTemplateParameters(D->getFriendTypeTemplateParameterList(i));
806     Out << "friend ";
807     Out << " " << TSI->getType().getAsString(Policy);
808   }
809   else if (FunctionDecl *FD =
810       dyn_cast<FunctionDecl>(D->getFriendDecl())) {
811     Out << "friend ";
812     VisitFunctionDecl(FD);
813   }
814   else if (FunctionTemplateDecl *FTD =
815            dyn_cast<FunctionTemplateDecl>(D->getFriendDecl())) {
816     Out << "friend ";
817     VisitFunctionTemplateDecl(FTD);
818   }
819   else if (ClassTemplateDecl *CTD =
820            dyn_cast<ClassTemplateDecl>(D->getFriendDecl())) {
821     Out << "friend ";
822     VisitRedeclarableTemplateDecl(CTD);
823   }
824 }
825 
VisitFieldDecl(FieldDecl * D)826 void DeclPrinter::VisitFieldDecl(FieldDecl *D) {
827   // FIXME: add printing of pragma attributes if required.
828   if (!Policy.SuppressSpecifiers && D->isMutable())
829     Out << "mutable ";
830   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
831     Out << "__module_private__ ";
832 
833   Out << D->getASTContext().getUnqualifiedObjCPointerType(D->getType()).
834          stream(Policy, D->getName(), Indentation);
835 
836   if (D->isBitField()) {
837     Out << " : ";
838     D->getBitWidth()->printPretty(Out, nullptr, Policy, Indentation, "\n",
839                                   &Context);
840   }
841 
842   Expr *Init = D->getInClassInitializer();
843   if (!Policy.SuppressInitializers && Init) {
844     if (D->getInClassInitStyle() == ICIS_ListInit)
845       Out << " ";
846     else
847       Out << " = ";
848     Init->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context);
849   }
850   prettyPrintAttributes(D);
851 }
852 
VisitLabelDecl(LabelDecl * D)853 void DeclPrinter::VisitLabelDecl(LabelDecl *D) {
854   Out << *D << ":";
855 }
856 
VisitVarDecl(VarDecl * D)857 void DeclPrinter::VisitVarDecl(VarDecl *D) {
858   prettyPrintPragmas(D);
859 
860   QualType T = D->getTypeSourceInfo()
861     ? D->getTypeSourceInfo()->getType()
862     : D->getASTContext().getUnqualifiedObjCPointerType(D->getType());
863 
864   if (!Policy.SuppressSpecifiers) {
865     StorageClass SC = D->getStorageClass();
866     if (SC != SC_None)
867       Out << VarDecl::getStorageClassSpecifierString(SC) << " ";
868 
869     switch (D->getTSCSpec()) {
870     case TSCS_unspecified:
871       break;
872     case TSCS___thread:
873       Out << "__thread ";
874       break;
875     case TSCS__Thread_local:
876       Out << "_Thread_local ";
877       break;
878     case TSCS_thread_local:
879       Out << "thread_local ";
880       break;
881     }
882 
883     if (D->isModulePrivate())
884       Out << "__module_private__ ";
885 
886     if (D->isConstexpr()) {
887       Out << "constexpr ";
888       T.removeLocalConst();
889     }
890   }
891 
892   printDeclType(T, D->getName());
893   Expr *Init = D->getInit();
894   if (!Policy.SuppressInitializers && Init) {
895     bool ImplicitInit = false;
896     if (CXXConstructExpr *Construct =
897             dyn_cast<CXXConstructExpr>(Init->IgnoreImplicit())) {
898       if (D->getInitStyle() == VarDecl::CallInit &&
899           !Construct->isListInitialization()) {
900         ImplicitInit = Construct->getNumArgs() == 0 ||
901           Construct->getArg(0)->isDefaultArgument();
902       }
903     }
904     if (!ImplicitInit) {
905       if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
906         Out << "(";
907       else if (D->getInitStyle() == VarDecl::CInit) {
908         Out << " = ";
909       }
910       PrintingPolicy SubPolicy(Policy);
911       SubPolicy.SuppressSpecifiers = false;
912       SubPolicy.IncludeTagDefinition = false;
913       Init->printPretty(Out, nullptr, SubPolicy, Indentation, "\n", &Context);
914       if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
915         Out << ")";
916     }
917   }
918   prettyPrintAttributes(D);
919 }
920 
VisitParmVarDecl(ParmVarDecl * D)921 void DeclPrinter::VisitParmVarDecl(ParmVarDecl *D) {
922   VisitVarDecl(D);
923 }
924 
VisitFileScopeAsmDecl(FileScopeAsmDecl * D)925 void DeclPrinter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) {
926   Out << "__asm (";
927   D->getAsmString()->printPretty(Out, nullptr, Policy, Indentation, "\n",
928                                  &Context);
929   Out << ")";
930 }
931 
VisitImportDecl(ImportDecl * D)932 void DeclPrinter::VisitImportDecl(ImportDecl *D) {
933   Out << "@import " << D->getImportedModule()->getFullModuleName()
934       << ";\n";
935 }
936 
VisitStaticAssertDecl(StaticAssertDecl * D)937 void DeclPrinter::VisitStaticAssertDecl(StaticAssertDecl *D) {
938   Out << "static_assert(";
939   D->getAssertExpr()->printPretty(Out, nullptr, Policy, Indentation, "\n",
940                                   &Context);
941   if (StringLiteral *SL = D->getMessage()) {
942     Out << ", ";
943     SL->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context);
944   }
945   Out << ")";
946 }
947 
948 //----------------------------------------------------------------------------
949 // C++ declarations
950 //----------------------------------------------------------------------------
VisitNamespaceDecl(NamespaceDecl * D)951 void DeclPrinter::VisitNamespaceDecl(NamespaceDecl *D) {
952   if (D->isInline())
953     Out << "inline ";
954 
955   Out << "namespace ";
956   if (D->getDeclName())
957     Out << D->getDeclName() << ' ';
958   Out << "{\n";
959 
960   VisitDeclContext(D);
961   Indent() << "}";
962 }
963 
VisitUsingDirectiveDecl(UsingDirectiveDecl * D)964 void DeclPrinter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
965   Out << "using namespace ";
966   if (D->getQualifier())
967     D->getQualifier()->print(Out, Policy);
968   Out << *D->getNominatedNamespaceAsWritten();
969 }
970 
VisitNamespaceAliasDecl(NamespaceAliasDecl * D)971 void DeclPrinter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
972   Out << "namespace " << *D << " = ";
973   if (D->getQualifier())
974     D->getQualifier()->print(Out, Policy);
975   Out << *D->getAliasedNamespace();
976 }
977 
VisitEmptyDecl(EmptyDecl * D)978 void DeclPrinter::VisitEmptyDecl(EmptyDecl *D) {
979   prettyPrintAttributes(D);
980 }
981 
VisitCXXRecordDecl(CXXRecordDecl * D)982 void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) {
983   // FIXME: add printing of pragma attributes if required.
984   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
985     Out << "__module_private__ ";
986   Out << D->getKindName();
987 
988   prettyPrintAttributes(D);
989 
990   if (D->getIdentifier()) {
991     Out << ' ' << *D;
992 
993     if (auto S = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
994       ArrayRef<TemplateArgument> Args = S->getTemplateArgs().asArray();
995       if (!Policy.PrintCanonicalTypes)
996         if (const auto* TSI = S->getTypeAsWritten())
997           if (const auto *TST =
998                   dyn_cast<TemplateSpecializationType>(TSI->getType()))
999             Args = TST->template_arguments();
1000       printTemplateArguments(
1001           Args, S->getSpecializedTemplate()->getTemplateParameters(),
1002           /*TemplOverloaded*/ false);
1003     }
1004   }
1005 
1006   if (D->isCompleteDefinition()) {
1007     // Print the base classes
1008     if (D->getNumBases()) {
1009       Out << " : ";
1010       for (CXXRecordDecl::base_class_iterator Base = D->bases_begin(),
1011              BaseEnd = D->bases_end(); Base != BaseEnd; ++Base) {
1012         if (Base != D->bases_begin())
1013           Out << ", ";
1014 
1015         if (Base->isVirtual())
1016           Out << "virtual ";
1017 
1018         AccessSpecifier AS = Base->getAccessSpecifierAsWritten();
1019         if (AS != AS_none) {
1020           Print(AS);
1021           Out << " ";
1022         }
1023         Out << Base->getType().getAsString(Policy);
1024 
1025         if (Base->isPackExpansion())
1026           Out << "...";
1027       }
1028     }
1029 
1030     // Print the class definition
1031     // FIXME: Doesn't print access specifiers, e.g., "public:"
1032     if (Policy.TerseOutput) {
1033       Out << " {}";
1034     } else {
1035       Out << " {\n";
1036       VisitDeclContext(D);
1037       Indent() << "}";
1038     }
1039   }
1040 }
1041 
VisitLinkageSpecDecl(LinkageSpecDecl * D)1042 void DeclPrinter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1043   const char *l;
1044   if (D->getLanguage() == LinkageSpecDecl::lang_c)
1045     l = "C";
1046   else {
1047     assert(D->getLanguage() == LinkageSpecDecl::lang_cxx &&
1048            "unknown language in linkage specification");
1049     l = "C++";
1050   }
1051 
1052   Out << "extern \"" << l << "\" ";
1053   if (D->hasBraces()) {
1054     Out << "{\n";
1055     VisitDeclContext(D);
1056     Indent() << "}";
1057   } else
1058     Visit(*D->decls_begin());
1059 }
1060 
printTemplateParameters(const TemplateParameterList * Params,bool OmitTemplateKW)1061 void DeclPrinter::printTemplateParameters(const TemplateParameterList *Params,
1062                                           bool OmitTemplateKW) {
1063   assert(Params);
1064 
1065   if (!OmitTemplateKW)
1066     Out << "template ";
1067   Out << '<';
1068 
1069   bool NeedComma = false;
1070   for (const Decl *Param : *Params) {
1071     if (Param->isImplicit())
1072       continue;
1073 
1074     if (NeedComma)
1075       Out << ", ";
1076     else
1077       NeedComma = true;
1078 
1079     if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
1080       VisitTemplateTypeParmDecl(TTP);
1081     } else if (auto NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1082       VisitNonTypeTemplateParmDecl(NTTP);
1083     } else if (auto TTPD = dyn_cast<TemplateTemplateParmDecl>(Param)) {
1084       VisitTemplateDecl(TTPD);
1085       // FIXME: print the default argument, if present.
1086     }
1087   }
1088 
1089   Out << '>';
1090   if (!OmitTemplateKW)
1091     Out << ' ';
1092 }
1093 
printTemplateArguments(ArrayRef<TemplateArgument> Args,const TemplateParameterList * Params,bool TemplOverloaded)1094 void DeclPrinter::printTemplateArguments(ArrayRef<TemplateArgument> Args,
1095                                          const TemplateParameterList *Params,
1096                                          bool TemplOverloaded) {
1097   Out << "<";
1098   for (size_t I = 0, E = Args.size(); I < E; ++I) {
1099     if (I)
1100       Out << ", ";
1101     if (TemplOverloaded || !Params)
1102       Args[I].print(Policy, Out, /*IncludeType*/ true);
1103     else
1104       Args[I].print(
1105           Policy, Out,
1106           TemplateParameterList::shouldIncludeTypeForArgument(Params, I));
1107   }
1108   Out << ">";
1109 }
1110 
printTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,const TemplateParameterList * Params,bool TemplOverloaded)1111 void DeclPrinter::printTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
1112                                          const TemplateParameterList *Params,
1113                                          bool TemplOverloaded) {
1114   Out << "<";
1115   for (size_t I = 0, E = Args.size(); I < E; ++I) {
1116     if (I)
1117       Out << ", ";
1118     if (TemplOverloaded)
1119       Args[I].getArgument().print(Policy, Out, /*IncludeType*/ true);
1120     else
1121       Args[I].getArgument().print(
1122           Policy, Out,
1123           TemplateParameterList::shouldIncludeTypeForArgument(Params, I));
1124   }
1125   Out << ">";
1126 }
1127 
VisitTemplateDecl(const TemplateDecl * D)1128 void DeclPrinter::VisitTemplateDecl(const TemplateDecl *D) {
1129   printTemplateParameters(D->getTemplateParameters());
1130 
1131   if (const TemplateTemplateParmDecl *TTP =
1132         dyn_cast<TemplateTemplateParmDecl>(D)) {
1133     Out << "class";
1134 
1135     if (TTP->isParameterPack())
1136       Out << " ...";
1137     else if (TTP->getDeclName())
1138       Out << ' ';
1139 
1140     if (TTP->getDeclName())
1141       Out << TTP->getDeclName();
1142   } else if (auto *TD = D->getTemplatedDecl())
1143     Visit(TD);
1144   else if (const auto *Concept = dyn_cast<ConceptDecl>(D)) {
1145     Out << "concept " << Concept->getName() << " = " ;
1146     Concept->getConstraintExpr()->printPretty(Out, nullptr, Policy, Indentation,
1147                                               "\n", &Context);
1148     Out << ";";
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 
1612 void
VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl * D)1613 DeclPrinter::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
1614   Out << "using typename ";
1615   D->getQualifier()->print(Out, Policy);
1616   Out << D->getDeclName();
1617 }
1618 
VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl * D)1619 void DeclPrinter::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1620   if (!D->isAccessDeclaration())
1621     Out << "using ";
1622   D->getQualifier()->print(Out, Policy);
1623   Out << D->getDeclName();
1624 }
1625 
VisitUsingShadowDecl(UsingShadowDecl * D)1626 void DeclPrinter::VisitUsingShadowDecl(UsingShadowDecl *D) {
1627   // ignore
1628 }
1629 
VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl * D)1630 void DeclPrinter::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
1631   Out << "#pragma omp threadprivate";
1632   if (!D->varlist_empty()) {
1633     for (OMPThreadPrivateDecl::varlist_iterator I = D->varlist_begin(),
1634                                                 E = D->varlist_end();
1635                                                 I != E; ++I) {
1636       Out << (I == D->varlist_begin() ? '(' : ',');
1637       NamedDecl *ND = cast<DeclRefExpr>(*I)->getDecl();
1638       ND->printQualifiedName(Out);
1639     }
1640     Out << ")";
1641   }
1642 }
1643 
VisitOMPAllocateDecl(OMPAllocateDecl * D)1644 void DeclPrinter::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
1645   Out << "#pragma omp allocate";
1646   if (!D->varlist_empty()) {
1647     for (OMPAllocateDecl::varlist_iterator I = D->varlist_begin(),
1648                                            E = D->varlist_end();
1649          I != E; ++I) {
1650       Out << (I == D->varlist_begin() ? '(' : ',');
1651       NamedDecl *ND = cast<DeclRefExpr>(*I)->getDecl();
1652       ND->printQualifiedName(Out);
1653     }
1654     Out << ")";
1655   }
1656   if (!D->clauselist_empty()) {
1657     Out << " ";
1658     OMPClausePrinter Printer(Out, Policy);
1659     for (OMPClause *C : D->clauselists())
1660       Printer.Visit(C);
1661   }
1662 }
1663 
VisitOMPRequiresDecl(OMPRequiresDecl * D)1664 void DeclPrinter::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
1665   Out << "#pragma omp requires ";
1666   if (!D->clauselist_empty()) {
1667     OMPClausePrinter Printer(Out, Policy);
1668     for (auto I = D->clauselist_begin(), E = D->clauselist_end(); I != E; ++I)
1669       Printer.Visit(*I);
1670   }
1671 }
1672 
VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl * D)1673 void DeclPrinter::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
1674   if (!D->isInvalidDecl()) {
1675     Out << "#pragma omp declare reduction (";
1676     if (D->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) {
1677       const char *OpName =
1678           getOperatorSpelling(D->getDeclName().getCXXOverloadedOperator());
1679       assert(OpName && "not an overloaded operator");
1680       Out << OpName;
1681     } else {
1682       assert(D->getDeclName().isIdentifier());
1683       D->printName(Out);
1684     }
1685     Out << " : ";
1686     D->getType().print(Out, Policy);
1687     Out << " : ";
1688     D->getCombiner()->printPretty(Out, nullptr, Policy, 0, "\n", &Context);
1689     Out << ")";
1690     if (auto *Init = D->getInitializer()) {
1691       Out << " initializer(";
1692       switch (D->getInitializerKind()) {
1693       case OMPDeclareReductionDecl::DirectInit:
1694         Out << "omp_priv(";
1695         break;
1696       case OMPDeclareReductionDecl::CopyInit:
1697         Out << "omp_priv = ";
1698         break;
1699       case OMPDeclareReductionDecl::CallInit:
1700         break;
1701       }
1702       Init->printPretty(Out, nullptr, Policy, 0, "\n", &Context);
1703       if (D->getInitializerKind() == OMPDeclareReductionDecl::DirectInit)
1704         Out << ")";
1705       Out << ")";
1706     }
1707   }
1708 }
1709 
VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl * D)1710 void DeclPrinter::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
1711   if (!D->isInvalidDecl()) {
1712     Out << "#pragma omp declare mapper (";
1713     D->printName(Out);
1714     Out << " : ";
1715     D->getType().print(Out, Policy);
1716     Out << " ";
1717     Out << D->getVarName();
1718     Out << ")";
1719     if (!D->clauselist_empty()) {
1720       OMPClausePrinter Printer(Out, Policy);
1721       for (auto *C : D->clauselists()) {
1722         Out << " ";
1723         Printer.Visit(C);
1724       }
1725     }
1726   }
1727 }
1728 
VisitOMPCapturedExprDecl(OMPCapturedExprDecl * D)1729 void DeclPrinter::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
1730   D->getInit()->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context);
1731 }
1732 
VisitTemplateTypeParmDecl(const TemplateTypeParmDecl * TTP)1733 void DeclPrinter::VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *TTP) {
1734   if (const TypeConstraint *TC = TTP->getTypeConstraint())
1735     TC->print(Out, Policy);
1736   else if (TTP->wasDeclaredWithTypename())
1737     Out << "typename";
1738   else
1739     Out << "class";
1740 
1741   if (TTP->isParameterPack())
1742     Out << " ...";
1743   else if (TTP->getDeclName())
1744     Out << ' ';
1745 
1746   if (TTP->getDeclName())
1747     Out << TTP->getDeclName();
1748 
1749   if (TTP->hasDefaultArgument()) {
1750     Out << " = ";
1751     Out << TTP->getDefaultArgument().getAsString(Policy);
1752   }
1753 }
1754 
VisitNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl * NTTP)1755 void DeclPrinter::VisitNonTypeTemplateParmDecl(
1756     const NonTypeTemplateParmDecl *NTTP) {
1757   StringRef Name;
1758   if (IdentifierInfo *II = NTTP->getIdentifier())
1759     Name = II->getName();
1760   printDeclType(NTTP->getType(), Name, NTTP->isParameterPack());
1761 
1762   if (NTTP->hasDefaultArgument()) {
1763     Out << " = ";
1764     NTTP->getDefaultArgument()->printPretty(Out, nullptr, Policy, Indentation,
1765                                             "\n", &Context);
1766   }
1767 }
1768