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