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