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