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