1 //===--- DeclPrinter.cpp - Printing implementation for Decl ASTs ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Decl::print method, which pretty prints the
11 // AST back out to C/Objective-C/C++/Objective-C++ code.
12 //
13 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/Attr.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclVisitor.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/PrettyPrinter.h"
23 #include "clang/Basic/Module.h"
24 #include "llvm/Support/raw_ostream.h"
25 using namespace clang;
26 
27 namespace {
28   class DeclPrinter : public DeclVisitor<DeclPrinter> {
29     raw_ostream &Out;
30     PrintingPolicy Policy;
31     unsigned Indentation;
32     bool PrintInstantiation;
33 
34     raw_ostream& Indent() { return Indent(Indentation); }
35     raw_ostream& Indent(unsigned Indentation);
36     void ProcessDeclGroup(SmallVectorImpl<Decl*>& Decls);
37 
38     void Print(AccessSpecifier AS);
39 
40   public:
41     DeclPrinter(raw_ostream &Out, const PrintingPolicy &Policy,
42                 unsigned Indentation = 0, bool PrintInstantiation = false)
43       : Out(Out), Policy(Policy), Indentation(Indentation),
44         PrintInstantiation(PrintInstantiation) { }
45 
46     void VisitDeclContext(DeclContext *DC, bool Indent = true);
47 
48     void VisitTranslationUnitDecl(TranslationUnitDecl *D);
49     void VisitTypedefDecl(TypedefDecl *D);
50     void VisitTypeAliasDecl(TypeAliasDecl *D);
51     void VisitEnumDecl(EnumDecl *D);
52     void VisitRecordDecl(RecordDecl *D);
53     void VisitEnumConstantDecl(EnumConstantDecl *D);
54     void VisitFunctionDecl(FunctionDecl *D);
55     void VisitFriendDecl(FriendDecl *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 VisitImportDecl(ImportDecl *D);
62     void VisitStaticAssertDecl(StaticAssertDecl *D);
63     void VisitNamespaceDecl(NamespaceDecl *D);
64     void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
65     void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
66     void VisitCXXRecordDecl(CXXRecordDecl *D);
67     void VisitLinkageSpecDecl(LinkageSpecDecl *D);
68     void VisitTemplateDecl(const TemplateDecl *D);
69     void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
70     void VisitClassTemplateDecl(ClassTemplateDecl *D);
71     void VisitObjCMethodDecl(ObjCMethodDecl *D);
72     void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
73     void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
74     void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
75     void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
76     void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
77     void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
78     void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
79     void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
80     void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
81     void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
82     void VisitUsingDecl(UsingDecl *D);
83     void VisitUsingShadowDecl(UsingShadowDecl *D);
84 
85     void PrintTemplateParameters(const TemplateParameterList *Params,
86                                  const TemplateArgumentList *Args);
87     void prettyPrintAttributes(Decl *D);
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, 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 BlockPointerType *BPy = BaseType->getAs<BlockPointerType>())
111       BaseType = BPy->getPointeeType();
112     else if (const ArrayType* ATy = dyn_cast<ArrayType>(BaseType))
113       BaseType = ATy->getElementType();
114     else if (const FunctionType* FTy = BaseType->getAs<FunctionType>())
115       BaseType = FTy->getResultType();
116     else if (const VectorType *VTy = BaseType->getAs<VectorType>())
117       BaseType = VTy->getElementType();
118     else if (const ReferenceType *RTy = BaseType->getAs<ReferenceType>())
119       BaseType = RTy->getPointeeType();
120     else
121       llvm_unreachable("Unknown declarator!");
122   }
123   return BaseType;
124 }
125 
126 static QualType getDeclType(Decl* D) {
127   if (TypedefNameDecl* TDD = dyn_cast<TypedefNameDecl>(D))
128     return TDD->getUnderlyingType();
129   if (ValueDecl* VD = dyn_cast<ValueDecl>(D))
130     return VD->getType();
131   return QualType();
132 }
133 
134 void Decl::printGroup(Decl** Begin, unsigned NumDecls,
135                       raw_ostream &Out, const PrintingPolicy &Policy,
136                       unsigned Indentation) {
137   if (NumDecls == 1) {
138     (*Begin)->print(Out, Policy, Indentation);
139     return;
140   }
141 
142   Decl** End = Begin + NumDecls;
143   TagDecl* TD = dyn_cast<TagDecl>(*Begin);
144   if (TD)
145     ++Begin;
146 
147   PrintingPolicy SubPolicy(Policy);
148   if (TD && TD->isCompleteDefinition()) {
149     TD->print(Out, Policy, Indentation);
150     Out << " ";
151     SubPolicy.SuppressTag = true;
152   }
153 
154   bool isFirst = true;
155   for ( ; Begin != End; ++Begin) {
156     if (isFirst) {
157       SubPolicy.SuppressSpecifiers = false;
158       isFirst = false;
159     } else {
160       if (!isFirst) Out << ", ";
161       SubPolicy.SuppressSpecifiers = true;
162     }
163 
164     (*Begin)->print(Out, SubPolicy, Indentation);
165   }
166 }
167 
168 void DeclContext::dumpDeclContext() const {
169   // Get the translation unit
170   const DeclContext *DC = this;
171   while (!DC->isTranslationUnit())
172     DC = DC->getParent();
173 
174   ASTContext &Ctx = cast<TranslationUnitDecl>(DC)->getASTContext();
175   DeclPrinter Printer(llvm::errs(), Ctx.getPrintingPolicy(), 0);
176   Printer.VisitDeclContext(const_cast<DeclContext *>(this), /*Indent=*/false);
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::prettyPrintAttributes(Decl *D) {
186   if (Policy.PolishForDeclaration)
187     return;
188 
189   if (D->hasAttrs()) {
190     AttrVec &Attrs = D->getAttrs();
191     for (AttrVec::const_iterator i=Attrs.begin(), e=Attrs.end(); i!=e; ++i) {
192       Attr *A = *i;
193       A->printPretty(Out, Policy);
194     }
195   }
196 }
197 
198 void DeclPrinter::ProcessDeclGroup(SmallVectorImpl<Decl*>& Decls) {
199   this->Indent();
200   Decl::printGroup(Decls.data(), Decls.size(), Out, Policy, Indentation);
201   Out << ";\n";
202   Decls.clear();
203 
204 }
205 
206 void DeclPrinter::Print(AccessSpecifier AS) {
207   switch(AS) {
208   case AS_none:      llvm_unreachable("No access specifier!");
209   case AS_public:    Out << "public"; break;
210   case AS_protected: Out << "protected"; break;
211   case AS_private:   Out << "private"; break;
212   }
213 }
214 
215 //----------------------------------------------------------------------------
216 // Common C declarations
217 //----------------------------------------------------------------------------
218 
219 void DeclPrinter::VisitDeclContext(DeclContext *DC, bool Indent) {
220   if (Policy.TerseOutput)
221     return;
222 
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     // Skip over implicit declarations in pretty-printing mode.
236     if (D->isImplicit())
237       continue;
238 
239     // FIXME: Ugly hack so we don't pretty-print the builtin declaration
240     // of __builtin_va_list or __[u]int128_t.  There should be some other way
241     // to check that.
242     if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
243       if (IdentifierInfo *II = ND->getIdentifier()) {
244         if (II->isStr("__builtin_va_list") ||
245             II->isStr("__int128_t") || II->isStr("__uint128_t"))
246           continue;
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   CXXConstructorDecl *CDecl = dyn_cast<CXXConstructorDecl>(D);
391   if (!Policy.SuppressSpecifiers) {
392     switch (D->getStorageClassAsWritten()) {
393     case SC_None: break;
394     case SC_Extern: Out << "extern "; break;
395     case SC_Static: Out << "static "; break;
396     case SC_PrivateExtern: Out << "__private_extern__ "; break;
397     case SC_Auto: case SC_Register: case SC_OpenCLWorkGroupLocal:
398       llvm_unreachable("invalid for functions");
399     }
400 
401     if (D->isInlineSpecified())  Out << "inline ";
402     if (D->isVirtualAsWritten()) Out << "virtual ";
403     if (D->isModulePrivate())    Out << "__module_private__ ";
404     if (CDecl && CDecl->isExplicitSpecified())
405       Out << "explicit ";
406   }
407 
408   PrintingPolicy SubPolicy(Policy);
409   SubPolicy.SuppressSpecifiers = false;
410   std::string Proto = D->getNameInfo().getAsString();
411 
412   QualType Ty = D->getType();
413   while (const ParenType *PT = dyn_cast<ParenType>(Ty)) {
414     Proto = '(' + Proto + ')';
415     Ty = PT->getInnerType();
416   }
417 
418   if (isa<FunctionType>(Ty)) {
419     const FunctionType *AFT = Ty->getAs<FunctionType>();
420     const FunctionProtoType *FT = 0;
421     if (D->hasWrittenPrototype())
422       FT = dyn_cast<FunctionProtoType>(AFT);
423 
424     Proto += "(";
425     if (FT) {
426       llvm::raw_string_ostream POut(Proto);
427       DeclPrinter ParamPrinter(POut, SubPolicy, Indentation);
428       for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
429         if (i) POut << ", ";
430         ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
431       }
432 
433       if (FT->isVariadic()) {
434         if (D->getNumParams()) POut << ", ";
435         POut << "...";
436       }
437     } else if (D->doesThisDeclarationHaveABody() && !D->hasPrototype()) {
438       for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
439         if (i)
440           Proto += ", ";
441         Proto += D->getParamDecl(i)->getNameAsString();
442       }
443     }
444 
445     Proto += ")";
446 
447     if (FT) {
448       if (FT->isConst())
449         Proto += " const";
450       if (FT->isVolatile())
451         Proto += " volatile";
452       if (FT->isRestrict())
453         Proto += " restrict";
454     }
455 
456     if (FT && FT->hasDynamicExceptionSpec()) {
457       Proto += " throw(";
458       if (FT->getExceptionSpecType() == EST_MSAny)
459         Proto += "...";
460       else
461         for (unsigned I = 0, N = FT->getNumExceptions(); I != N; ++I) {
462           if (I)
463             Proto += ", ";
464 
465           Proto += FT->getExceptionType(I).getAsString(SubPolicy);
466         }
467       Proto += ")";
468     } else if (FT && isNoexceptExceptionSpec(FT->getExceptionSpecType())) {
469       Proto += " noexcept";
470       if (FT->getExceptionSpecType() == EST_ComputedNoexcept) {
471         Proto += "(";
472         llvm::raw_string_ostream EOut(Proto);
473         FT->getNoexceptExpr()->printPretty(EOut, 0, SubPolicy,
474                                            Indentation);
475         EOut.flush();
476         Proto += EOut.str();
477         Proto += ")";
478       }
479     }
480 
481     if (CDecl) {
482       bool HasInitializerList = false;
483       for (CXXConstructorDecl::init_const_iterator B = CDecl->init_begin(),
484            E = CDecl->init_end();
485            B != E; ++B) {
486         CXXCtorInitializer * BMInitializer = (*B);
487         if (BMInitializer->isInClassMemberInitializer())
488           continue;
489 
490         if (!HasInitializerList) {
491           Proto += " : ";
492           Out << Proto;
493           Proto.clear();
494           HasInitializerList = true;
495         } else
496           Out << ", ";
497 
498         if (BMInitializer->isAnyMemberInitializer()) {
499           FieldDecl *FD = BMInitializer->getAnyMember();
500           Out << *FD;
501         } else {
502           Out << QualType(BMInitializer->getBaseClass(), 0).getAsString(Policy);
503         }
504 
505         Out << "(";
506         if (!BMInitializer->getInit()) {
507           // Nothing to print
508         } else {
509           Expr *Init = BMInitializer->getInit();
510           if (ExprWithCleanups *Tmp = dyn_cast<ExprWithCleanups>(Init))
511             Init = Tmp->getSubExpr();
512 
513           Init = Init->IgnoreParens();
514 
515           Expr *SimpleInit = 0;
516           Expr **Args = 0;
517           unsigned NumArgs = 0;
518           if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
519             Args = ParenList->getExprs();
520             NumArgs = ParenList->getNumExprs();
521           } else if (CXXConstructExpr *Construct
522                                         = dyn_cast<CXXConstructExpr>(Init)) {
523             Args = Construct->getArgs();
524             NumArgs = Construct->getNumArgs();
525           } else
526             SimpleInit = Init;
527 
528           if (SimpleInit)
529             SimpleInit->printPretty(Out, 0, Policy, Indentation);
530           else {
531             for (unsigned I = 0; I != NumArgs; ++I) {
532               if (isa<CXXDefaultArgExpr>(Args[I]))
533                 break;
534 
535               if (I)
536                 Out << ", ";
537               Args[I]->printPretty(Out, 0, Policy, Indentation);
538             }
539           }
540         }
541         Out << ")";
542       }
543       if (!Proto.empty())
544         Out << Proto;
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->isExplicitlyDefaulted())
559     Out << " = default";
560   else if (D->doesThisDeclarationHaveABody() && !Policy.TerseOutput) {
561     if (!D->hasPrototype() && D->getNumParams()) {
562       // This is a K&R function definition, so we need to print the
563       // parameters.
564       Out << '\n';
565       DeclPrinter ParamPrinter(Out, SubPolicy, Indentation);
566       Indentation += Policy.Indentation;
567       for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
568         Indent();
569         ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
570         Out << ";\n";
571       }
572       Indentation -= Policy.Indentation;
573     } else
574       Out << ' ';
575 
576     D->getBody()->printPretty(Out, 0, SubPolicy, Indentation);
577     Out << '\n';
578   }
579 }
580 
581 void DeclPrinter::VisitFriendDecl(FriendDecl *D) {
582   if (TypeSourceInfo *TSI = D->getFriendType()) {
583     Out << "friend ";
584     Out << " " << TSI->getType().getAsString(Policy);
585   }
586   else if (FunctionDecl *FD =
587       dyn_cast<FunctionDecl>(D->getFriendDecl())) {
588     Out << "friend ";
589     VisitFunctionDecl(FD);
590   }
591   else if (FunctionTemplateDecl *FTD =
592            dyn_cast<FunctionTemplateDecl>(D->getFriendDecl())) {
593     Out << "friend ";
594     VisitFunctionTemplateDecl(FTD);
595   }
596   else if (ClassTemplateDecl *CTD =
597            dyn_cast<ClassTemplateDecl>(D->getFriendDecl())) {
598     Out << "friend ";
599     VisitRedeclarableTemplateDecl(CTD);
600   }
601 }
602 
603 void DeclPrinter::VisitFieldDecl(FieldDecl *D) {
604   if (!Policy.SuppressSpecifiers && D->isMutable())
605     Out << "mutable ";
606   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
607     Out << "__module_private__ ";
608 
609   Out << D->getType().stream(Policy, D->getName());
610 
611   if (D->isBitField()) {
612     Out << " : ";
613     D->getBitWidth()->printPretty(Out, 0, Policy, Indentation);
614   }
615 
616   Expr *Init = D->getInClassInitializer();
617   if (!Policy.SuppressInitializers && Init) {
618     if (D->getInClassInitStyle() == ICIS_ListInit)
619       Out << " ";
620     else
621       Out << " = ";
622     Init->printPretty(Out, 0, Policy, Indentation);
623   }
624   prettyPrintAttributes(D);
625 }
626 
627 void DeclPrinter::VisitLabelDecl(LabelDecl *D) {
628   Out << *D << ":";
629 }
630 
631 
632 void DeclPrinter::VisitVarDecl(VarDecl *D) {
633   StorageClass SCAsWritten = D->getStorageClassAsWritten();
634   if (!Policy.SuppressSpecifiers && SCAsWritten != SC_None)
635     Out << VarDecl::getStorageClassSpecifierString(SCAsWritten) << " ";
636 
637   if (!Policy.SuppressSpecifiers && D->isThreadSpecified())
638     Out << "__thread ";
639   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
640     Out << "__module_private__ ";
641 
642   QualType T = D->getType();
643   if (ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(D))
644     T = Parm->getOriginalType();
645   T.print(Out, Policy, D->getName());
646   Expr *Init = D->getInit();
647   if (!Policy.SuppressInitializers && Init) {
648     bool ImplicitInit = false;
649     if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
650       ImplicitInit = D->getInitStyle() == VarDecl::CallInit &&
651           Construct->getNumArgs() == 0 && !Construct->isListInitialization();
652     if (!ImplicitInit) {
653       if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
654         Out << "(";
655       else if (D->getInitStyle() == VarDecl::CInit) {
656         Out << " = ";
657       }
658       Init->printPretty(Out, 0, Policy, Indentation);
659       if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
660         Out << ")";
661     }
662   }
663   prettyPrintAttributes(D);
664 }
665 
666 void DeclPrinter::VisitParmVarDecl(ParmVarDecl *D) {
667   VisitVarDecl(D);
668 }
669 
670 void DeclPrinter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) {
671   Out << "__asm (";
672   D->getAsmString()->printPretty(Out, 0, Policy, Indentation);
673   Out << ")";
674 }
675 
676 void DeclPrinter::VisitImportDecl(ImportDecl *D) {
677   Out << "@import " << D->getImportedModule()->getFullModuleName()
678       << ";\n";
679 }
680 
681 void DeclPrinter::VisitStaticAssertDecl(StaticAssertDecl *D) {
682   Out << "static_assert(";
683   D->getAssertExpr()->printPretty(Out, 0, Policy, Indentation);
684   Out << ", ";
685   D->getMessage()->printPretty(Out, 0, Policy, Indentation);
686   Out << ")";
687 }
688 
689 //----------------------------------------------------------------------------
690 // C++ declarations
691 //----------------------------------------------------------------------------
692 void DeclPrinter::VisitNamespaceDecl(NamespaceDecl *D) {
693   if (D->isInline())
694     Out << "inline ";
695   Out << "namespace " << *D << " {\n";
696   VisitDeclContext(D);
697   Indent() << "}";
698 }
699 
700 void DeclPrinter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
701   Out << "using namespace ";
702   if (D->getQualifier())
703     D->getQualifier()->print(Out, Policy);
704   Out << *D->getNominatedNamespaceAsWritten();
705 }
706 
707 void DeclPrinter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
708   Out << "namespace " << *D << " = ";
709   if (D->getQualifier())
710     D->getQualifier()->print(Out, Policy);
711   Out << *D->getAliasedNamespace();
712 }
713 
714 void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) {
715   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
716     Out << "__module_private__ ";
717   Out << D->getKindName();
718   if (D->getIdentifier())
719     Out << ' ' << *D;
720 
721   if (D->isCompleteDefinition()) {
722     // Print the base classes
723     if (D->getNumBases()) {
724       Out << " : ";
725       for (CXXRecordDecl::base_class_iterator Base = D->bases_begin(),
726              BaseEnd = D->bases_end(); Base != BaseEnd; ++Base) {
727         if (Base != D->bases_begin())
728           Out << ", ";
729 
730         if (Base->isVirtual())
731           Out << "virtual ";
732 
733         AccessSpecifier AS = Base->getAccessSpecifierAsWritten();
734         if (AS != AS_none)
735           Print(AS);
736         Out << " " << Base->getType().getAsString(Policy);
737 
738         if (Base->isPackExpansion())
739           Out << "...";
740       }
741     }
742 
743     // Print the class definition
744     // FIXME: Doesn't print access specifiers, e.g., "public:"
745     Out << " {\n";
746     VisitDeclContext(D);
747     Indent() << "}";
748   }
749 }
750 
751 void DeclPrinter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
752   const char *l;
753   if (D->getLanguage() == LinkageSpecDecl::lang_c)
754     l = "C";
755   else {
756     assert(D->getLanguage() == LinkageSpecDecl::lang_cxx &&
757            "unknown language in linkage specification");
758     l = "C++";
759   }
760 
761   Out << "extern \"" << l << "\" ";
762   if (D->hasBraces()) {
763     Out << "{\n";
764     VisitDeclContext(D);
765     Indent() << "}";
766   } else
767     Visit(*D->decls_begin());
768 }
769 
770 void DeclPrinter::PrintTemplateParameters(
771     const TemplateParameterList *Params, const TemplateArgumentList *Args = 0) {
772   assert(Params);
773   assert(!Args || Params->size() == Args->size());
774 
775   Out << "template <";
776 
777   for (unsigned i = 0, e = Params->size(); i != e; ++i) {
778     if (i != 0)
779       Out << ", ";
780 
781     const Decl *Param = Params->getParam(i);
782     if (const TemplateTypeParmDecl *TTP =
783           dyn_cast<TemplateTypeParmDecl>(Param)) {
784 
785       if (TTP->wasDeclaredWithTypename())
786         Out << "typename ";
787       else
788         Out << "class ";
789 
790       if (TTP->isParameterPack())
791         Out << "... ";
792 
793       Out << *TTP;
794 
795       if (Args) {
796         Out << " = ";
797         Args->get(i).print(Policy, Out);
798       } else if (TTP->hasDefaultArgument()) {
799         Out << " = ";
800         Out << TTP->getDefaultArgument().getAsString(Policy);
801       };
802     } else if (const NonTypeTemplateParmDecl *NTTP =
803                  dyn_cast<NonTypeTemplateParmDecl>(Param)) {
804       Out << NTTP->getType().getAsString(Policy);
805 
806       if (NTTP->isParameterPack() && !isa<PackExpansionType>(NTTP->getType()))
807         Out << "...";
808 
809       if (IdentifierInfo *Name = NTTP->getIdentifier()) {
810         Out << ' ';
811         Out << Name->getName();
812       }
813 
814       if (Args) {
815         Out << " = ";
816         Args->get(i).print(Policy, Out);
817       } else if (NTTP->hasDefaultArgument()) {
818         Out << " = ";
819         NTTP->getDefaultArgument()->printPretty(Out, 0, Policy, Indentation);
820       }
821     } else if (const TemplateTemplateParmDecl *TTPD =
822                  dyn_cast<TemplateTemplateParmDecl>(Param)) {
823       VisitTemplateDecl(TTPD);
824       // FIXME: print the default argument, if present.
825     }
826   }
827 
828   Out << "> ";
829 }
830 
831 void DeclPrinter::VisitTemplateDecl(const TemplateDecl *D) {
832   PrintTemplateParameters(D->getTemplateParameters());
833 
834   if (const TemplateTemplateParmDecl *TTP =
835         dyn_cast<TemplateTemplateParmDecl>(D)) {
836     Out << "class ";
837     if (TTP->isParameterPack())
838       Out << "...";
839     Out << D->getName();
840   } else {
841     Visit(D->getTemplatedDecl());
842   }
843 }
844 
845 void DeclPrinter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
846   if (PrintInstantiation) {
847     TemplateParameterList *Params = D->getTemplateParameters();
848     for (FunctionTemplateDecl::spec_iterator I = D->spec_begin(), E = D->spec_end();
849          I != E; ++I) {
850       PrintTemplateParameters(Params, (*I)->getTemplateSpecializationArgs());
851       Visit(*I);
852     }
853   }
854 
855   return VisitRedeclarableTemplateDecl(D);
856 }
857 
858 void DeclPrinter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
859   if (PrintInstantiation) {
860     TemplateParameterList *Params = D->getTemplateParameters();
861     for (ClassTemplateDecl::spec_iterator I = D->spec_begin(), E = D->spec_end();
862          I != E; ++I) {
863       PrintTemplateParameters(Params, &(*I)->getTemplateArgs());
864       Visit(*I);
865       Out << '\n';
866     }
867   }
868 
869   return VisitRedeclarableTemplateDecl(D);
870 }
871 
872 //----------------------------------------------------------------------------
873 // Objective-C declarations
874 //----------------------------------------------------------------------------
875 
876 void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) {
877   if (OMD->isInstanceMethod())
878     Out << "- ";
879   else
880     Out << "+ ";
881   if (!OMD->getResultType().isNull())
882     Out << '(' << OMD->getResultType().getAsString(Policy) << ")";
883 
884   std::string name = OMD->getSelector().getAsString();
885   std::string::size_type pos, lastPos = 0;
886   for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
887        E = OMD->param_end(); PI != E; ++PI) {
888     // FIXME: selector is missing here!
889     pos = name.find_first_of(':', lastPos);
890     Out << " " << name.substr(lastPos, pos - lastPos);
891     Out << ":(" << (*PI)->getType().getAsString(Policy) << ')' << **PI;
892     lastPos = pos + 1;
893   }
894 
895   if (OMD->param_begin() == OMD->param_end())
896     Out << " " << name;
897 
898   if (OMD->isVariadic())
899       Out << ", ...";
900 
901   if (OMD->getBody() && !Policy.TerseOutput) {
902     Out << ' ';
903     OMD->getBody()->printPretty(Out, 0, Policy);
904     Out << '\n';
905   }
906   else if (Policy.PolishForDeclaration)
907     Out << ';';
908 }
909 
910 void DeclPrinter::VisitObjCImplementationDecl(ObjCImplementationDecl *OID) {
911   std::string I = OID->getNameAsString();
912   ObjCInterfaceDecl *SID = OID->getSuperClass();
913 
914   if (SID)
915     Out << "@implementation " << I << " : " << *SID;
916   else
917     Out << "@implementation " << I;
918 
919   if (OID->ivar_size() > 0) {
920     Out << "{\n";
921     Indentation += Policy.Indentation;
922     for (ObjCImplementationDecl::ivar_iterator I = OID->ivar_begin(),
923          E = OID->ivar_end(); I != E; ++I) {
924       Indent() << I->getType().getAsString(Policy) << ' ' << **I << ";\n";
925     }
926     Indentation -= Policy.Indentation;
927     Out << "}\n";
928   }
929   VisitDeclContext(OID, false);
930   Out << "@end";
931 }
932 
933 void DeclPrinter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *OID) {
934   std::string I = OID->getNameAsString();
935   ObjCInterfaceDecl *SID = OID->getSuperClass();
936 
937   if (!OID->isThisDeclarationADefinition()) {
938     Out << "@class " << I << ";";
939     return;
940   }
941   bool eolnOut = false;
942   if (SID)
943     Out << "@interface " << I << " : " << *SID;
944   else
945     Out << "@interface " << I;
946 
947   // Protocols?
948   const ObjCList<ObjCProtocolDecl> &Protocols = OID->getReferencedProtocols();
949   if (!Protocols.empty()) {
950     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
951          E = Protocols.end(); I != E; ++I)
952       Out << (I == Protocols.begin() ? '<' : ',') << **I;
953     Out << "> ";
954   }
955 
956   if (OID->ivar_size() > 0) {
957     Out << "{\n";
958     eolnOut = true;
959     Indentation += Policy.Indentation;
960     for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
961          E = OID->ivar_end(); I != E; ++I) {
962       Indent() << I->getType().getAsString(Policy) << ' ' << **I << ";\n";
963     }
964     Indentation -= Policy.Indentation;
965     Out << "}\n";
966   }
967   else if (SID) {
968     Out << "\n";
969     eolnOut = true;
970   }
971 
972   VisitDeclContext(OID, false);
973   if (!eolnOut)
974     Out << ' ';
975   Out << "@end";
976   // FIXME: implement the rest...
977 }
978 
979 void DeclPrinter::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
980   if (!PID->isThisDeclarationADefinition()) {
981     Out << "@protocol " << *PID << ";\n";
982     return;
983   }
984   // Protocols?
985   const ObjCList<ObjCProtocolDecl> &Protocols = PID->getReferencedProtocols();
986   if (!Protocols.empty()) {
987     Out << "@protocol " << *PID;
988     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
989          E = Protocols.end(); I != E; ++I)
990       Out << (I == Protocols.begin() ? '<' : ',') << **I;
991     Out << ">\n";
992   } else
993     Out << "@protocol " << *PID << '\n';
994   VisitDeclContext(PID, false);
995   Out << "@end";
996 }
997 
998 void DeclPrinter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *PID) {
999   Out << "@implementation " << *PID->getClassInterface() << '(' << *PID <<")\n";
1000 
1001   VisitDeclContext(PID, false);
1002   Out << "@end";
1003   // FIXME: implement the rest...
1004 }
1005 
1006 void DeclPrinter::VisitObjCCategoryDecl(ObjCCategoryDecl *PID) {
1007   Out << "@interface " << *PID->getClassInterface() << '(' << *PID << ")\n";
1008   if (PID->ivar_size() > 0) {
1009     Out << "{\n";
1010     Indentation += Policy.Indentation;
1011     for (ObjCCategoryDecl::ivar_iterator I = PID->ivar_begin(),
1012          E = PID->ivar_end(); I != E; ++I) {
1013       Indent() << I->getType().getAsString(Policy) << ' ' << **I << ";\n";
1014     }
1015     Indentation -= Policy.Indentation;
1016     Out << "}\n";
1017   }
1018 
1019   VisitDeclContext(PID, false);
1020   Out << "@end";
1021 
1022   // FIXME: implement the rest...
1023 }
1024 
1025 void DeclPrinter::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *AID) {
1026   Out << "@compatibility_alias " << *AID
1027       << ' ' << *AID->getClassInterface() << ";\n";
1028 }
1029 
1030 /// PrintObjCPropertyDecl - print a property declaration.
1031 ///
1032 void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) {
1033   if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Required)
1034     Out << "@required\n";
1035   else if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Optional)
1036     Out << "@optional\n";
1037 
1038   Out << "@property";
1039   if (PDecl->getPropertyAttributes() != ObjCPropertyDecl::OBJC_PR_noattr) {
1040     bool first = true;
1041     Out << " (";
1042     if (PDecl->getPropertyAttributes() &
1043         ObjCPropertyDecl::OBJC_PR_readonly) {
1044       Out << (first ? ' ' : ',') << "readonly";
1045       first = false;
1046     }
1047 
1048     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
1049       Out << (first ? ' ' : ',') << "getter = "
1050           << PDecl->getGetterName().getAsString();
1051       first = false;
1052     }
1053     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
1054       Out << (first ? ' ' : ',') << "setter = "
1055           << PDecl->getSetterName().getAsString();
1056       first = false;
1057     }
1058 
1059     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_assign) {
1060       Out << (first ? ' ' : ',') << "assign";
1061       first = false;
1062     }
1063 
1064     if (PDecl->getPropertyAttributes() &
1065         ObjCPropertyDecl::OBJC_PR_readwrite) {
1066       Out << (first ? ' ' : ',') << "readwrite";
1067       first = false;
1068     }
1069 
1070     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain) {
1071       Out << (first ? ' ' : ',') << "retain";
1072       first = false;
1073     }
1074 
1075     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_strong) {
1076       Out << (first ? ' ' : ',') << "strong";
1077       first = false;
1078     }
1079 
1080     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy) {
1081       Out << (first ? ' ' : ',') << "copy";
1082       first = false;
1083     }
1084 
1085     if (PDecl->getPropertyAttributes() &
1086         ObjCPropertyDecl::OBJC_PR_nonatomic) {
1087       Out << (first ? ' ' : ',') << "nonatomic";
1088       first = false;
1089     }
1090     if (PDecl->getPropertyAttributes() &
1091         ObjCPropertyDecl::OBJC_PR_atomic) {
1092       Out << (first ? ' ' : ',') << "atomic";
1093       first = false;
1094     }
1095 
1096     (void) first; // Silence dead store warning due to idiomatic code.
1097     Out << " )";
1098   }
1099   Out << ' ' << PDecl->getType().getAsString(Policy) << ' ' << *PDecl;
1100   if (Policy.PolishForDeclaration)
1101     Out << ';';
1102 }
1103 
1104 void DeclPrinter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PID) {
1105   if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize)
1106     Out << "@synthesize ";
1107   else
1108     Out << "@dynamic ";
1109   Out << *PID->getPropertyDecl();
1110   if (PID->getPropertyIvarDecl())
1111     Out << '=' << *PID->getPropertyIvarDecl();
1112 }
1113 
1114 void DeclPrinter::VisitUsingDecl(UsingDecl *D) {
1115   Out << "using ";
1116   D->getQualifier()->print(Out, Policy);
1117   Out << *D;
1118 }
1119 
1120 void
1121 DeclPrinter::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
1122   Out << "using typename ";
1123   D->getQualifier()->print(Out, Policy);
1124   Out << D->getDeclName();
1125 }
1126 
1127 void DeclPrinter::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1128   Out << "using ";
1129   D->getQualifier()->print(Out, Policy);
1130   Out << D->getName();
1131 }
1132 
1133 void DeclPrinter::VisitUsingShadowDecl(UsingShadowDecl *D) {
1134   // ignore
1135 }
1136