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   public:
41     DeclPrinter(raw_ostream &Out, const PrintingPolicy &Policy,
42                 unsigned Indentation = 0, bool PrintInstantiation = false)
43       : Out(Out), Policy(Policy), Indentation(Indentation),
44         PrintInstantiation(PrintInstantiation) { }
45 
46     void VisitDeclContext(DeclContext *DC, bool Indent = true);
47 
48     void VisitTranslationUnitDecl(TranslationUnitDecl *D);
49     void VisitTypedefDecl(TypedefDecl *D);
50     void VisitTypeAliasDecl(TypeAliasDecl *D);
51     void VisitEnumDecl(EnumDecl *D);
52     void VisitRecordDecl(RecordDecl *D);
53     void VisitEnumConstantDecl(EnumConstantDecl *D);
54     void VisitEmptyDecl(EmptyDecl *D);
55     void VisitFunctionDecl(FunctionDecl *D);
56     void VisitFriendDecl(FriendDecl *D);
57     void VisitFieldDecl(FieldDecl *D);
58     void VisitVarDecl(VarDecl *D);
59     void VisitLabelDecl(LabelDecl *D);
60     void VisitParmVarDecl(ParmVarDecl *D);
61     void VisitFileScopeAsmDecl(FileScopeAsmDecl *D);
62     void VisitImportDecl(ImportDecl *D);
63     void VisitStaticAssertDecl(StaticAssertDecl *D);
64     void VisitNamespaceDecl(NamespaceDecl *D);
65     void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
66     void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
67     void VisitCXXRecordDecl(CXXRecordDecl *D);
68     void VisitLinkageSpecDecl(LinkageSpecDecl *D);
69     void VisitTemplateDecl(const TemplateDecl *D);
70     void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
71     void VisitClassTemplateDecl(ClassTemplateDecl *D);
72     void VisitObjCMethodDecl(ObjCMethodDecl *D);
73     void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
74     void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
75     void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
76     void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
77     void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
78     void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
79     void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
80     void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
81     void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
82     void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
83     void VisitUsingDecl(UsingDecl *D);
84     void VisitUsingShadowDecl(UsingShadowDecl *D);
85     void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
86 
87     void PrintTemplateParameters(const TemplateParameterList *Params,
88                                  const TemplateArgumentList *Args = nullptr);
89     void prettyPrintAttributes(Decl *D);
90     void printDeclType(QualType T, StringRef DeclName, bool Pack = false);
91   };
92 }
93 
94 void Decl::print(raw_ostream &Out, unsigned Indentation,
95                  bool PrintInstantiation) const {
96   print(Out, getASTContext().getPrintingPolicy(), Indentation, PrintInstantiation);
97 }
98 
99 void Decl::print(raw_ostream &Out, const PrintingPolicy &Policy,
100                  unsigned Indentation, bool PrintInstantiation) const {
101   DeclPrinter Printer(Out, Policy, Indentation, PrintInstantiation);
102   Printer.Visit(const_cast<Decl*>(this));
103 }
104 
105 static QualType GetBaseType(QualType T) {
106   // FIXME: This should be on the Type class!
107   QualType BaseType = T;
108   while (!BaseType->isSpecifierType()) {
109     if (isa<TypedefType>(BaseType))
110       break;
111     else if (const PointerType* PTy = BaseType->getAs<PointerType>())
112       BaseType = PTy->getPointeeType();
113     else if (const BlockPointerType *BPy = BaseType->getAs<BlockPointerType>())
114       BaseType = BPy->getPointeeType();
115     else if (const ArrayType* ATy = dyn_cast<ArrayType>(BaseType))
116       BaseType = ATy->getElementType();
117     else if (const FunctionType* FTy = BaseType->getAs<FunctionType>())
118       BaseType = FTy->getReturnType();
119     else if (const VectorType *VTy = BaseType->getAs<VectorType>())
120       BaseType = VTy->getElementType();
121     else if (const ReferenceType *RTy = BaseType->getAs<ReferenceType>())
122       BaseType = RTy->getPointeeType();
123     else
124       llvm_unreachable("Unknown declarator!");
125   }
126   return BaseType;
127 }
128 
129 static QualType getDeclType(Decl* D) {
130   if (TypedefNameDecl* TDD = dyn_cast<TypedefNameDecl>(D))
131     return TDD->getUnderlyingType();
132   if (ValueDecl* VD = dyn_cast<ValueDecl>(D))
133     return VD->getType();
134   return QualType();
135 }
136 
137 void Decl::printGroup(Decl** Begin, unsigned NumDecls,
138                       raw_ostream &Out, const PrintingPolicy &Policy,
139                       unsigned Indentation) {
140   if (NumDecls == 1) {
141     (*Begin)->print(Out, Policy, Indentation);
142     return;
143   }
144 
145   Decl** End = Begin + NumDecls;
146   TagDecl* TD = dyn_cast<TagDecl>(*Begin);
147   if (TD)
148     ++Begin;
149 
150   PrintingPolicy SubPolicy(Policy);
151   if (TD && TD->isCompleteDefinition()) {
152     TD->print(Out, Policy, Indentation);
153     Out << " ";
154     SubPolicy.SuppressTag = true;
155   }
156 
157   bool isFirst = true;
158   for ( ; Begin != End; ++Begin) {
159     if (isFirst) {
160       SubPolicy.SuppressSpecifiers = false;
161       isFirst = false;
162     } else {
163       if (!isFirst) Out << ", ";
164       SubPolicy.SuppressSpecifiers = true;
165     }
166 
167     (*Begin)->print(Out, SubPolicy, Indentation);
168   }
169 }
170 
171 LLVM_DUMP_METHOD void DeclContext::dumpDeclContext() const {
172   // Get the translation unit
173   const DeclContext *DC = this;
174   while (!DC->isTranslationUnit())
175     DC = DC->getParent();
176 
177   ASTContext &Ctx = cast<TranslationUnitDecl>(DC)->getASTContext();
178   DeclPrinter Printer(llvm::errs(), Ctx.getPrintingPolicy(), 0);
179   Printer.VisitDeclContext(const_cast<DeclContext *>(this), /*Indent=*/false);
180 }
181 
182 raw_ostream& DeclPrinter::Indent(unsigned Indentation) {
183   for (unsigned i = 0; i != Indentation; ++i)
184     Out << "  ";
185   return Out;
186 }
187 
188 void DeclPrinter::prettyPrintAttributes(Decl *D) {
189   if (Policy.PolishForDeclaration)
190     return;
191 
192   if (D->hasAttrs()) {
193     AttrVec &Attrs = D->getAttrs();
194     for (AttrVec::const_iterator i=Attrs.begin(), e=Attrs.end(); i!=e; ++i) {
195       Attr *A = *i;
196       A->printPretty(Out, Policy);
197     }
198   }
199 }
200 
201 void DeclPrinter::printDeclType(QualType T, StringRef DeclName, bool Pack) {
202   // Normally, a PackExpansionType is written as T[3]... (for instance, as a
203   // template argument), but if it is the type of a declaration, the ellipsis
204   // is placed before the name being declared.
205   if (auto *PET = T->getAs<PackExpansionType>()) {
206     Pack = true;
207     T = PET->getPattern();
208   }
209   T.print(Out, Policy, (Pack ? "..." : "") + DeclName);
210 }
211 
212 void DeclPrinter::ProcessDeclGroup(SmallVectorImpl<Decl*>& Decls) {
213   this->Indent();
214   Decl::printGroup(Decls.data(), Decls.size(), Out, Policy, Indentation);
215   Out << ";\n";
216   Decls.clear();
217 
218 }
219 
220 void DeclPrinter::Print(AccessSpecifier AS) {
221   switch(AS) {
222   case AS_none:      llvm_unreachable("No access specifier!");
223   case AS_public:    Out << "public"; break;
224   case AS_protected: Out << "protected"; break;
225   case AS_private:   Out << "private"; break;
226   }
227 }
228 
229 //----------------------------------------------------------------------------
230 // Common C declarations
231 //----------------------------------------------------------------------------
232 
233 void DeclPrinter::VisitDeclContext(DeclContext *DC, bool Indent) {
234   if (Policy.TerseOutput)
235     return;
236 
237   if (Indent)
238     Indentation += Policy.Indentation;
239 
240   SmallVector<Decl*, 2> Decls;
241   for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
242        D != DEnd; ++D) {
243 
244     // Don't print ObjCIvarDecls, as they are printed when visiting the
245     // containing ObjCInterfaceDecl.
246     if (isa<ObjCIvarDecl>(*D))
247       continue;
248 
249     // Skip over implicit declarations in pretty-printing mode.
250     if (D->isImplicit())
251       continue;
252 
253     // The next bits of code handles stuff like "struct {int x;} a,b"; we're
254     // forced to merge the declarations because there's no other way to
255     // refer to the struct in question.  This limited merging is safe without
256     // a bunch of other checks because it only merges declarations directly
257     // referring to the tag, not typedefs.
258     //
259     // Check whether the current declaration should be grouped with a previous
260     // unnamed struct.
261     QualType CurDeclType = getDeclType(*D);
262     if (!Decls.empty() && !CurDeclType.isNull()) {
263       QualType BaseType = GetBaseType(CurDeclType);
264       if (!BaseType.isNull() && isa<ElaboratedType>(BaseType))
265         BaseType = cast<ElaboratedType>(BaseType)->getNamedType();
266       if (!BaseType.isNull() && isa<TagType>(BaseType) &&
267           cast<TagType>(BaseType)->getDecl() == Decls[0]) {
268         Decls.push_back(*D);
269         continue;
270       }
271     }
272 
273     // If we have a merged group waiting to be handled, handle it now.
274     if (!Decls.empty())
275       ProcessDeclGroup(Decls);
276 
277     // If the current declaration is an unnamed tag type, save it
278     // so we can merge it with the subsequent declaration(s) using it.
279     if (isa<TagDecl>(*D) && !cast<TagDecl>(*D)->getIdentifier()) {
280       Decls.push_back(*D);
281       continue;
282     }
283 
284     if (isa<AccessSpecDecl>(*D)) {
285       Indentation -= Policy.Indentation;
286       this->Indent();
287       Print(D->getAccess());
288       Out << ":\n";
289       Indentation += Policy.Indentation;
290       continue;
291     }
292 
293     this->Indent();
294     Visit(*D);
295 
296     // FIXME: Need to be able to tell the DeclPrinter when
297     const char *Terminator = nullptr;
298     if (isa<OMPThreadPrivateDecl>(*D))
299       Terminator = nullptr;
300     else if (isa<FunctionDecl>(*D) &&
301              cast<FunctionDecl>(*D)->isThisDeclarationADefinition())
302       Terminator = nullptr;
303     else if (isa<ObjCMethodDecl>(*D) && cast<ObjCMethodDecl>(*D)->getBody())
304       Terminator = nullptr;
305     else if (isa<NamespaceDecl>(*D) || isa<LinkageSpecDecl>(*D) ||
306              isa<ObjCImplementationDecl>(*D) ||
307              isa<ObjCInterfaceDecl>(*D) ||
308              isa<ObjCProtocolDecl>(*D) ||
309              isa<ObjCCategoryImplDecl>(*D) ||
310              isa<ObjCCategoryDecl>(*D))
311       Terminator = nullptr;
312     else if (isa<EnumConstantDecl>(*D)) {
313       DeclContext::decl_iterator Next = D;
314       ++Next;
315       if (Next != DEnd)
316         Terminator = ",";
317     } else
318       Terminator = ";";
319 
320     if (Terminator)
321       Out << Terminator;
322     Out << "\n";
323   }
324 
325   if (!Decls.empty())
326     ProcessDeclGroup(Decls);
327 
328   if (Indent)
329     Indentation -= Policy.Indentation;
330 }
331 
332 void DeclPrinter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
333   VisitDeclContext(D, false);
334 }
335 
336 void DeclPrinter::VisitTypedefDecl(TypedefDecl *D) {
337   if (!Policy.SuppressSpecifiers) {
338     Out << "typedef ";
339 
340     if (D->isModulePrivate())
341       Out << "__module_private__ ";
342   }
343   D->getTypeSourceInfo()->getType().print(Out, Policy, D->getName());
344   prettyPrintAttributes(D);
345 }
346 
347 void DeclPrinter::VisitTypeAliasDecl(TypeAliasDecl *D) {
348   Out << "using " << *D;
349   prettyPrintAttributes(D);
350   Out << " = " << D->getTypeSourceInfo()->getType().getAsString(Policy);
351 }
352 
353 void DeclPrinter::VisitEnumDecl(EnumDecl *D) {
354   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
355     Out << "__module_private__ ";
356   Out << "enum ";
357   if (D->isScoped()) {
358     if (D->isScopedUsingClassTag())
359       Out << "class ";
360     else
361       Out << "struct ";
362   }
363   Out << *D;
364 
365   if (D->isFixed())
366     Out << " : " << D->getIntegerType().stream(Policy);
367 
368   if (D->isCompleteDefinition()) {
369     Out << " {\n";
370     VisitDeclContext(D);
371     Indent() << "}";
372   }
373   prettyPrintAttributes(D);
374 }
375 
376 void DeclPrinter::VisitRecordDecl(RecordDecl *D) {
377   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
378     Out << "__module_private__ ";
379   Out << D->getKindName();
380   if (D->getIdentifier())
381     Out << ' ' << *D;
382 
383   if (D->isCompleteDefinition()) {
384     Out << " {\n";
385     VisitDeclContext(D);
386     Indent() << "}";
387   }
388 }
389 
390 void DeclPrinter::VisitEnumConstantDecl(EnumConstantDecl *D) {
391   Out << *D;
392   if (Expr *Init = D->getInitExpr()) {
393     Out << " = ";
394     Init->printPretty(Out, nullptr, Policy, Indentation);
395   }
396 }
397 
398 void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) {
399   CXXConstructorDecl *CDecl = dyn_cast<CXXConstructorDecl>(D);
400   CXXConversionDecl *ConversionDecl = dyn_cast<CXXConversionDecl>(D);
401   if (!Policy.SuppressSpecifiers) {
402     switch (D->getStorageClass()) {
403     case SC_None: break;
404     case SC_Extern: Out << "extern "; break;
405     case SC_Static: Out << "static "; break;
406     case SC_PrivateExtern: Out << "__private_extern__ "; break;
407     case SC_Auto: case SC_Register: case SC_OpenCLWorkGroupLocal:
408       llvm_unreachable("invalid for functions");
409     }
410 
411     if (D->isInlineSpecified())  Out << "inline ";
412     if (D->isVirtualAsWritten()) Out << "virtual ";
413     if (D->isModulePrivate())    Out << "__module_private__ ";
414     if (D->isConstexpr() && !D->isExplicitlyDefaulted()) Out << "constexpr ";
415     if ((CDecl && CDecl->isExplicitSpecified()) ||
416         (ConversionDecl && ConversionDecl->isExplicit()))
417       Out << "explicit ";
418   }
419 
420   PrintingPolicy SubPolicy(Policy);
421   SubPolicy.SuppressSpecifiers = false;
422   std::string Proto = D->getNameInfo().getAsString();
423 
424   QualType Ty = D->getType();
425   while (const ParenType *PT = dyn_cast<ParenType>(Ty)) {
426     Proto = '(' + Proto + ')';
427     Ty = PT->getInnerType();
428   }
429 
430   if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
431     const FunctionProtoType *FT = nullptr;
432     if (D->hasWrittenPrototype())
433       FT = dyn_cast<FunctionProtoType>(AFT);
434 
435     Proto += "(";
436     if (FT) {
437       llvm::raw_string_ostream POut(Proto);
438       DeclPrinter ParamPrinter(POut, SubPolicy, Indentation);
439       for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
440         if (i) POut << ", ";
441         ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
442       }
443 
444       if (FT->isVariadic()) {
445         if (D->getNumParams()) POut << ", ";
446         POut << "...";
447       }
448     } else if (D->doesThisDeclarationHaveABody() && !D->hasPrototype()) {
449       for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
450         if (i)
451           Proto += ", ";
452         Proto += D->getParamDecl(i)->getNameAsString();
453       }
454     }
455 
456     Proto += ")";
457 
458     if (FT) {
459       if (FT->isConst())
460         Proto += " const";
461       if (FT->isVolatile())
462         Proto += " volatile";
463       if (FT->isRestrict())
464         Proto += " restrict";
465 
466       switch (FT->getRefQualifier()) {
467       case RQ_None:
468         break;
469       case RQ_LValue:
470         Proto += " &";
471         break;
472       case RQ_RValue:
473         Proto += " &&";
474         break;
475       }
476     }
477 
478     if (FT && FT->hasDynamicExceptionSpec()) {
479       Proto += " throw(";
480       if (FT->getExceptionSpecType() == EST_MSAny)
481         Proto += "...";
482       else
483         for (unsigned I = 0, N = FT->getNumExceptions(); I != N; ++I) {
484           if (I)
485             Proto += ", ";
486 
487           Proto += FT->getExceptionType(I).getAsString(SubPolicy);
488         }
489       Proto += ")";
490     } else if (FT && isNoexceptExceptionSpec(FT->getExceptionSpecType())) {
491       Proto += " noexcept";
492       if (FT->getExceptionSpecType() == EST_ComputedNoexcept) {
493         Proto += "(";
494         llvm::raw_string_ostream EOut(Proto);
495         FT->getNoexceptExpr()->printPretty(EOut, nullptr, SubPolicy,
496                                            Indentation);
497         EOut.flush();
498         Proto += EOut.str();
499         Proto += ")";
500       }
501     }
502 
503     if (CDecl) {
504       bool HasInitializerList = false;
505       for (const auto *BMInitializer : CDecl->inits()) {
506         if (BMInitializer->isInClassMemberInitializer())
507           continue;
508 
509         if (!HasInitializerList) {
510           Proto += " : ";
511           Out << Proto;
512           Proto.clear();
513           HasInitializerList = true;
514         } else
515           Out << ", ";
516 
517         if (BMInitializer->isAnyMemberInitializer()) {
518           FieldDecl *FD = BMInitializer->getAnyMember();
519           Out << *FD;
520         } else {
521           Out << QualType(BMInitializer->getBaseClass(), 0).getAsString(Policy);
522         }
523 
524         Out << "(";
525         if (!BMInitializer->getInit()) {
526           // Nothing to print
527         } else {
528           Expr *Init = BMInitializer->getInit();
529           if (ExprWithCleanups *Tmp = dyn_cast<ExprWithCleanups>(Init))
530             Init = Tmp->getSubExpr();
531 
532           Init = Init->IgnoreParens();
533 
534           Expr *SimpleInit = nullptr;
535           Expr **Args = nullptr;
536           unsigned NumArgs = 0;
537           if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
538             Args = ParenList->getExprs();
539             NumArgs = ParenList->getNumExprs();
540           } else if (CXXConstructExpr *Construct
541                                         = dyn_cast<CXXConstructExpr>(Init)) {
542             Args = Construct->getArgs();
543             NumArgs = Construct->getNumArgs();
544           } else
545             SimpleInit = Init;
546 
547           if (SimpleInit)
548             SimpleInit->printPretty(Out, nullptr, Policy, Indentation);
549           else {
550             for (unsigned I = 0; I != NumArgs; ++I) {
551               assert(Args[I] != nullptr && "Expected non-null Expr");
552               if (isa<CXXDefaultArgExpr>(Args[I]))
553                 break;
554 
555               if (I)
556                 Out << ", ";
557               Args[I]->printPretty(Out, nullptr, Policy, Indentation);
558             }
559           }
560         }
561         Out << ")";
562         if (BMInitializer->isPackExpansion())
563           Out << "...";
564       }
565     } else if (!ConversionDecl && !isa<CXXDestructorDecl>(D)) {
566       if (FT && FT->hasTrailingReturn()) {
567         Out << "auto " << Proto << " -> ";
568         Proto.clear();
569       }
570       AFT->getReturnType().print(Out, Policy, Proto);
571       Proto.clear();
572     }
573     Out << Proto;
574   } else {
575     Ty.print(Out, Policy, Proto);
576   }
577 
578   prettyPrintAttributes(D);
579 
580   if (D->isPure())
581     Out << " = 0";
582   else if (D->isDeletedAsWritten())
583     Out << " = delete";
584   else if (D->isExplicitlyDefaulted())
585     Out << " = default";
586   else if (D->doesThisDeclarationHaveABody() && !Policy.TerseOutput) {
587     if (!D->hasPrototype() && D->getNumParams()) {
588       // This is a K&R function definition, so we need to print the
589       // parameters.
590       Out << '\n';
591       DeclPrinter ParamPrinter(Out, SubPolicy, Indentation);
592       Indentation += Policy.Indentation;
593       for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
594         Indent();
595         ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
596         Out << ";\n";
597       }
598       Indentation -= Policy.Indentation;
599     } else
600       Out << ' ';
601 
602     if (D->getBody())
603       D->getBody()->printPretty(Out, nullptr, SubPolicy, Indentation);
604     Out << '\n';
605   }
606 }
607 
608 void DeclPrinter::VisitFriendDecl(FriendDecl *D) {
609   if (TypeSourceInfo *TSI = D->getFriendType()) {
610     unsigned NumTPLists = D->getFriendTypeNumTemplateParameterLists();
611     for (unsigned i = 0; i < NumTPLists; ++i)
612       PrintTemplateParameters(D->getFriendTypeTemplateParameterList(i));
613     Out << "friend ";
614     Out << " " << TSI->getType().getAsString(Policy);
615   }
616   else if (FunctionDecl *FD =
617       dyn_cast<FunctionDecl>(D->getFriendDecl())) {
618     Out << "friend ";
619     VisitFunctionDecl(FD);
620   }
621   else if (FunctionTemplateDecl *FTD =
622            dyn_cast<FunctionTemplateDecl>(D->getFriendDecl())) {
623     Out << "friend ";
624     VisitFunctionTemplateDecl(FTD);
625   }
626   else if (ClassTemplateDecl *CTD =
627            dyn_cast<ClassTemplateDecl>(D->getFriendDecl())) {
628     Out << "friend ";
629     VisitRedeclarableTemplateDecl(CTD);
630   }
631 }
632 
633 void DeclPrinter::VisitFieldDecl(FieldDecl *D) {
634   if (!Policy.SuppressSpecifiers && D->isMutable())
635     Out << "mutable ";
636   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
637     Out << "__module_private__ ";
638 
639   Out << D->getASTContext().getUnqualifiedObjCPointerType(D->getType()).
640             stream(Policy, D->getName());
641 
642   if (D->isBitField()) {
643     Out << " : ";
644     D->getBitWidth()->printPretty(Out, nullptr, Policy, Indentation);
645   }
646 
647   Expr *Init = D->getInClassInitializer();
648   if (!Policy.SuppressInitializers && Init) {
649     if (D->getInClassInitStyle() == ICIS_ListInit)
650       Out << " ";
651     else
652       Out << " = ";
653     Init->printPretty(Out, nullptr, Policy, Indentation);
654   }
655   prettyPrintAttributes(D);
656 }
657 
658 void DeclPrinter::VisitLabelDecl(LabelDecl *D) {
659   Out << *D << ":";
660 }
661 
662 void DeclPrinter::VisitVarDecl(VarDecl *D) {
663   if (!Policy.SuppressSpecifiers) {
664     StorageClass SC = D->getStorageClass();
665     if (SC != SC_None)
666       Out << VarDecl::getStorageClassSpecifierString(SC) << " ";
667 
668     switch (D->getTSCSpec()) {
669     case TSCS_unspecified:
670       break;
671     case TSCS___thread:
672       Out << "__thread ";
673       break;
674     case TSCS__Thread_local:
675       Out << "_Thread_local ";
676       break;
677     case TSCS_thread_local:
678       Out << "thread_local ";
679       break;
680     }
681 
682     if (D->isModulePrivate())
683       Out << "__module_private__ ";
684   }
685 
686   QualType T = D->getTypeSourceInfo()
687     ? D->getTypeSourceInfo()->getType()
688     : D->getASTContext().getUnqualifiedObjCPointerType(D->getType());
689   printDeclType(T, D->getName());
690   Expr *Init = D->getInit();
691   if (!Policy.SuppressInitializers && Init) {
692     bool ImplicitInit = false;
693     if (CXXConstructExpr *Construct =
694             dyn_cast<CXXConstructExpr>(Init->IgnoreImplicit())) {
695       if (D->getInitStyle() == VarDecl::CallInit &&
696           !Construct->isListInitialization()) {
697         ImplicitInit = Construct->getNumArgs() == 0 ||
698           Construct->getArg(0)->isDefaultArgument();
699       }
700     }
701     if (!ImplicitInit) {
702       if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
703         Out << "(";
704       else if (D->getInitStyle() == VarDecl::CInit) {
705         Out << " = ";
706       }
707       Init->printPretty(Out, nullptr, Policy, Indentation);
708       if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
709         Out << ")";
710     }
711   }
712   prettyPrintAttributes(D);
713 }
714 
715 void DeclPrinter::VisitParmVarDecl(ParmVarDecl *D) {
716   VisitVarDecl(D);
717 }
718 
719 void DeclPrinter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) {
720   Out << "__asm (";
721   D->getAsmString()->printPretty(Out, nullptr, Policy, Indentation);
722   Out << ")";
723 }
724 
725 void DeclPrinter::VisitImportDecl(ImportDecl *D) {
726   Out << "@import " << D->getImportedModule()->getFullModuleName()
727       << ";\n";
728 }
729 
730 void DeclPrinter::VisitStaticAssertDecl(StaticAssertDecl *D) {
731   Out << "static_assert(";
732   D->getAssertExpr()->printPretty(Out, nullptr, Policy, Indentation);
733   Out << ", ";
734   D->getMessage()->printPretty(Out, nullptr, Policy, Indentation);
735   Out << ")";
736 }
737 
738 //----------------------------------------------------------------------------
739 // C++ declarations
740 //----------------------------------------------------------------------------
741 void DeclPrinter::VisitNamespaceDecl(NamespaceDecl *D) {
742   if (D->isInline())
743     Out << "inline ";
744   Out << "namespace " << *D << " {\n";
745   VisitDeclContext(D);
746   Indent() << "}";
747 }
748 
749 void DeclPrinter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
750   Out << "using namespace ";
751   if (D->getQualifier())
752     D->getQualifier()->print(Out, Policy);
753   Out << *D->getNominatedNamespaceAsWritten();
754 }
755 
756 void DeclPrinter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
757   Out << "namespace " << *D << " = ";
758   if (D->getQualifier())
759     D->getQualifier()->print(Out, Policy);
760   Out << *D->getAliasedNamespace();
761 }
762 
763 void DeclPrinter::VisitEmptyDecl(EmptyDecl *D) {
764   prettyPrintAttributes(D);
765 }
766 
767 void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) {
768   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
769     Out << "__module_private__ ";
770   Out << D->getKindName();
771   if (D->getIdentifier())
772     Out << ' ' << *D;
773 
774   if (D->isCompleteDefinition()) {
775     // Print the base classes
776     if (D->getNumBases()) {
777       Out << " : ";
778       for (CXXRecordDecl::base_class_iterator Base = D->bases_begin(),
779              BaseEnd = D->bases_end(); Base != BaseEnd; ++Base) {
780         if (Base != D->bases_begin())
781           Out << ", ";
782 
783         if (Base->isVirtual())
784           Out << "virtual ";
785 
786         AccessSpecifier AS = Base->getAccessSpecifierAsWritten();
787         if (AS != AS_none) {
788           Print(AS);
789           Out << " ";
790         }
791         Out << Base->getType().getAsString(Policy);
792 
793         if (Base->isPackExpansion())
794           Out << "...";
795       }
796     }
797 
798     // Print the class definition
799     // FIXME: Doesn't print access specifiers, e.g., "public:"
800     Out << " {\n";
801     VisitDeclContext(D);
802     Indent() << "}";
803   }
804 }
805 
806 void DeclPrinter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
807   const char *l;
808   if (D->getLanguage() == LinkageSpecDecl::lang_c)
809     l = "C";
810   else {
811     assert(D->getLanguage() == LinkageSpecDecl::lang_cxx &&
812            "unknown language in linkage specification");
813     l = "C++";
814   }
815 
816   Out << "extern \"" << l << "\" ";
817   if (D->hasBraces()) {
818     Out << "{\n";
819     VisitDeclContext(D);
820     Indent() << "}";
821   } else
822     Visit(*D->decls_begin());
823 }
824 
825 void DeclPrinter::PrintTemplateParameters(const TemplateParameterList *Params,
826                                           const TemplateArgumentList *Args) {
827   assert(Params);
828   assert(!Args || Params->size() == Args->size());
829 
830   Out << "template <";
831 
832   for (unsigned i = 0, e = Params->size(); i != e; ++i) {
833     if (i != 0)
834       Out << ", ";
835 
836     const Decl *Param = Params->getParam(i);
837     if (const TemplateTypeParmDecl *TTP =
838           dyn_cast<TemplateTypeParmDecl>(Param)) {
839 
840       if (TTP->wasDeclaredWithTypename())
841         Out << "typename ";
842       else
843         Out << "class ";
844 
845       if (TTP->isParameterPack())
846         Out << "...";
847 
848       Out << *TTP;
849 
850       if (Args) {
851         Out << " = ";
852         Args->get(i).print(Policy, Out);
853       } else if (TTP->hasDefaultArgument()) {
854         Out << " = ";
855         Out << TTP->getDefaultArgument().getAsString(Policy);
856       };
857     } else if (const NonTypeTemplateParmDecl *NTTP =
858                  dyn_cast<NonTypeTemplateParmDecl>(Param)) {
859       StringRef Name;
860       if (IdentifierInfo *II = NTTP->getIdentifier())
861         Name = II->getName();
862       printDeclType(NTTP->getType(), Name, NTTP->isParameterPack());
863 
864       if (Args) {
865         Out << " = ";
866         Args->get(i).print(Policy, Out);
867       } else if (NTTP->hasDefaultArgument()) {
868         Out << " = ";
869         NTTP->getDefaultArgument()->printPretty(Out, nullptr, Policy,
870                                                 Indentation);
871       }
872     } else if (const TemplateTemplateParmDecl *TTPD =
873                  dyn_cast<TemplateTemplateParmDecl>(Param)) {
874       VisitTemplateDecl(TTPD);
875       // FIXME: print the default argument, if present.
876     }
877   }
878 
879   Out << "> ";
880 }
881 
882 void DeclPrinter::VisitTemplateDecl(const TemplateDecl *D) {
883   PrintTemplateParameters(D->getTemplateParameters());
884 
885   if (const TemplateTemplateParmDecl *TTP =
886         dyn_cast<TemplateTemplateParmDecl>(D)) {
887     Out << "class ";
888     if (TTP->isParameterPack())
889       Out << "...";
890     Out << D->getName();
891   } else {
892     Visit(D->getTemplatedDecl());
893   }
894 }
895 
896 void DeclPrinter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
897   if (PrintInstantiation) {
898     TemplateParameterList *Params = D->getTemplateParameters();
899     for (auto *I : D->specializations()) {
900       PrintTemplateParameters(Params, I->getTemplateSpecializationArgs());
901       Visit(I);
902     }
903   }
904 
905   return VisitRedeclarableTemplateDecl(D);
906 }
907 
908 void DeclPrinter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
909   if (PrintInstantiation) {
910     TemplateParameterList *Params = D->getTemplateParameters();
911     for (auto *I : D->specializations()) {
912       PrintTemplateParameters(Params, &I->getTemplateArgs());
913       Visit(I);
914       Out << '\n';
915     }
916   }
917 
918   return VisitRedeclarableTemplateDecl(D);
919 }
920 
921 //----------------------------------------------------------------------------
922 // Objective-C declarations
923 //----------------------------------------------------------------------------
924 
925 void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) {
926   if (OMD->isInstanceMethod())
927     Out << "- ";
928   else
929     Out << "+ ";
930   if (!OMD->getReturnType().isNull())
931     Out << '(' << OMD->getASTContext()
932                       .getUnqualifiedObjCPointerType(OMD->getReturnType())
933                       .getAsString(Policy) << ")";
934 
935   std::string name = OMD->getSelector().getAsString();
936   std::string::size_type pos, lastPos = 0;
937   for (const auto *PI : OMD->params()) {
938     // FIXME: selector is missing here!
939     pos = name.find_first_of(':', lastPos);
940     Out << " " << name.substr(lastPos, pos - lastPos);
941     Out << ":(" << PI->getASTContext().getUnqualifiedObjCPointerType(PI->getType()).
942                       getAsString(Policy) << ')' << *PI;
943     lastPos = pos + 1;
944   }
945 
946   if (OMD->param_begin() == OMD->param_end())
947     Out << " " << name;
948 
949   if (OMD->isVariadic())
950       Out << ", ...";
951 
952   if (OMD->getBody() && !Policy.TerseOutput) {
953     Out << ' ';
954     OMD->getBody()->printPretty(Out, nullptr, Policy);
955     Out << '\n';
956   }
957   else if (Policy.PolishForDeclaration)
958     Out << ';';
959 }
960 
961 void DeclPrinter::VisitObjCImplementationDecl(ObjCImplementationDecl *OID) {
962   std::string I = OID->getNameAsString();
963   ObjCInterfaceDecl *SID = OID->getSuperClass();
964 
965   if (SID)
966     Out << "@implementation " << I << " : " << *SID;
967   else
968     Out << "@implementation " << I;
969 
970   if (OID->ivar_size() > 0) {
971     Out << "{\n";
972     Indentation += Policy.Indentation;
973     for (const auto *I : OID->ivars()) {
974       Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).
975                     getAsString(Policy) << ' ' << *I << ";\n";
976     }
977     Indentation -= Policy.Indentation;
978     Out << "}\n";
979   }
980   VisitDeclContext(OID, false);
981   Out << "@end";
982 }
983 
984 void DeclPrinter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *OID) {
985   std::string I = OID->getNameAsString();
986   ObjCInterfaceDecl *SID = OID->getSuperClass();
987 
988   if (!OID->isThisDeclarationADefinition()) {
989     Out << "@class " << I << ";";
990     return;
991   }
992   bool eolnOut = false;
993   if (SID)
994     Out << "@interface " << I << " : " << *SID;
995   else
996     Out << "@interface " << I;
997 
998   // Protocols?
999   const ObjCList<ObjCProtocolDecl> &Protocols = OID->getReferencedProtocols();
1000   if (!Protocols.empty()) {
1001     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1002          E = Protocols.end(); I != E; ++I)
1003       Out << (I == Protocols.begin() ? '<' : ',') << **I;
1004     Out << "> ";
1005   }
1006 
1007   if (OID->ivar_size() > 0) {
1008     Out << "{\n";
1009     eolnOut = true;
1010     Indentation += Policy.Indentation;
1011     for (const auto *I : OID->ivars()) {
1012       Indent() << I->getASTContext()
1013                       .getUnqualifiedObjCPointerType(I->getType())
1014                       .getAsString(Policy) << ' ' << *I << ";\n";
1015     }
1016     Indentation -= Policy.Indentation;
1017     Out << "}\n";
1018   }
1019   else if (SID) {
1020     Out << "\n";
1021     eolnOut = true;
1022   }
1023 
1024   VisitDeclContext(OID, false);
1025   if (!eolnOut)
1026     Out << ' ';
1027   Out << "@end";
1028   // FIXME: implement the rest...
1029 }
1030 
1031 void DeclPrinter::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1032   if (!PID->isThisDeclarationADefinition()) {
1033     Out << "@protocol " << *PID << ";\n";
1034     return;
1035   }
1036   // Protocols?
1037   const ObjCList<ObjCProtocolDecl> &Protocols = PID->getReferencedProtocols();
1038   if (!Protocols.empty()) {
1039     Out << "@protocol " << *PID;
1040     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1041          E = Protocols.end(); I != E; ++I)
1042       Out << (I == Protocols.begin() ? '<' : ',') << **I;
1043     Out << ">\n";
1044   } else
1045     Out << "@protocol " << *PID << '\n';
1046   VisitDeclContext(PID, false);
1047   Out << "@end";
1048 }
1049 
1050 void DeclPrinter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *PID) {
1051   Out << "@implementation " << *PID->getClassInterface() << '(' << *PID <<")\n";
1052 
1053   VisitDeclContext(PID, false);
1054   Out << "@end";
1055   // FIXME: implement the rest...
1056 }
1057 
1058 void DeclPrinter::VisitObjCCategoryDecl(ObjCCategoryDecl *PID) {
1059   Out << "@interface " << *PID->getClassInterface() << '(' << *PID << ")\n";
1060   if (PID->ivar_size() > 0) {
1061     Out << "{\n";
1062     Indentation += Policy.Indentation;
1063     for (const auto *I : PID->ivars())
1064       Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).
1065                     getAsString(Policy) << ' ' << *I << ";\n";
1066     Indentation -= Policy.Indentation;
1067     Out << "}\n";
1068   }
1069 
1070   VisitDeclContext(PID, false);
1071   Out << "@end";
1072 
1073   // FIXME: implement the rest...
1074 }
1075 
1076 void DeclPrinter::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *AID) {
1077   Out << "@compatibility_alias " << *AID
1078       << ' ' << *AID->getClassInterface() << ";\n";
1079 }
1080 
1081 /// PrintObjCPropertyDecl - print a property declaration.
1082 ///
1083 void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) {
1084   if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Required)
1085     Out << "@required\n";
1086   else if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Optional)
1087     Out << "@optional\n";
1088 
1089   Out << "@property";
1090   if (PDecl->getPropertyAttributes() != ObjCPropertyDecl::OBJC_PR_noattr) {
1091     bool first = true;
1092     Out << " (";
1093     if (PDecl->getPropertyAttributes() &
1094         ObjCPropertyDecl::OBJC_PR_readonly) {
1095       Out << (first ? ' ' : ',') << "readonly";
1096       first = false;
1097     }
1098 
1099     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
1100       Out << (first ? ' ' : ',') << "getter = ";
1101       PDecl->getGetterName().print(Out);
1102       first = false;
1103     }
1104     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
1105       Out << (first ? ' ' : ',') << "setter = ";
1106       PDecl->getSetterName().print(Out);
1107       first = false;
1108     }
1109 
1110     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_assign) {
1111       Out << (first ? ' ' : ',') << "assign";
1112       first = false;
1113     }
1114 
1115     if (PDecl->getPropertyAttributes() &
1116         ObjCPropertyDecl::OBJC_PR_readwrite) {
1117       Out << (first ? ' ' : ',') << "readwrite";
1118       first = false;
1119     }
1120 
1121     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain) {
1122       Out << (first ? ' ' : ',') << "retain";
1123       first = false;
1124     }
1125 
1126     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_strong) {
1127       Out << (first ? ' ' : ',') << "strong";
1128       first = false;
1129     }
1130 
1131     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy) {
1132       Out << (first ? ' ' : ',') << "copy";
1133       first = false;
1134     }
1135 
1136     if (PDecl->getPropertyAttributes() &
1137         ObjCPropertyDecl::OBJC_PR_nonatomic) {
1138       Out << (first ? ' ' : ',') << "nonatomic";
1139       first = false;
1140     }
1141     if (PDecl->getPropertyAttributes() &
1142         ObjCPropertyDecl::OBJC_PR_atomic) {
1143       Out << (first ? ' ' : ',') << "atomic";
1144       first = false;
1145     }
1146 
1147     (void) first; // Silence dead store warning due to idiomatic code.
1148     Out << " )";
1149   }
1150   Out << ' ' << PDecl->getASTContext().getUnqualifiedObjCPointerType(PDecl->getType()).
1151                   getAsString(Policy) << ' ' << *PDecl;
1152   if (Policy.PolishForDeclaration)
1153     Out << ';';
1154 }
1155 
1156 void DeclPrinter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PID) {
1157   if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize)
1158     Out << "@synthesize ";
1159   else
1160     Out << "@dynamic ";
1161   Out << *PID->getPropertyDecl();
1162   if (PID->getPropertyIvarDecl())
1163     Out << '=' << *PID->getPropertyIvarDecl();
1164 }
1165 
1166 void DeclPrinter::VisitUsingDecl(UsingDecl *D) {
1167   if (!D->isAccessDeclaration())
1168     Out << "using ";
1169   if (D->hasTypename())
1170     Out << "typename ";
1171   D->getQualifier()->print(Out, Policy);
1172   Out << *D;
1173 }
1174 
1175 void
1176 DeclPrinter::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
1177   Out << "using typename ";
1178   D->getQualifier()->print(Out, Policy);
1179   Out << D->getDeclName();
1180 }
1181 
1182 void DeclPrinter::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1183   if (!D->isAccessDeclaration())
1184     Out << "using ";
1185   D->getQualifier()->print(Out, Policy);
1186   Out << D->getName();
1187 }
1188 
1189 void DeclPrinter::VisitUsingShadowDecl(UsingShadowDecl *D) {
1190   // ignore
1191 }
1192 
1193 void DeclPrinter::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
1194   Out << "#pragma omp threadprivate";
1195   if (!D->varlist_empty()) {
1196     for (OMPThreadPrivateDecl::varlist_iterator I = D->varlist_begin(),
1197                                                 E = D->varlist_end();
1198                                                 I != E; ++I) {
1199       Out << (I == D->varlist_begin() ? '(' : ',');
1200       NamedDecl *ND = cast<NamedDecl>(cast<DeclRefExpr>(*I)->getDecl());
1201       ND->printQualifiedName(Out);
1202     }
1203     Out << ")";
1204   }
1205 }
1206 
1207