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