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