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