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