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