]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/AST/DeclPrinter.cpp
Update compiler-rt to trunk r224034. This brings a number of new
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / AST / DeclPrinter.cpp
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 = nullptr);
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->getReturnType();
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 = nullptr;
286     if (isa<OMPThreadPrivateDecl>(*D))
287       Terminator = nullptr;
288     else if (isa<FunctionDecl>(*D) &&
289              cast<FunctionDecl>(*D)->isThisDeclarationADefinition())
290       Terminator = nullptr;
291     else if (isa<ObjCMethodDecl>(*D) && cast<ObjCMethodDecl>(*D)->getBody())
292       Terminator = nullptr;
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 = nullptr;
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, nullptr, Policy, Indentation);
383   }
384 }
385
386 void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) {
387   CXXConstructorDecl *CDecl = dyn_cast<CXXConstructorDecl>(D);
388   CXXConversionDecl *ConversionDecl = dyn_cast<CXXConversionDecl>(D);
389   if (!Policy.SuppressSpecifiers) {
390     switch (D->getStorageClass()) {
391     case SC_None: break;
392     case SC_Extern: Out << "extern "; break;
393     case SC_Static: Out << "static "; break;
394     case SC_PrivateExtern: Out << "__private_extern__ "; break;
395     case SC_Auto: case SC_Register: case SC_OpenCLWorkGroupLocal:
396       llvm_unreachable("invalid for functions");
397     }
398
399     if (D->isInlineSpecified())  Out << "inline ";
400     if (D->isVirtualAsWritten()) Out << "virtual ";
401     if (D->isModulePrivate())    Out << "__module_private__ ";
402     if (D->isConstexpr() && !D->isExplicitlyDefaulted()) Out << "constexpr ";
403     if ((CDecl && CDecl->isExplicitSpecified()) ||
404         (ConversionDecl && ConversionDecl->isExplicit()))
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 (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
419     const FunctionProtoType *FT = nullptr;
420     if (D->hasWrittenPrototype())
421       FT = dyn_cast<FunctionProtoType>(AFT);
422
423     Proto += "(";
424     if (FT) {
425       llvm::raw_string_ostream POut(Proto);
426       DeclPrinter ParamPrinter(POut, SubPolicy, Indentation);
427       for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
428         if (i) POut << ", ";
429         ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
430       }
431
432       if (FT->isVariadic()) {
433         if (D->getNumParams()) POut << ", ";
434         POut << "...";
435       }
436     } else if (D->doesThisDeclarationHaveABody() && !D->hasPrototype()) {
437       for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
438         if (i)
439           Proto += ", ";
440         Proto += D->getParamDecl(i)->getNameAsString();
441       }
442     }
443
444     Proto += ")";
445     
446     if (FT) {
447       if (FT->isConst())
448         Proto += " const";
449       if (FT->isVolatile())
450         Proto += " volatile";
451       if (FT->isRestrict())
452         Proto += " restrict";
453
454       switch (FT->getRefQualifier()) {
455       case RQ_None:
456         break;
457       case RQ_LValue:
458         Proto += " &";
459         break;
460       case RQ_RValue:
461         Proto += " &&";
462         break;
463       }
464     }
465
466     if (FT && FT->hasDynamicExceptionSpec()) {
467       Proto += " throw(";
468       if (FT->getExceptionSpecType() == EST_MSAny)
469         Proto += "...";
470       else 
471         for (unsigned I = 0, N = FT->getNumExceptions(); I != N; ++I) {
472           if (I)
473             Proto += ", ";
474
475           Proto += FT->getExceptionType(I).getAsString(SubPolicy);
476         }
477       Proto += ")";
478     } else if (FT && isNoexceptExceptionSpec(FT->getExceptionSpecType())) {
479       Proto += " noexcept";
480       if (FT->getExceptionSpecType() == EST_ComputedNoexcept) {
481         Proto += "(";
482         llvm::raw_string_ostream EOut(Proto);
483         FT->getNoexceptExpr()->printPretty(EOut, nullptr, SubPolicy,
484                                            Indentation);
485         EOut.flush();
486         Proto += EOut.str();
487         Proto += ")";
488       }
489     }
490
491     if (CDecl) {
492       bool HasInitializerList = false;
493       for (const auto *BMInitializer : CDecl->inits()) {
494         if (BMInitializer->isInClassMemberInitializer())
495           continue;
496
497         if (!HasInitializerList) {
498           Proto += " : ";
499           Out << Proto;
500           Proto.clear();
501           HasInitializerList = true;
502         } else
503           Out << ", ";
504
505         if (BMInitializer->isAnyMemberInitializer()) {
506           FieldDecl *FD = BMInitializer->getAnyMember();
507           Out << *FD;
508         } else {
509           Out << QualType(BMInitializer->getBaseClass(), 0).getAsString(Policy);
510         }
511         
512         Out << "(";
513         if (!BMInitializer->getInit()) {
514           // Nothing to print
515         } else {
516           Expr *Init = BMInitializer->getInit();
517           if (ExprWithCleanups *Tmp = dyn_cast<ExprWithCleanups>(Init))
518             Init = Tmp->getSubExpr();
519           
520           Init = Init->IgnoreParens();
521
522           Expr *SimpleInit = nullptr;
523           Expr **Args = nullptr;
524           unsigned NumArgs = 0;
525           if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
526             Args = ParenList->getExprs();
527             NumArgs = ParenList->getNumExprs();
528           } else if (CXXConstructExpr *Construct
529                                         = dyn_cast<CXXConstructExpr>(Init)) {
530             Args = Construct->getArgs();
531             NumArgs = Construct->getNumArgs();
532           } else
533             SimpleInit = Init;
534           
535           if (SimpleInit)
536             SimpleInit->printPretty(Out, nullptr, Policy, Indentation);
537           else {
538             for (unsigned I = 0; I != NumArgs; ++I) {
539               assert(Args[I] != nullptr && "Expected non-null Expr");
540               if (isa<CXXDefaultArgExpr>(Args[I]))
541                 break;
542               
543               if (I)
544                 Out << ", ";
545               Args[I]->printPretty(Out, nullptr, Policy, Indentation);
546             }
547           }
548         }
549         Out << ")";
550         if (BMInitializer->isPackExpansion())
551           Out << "...";
552       }
553     } else if (!ConversionDecl && !isa<CXXDestructorDecl>(D)) {
554       if (FT && FT->hasTrailingReturn()) {
555         Out << "auto " << Proto << " -> ";
556         Proto.clear();
557       }
558       AFT->getReturnType().print(Out, Policy, Proto);
559       Proto.clear();
560     }
561     Out << Proto;
562   } else {
563     Ty.print(Out, Policy, Proto);
564   }
565
566   prettyPrintAttributes(D);
567
568   if (D->isPure())
569     Out << " = 0";
570   else if (D->isDeletedAsWritten())
571     Out << " = delete";
572   else if (D->isExplicitlyDefaulted())
573     Out << " = default";
574   else if (D->doesThisDeclarationHaveABody() && !Policy.TerseOutput) {
575     if (!D->hasPrototype() && D->getNumParams()) {
576       // This is a K&R function definition, so we need to print the
577       // parameters.
578       Out << '\n';
579       DeclPrinter ParamPrinter(Out, SubPolicy, Indentation);
580       Indentation += Policy.Indentation;
581       for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
582         Indent();
583         ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
584         Out << ";\n";
585       }
586       Indentation -= Policy.Indentation;
587     } else
588       Out << ' ';
589
590     if (D->getBody())
591       D->getBody()->printPretty(Out, nullptr, SubPolicy, Indentation);
592     Out << '\n';
593   }
594 }
595
596 void DeclPrinter::VisitFriendDecl(FriendDecl *D) {
597   if (TypeSourceInfo *TSI = D->getFriendType()) {
598     unsigned NumTPLists = D->getFriendTypeNumTemplateParameterLists();
599     for (unsigned i = 0; i < NumTPLists; ++i)
600       PrintTemplateParameters(D->getFriendTypeTemplateParameterList(i));
601     Out << "friend ";
602     Out << " " << TSI->getType().getAsString(Policy);
603   }
604   else if (FunctionDecl *FD =
605       dyn_cast<FunctionDecl>(D->getFriendDecl())) {
606     Out << "friend ";
607     VisitFunctionDecl(FD);
608   }
609   else if (FunctionTemplateDecl *FTD =
610            dyn_cast<FunctionTemplateDecl>(D->getFriendDecl())) {
611     Out << "friend ";
612     VisitFunctionTemplateDecl(FTD);
613   }
614   else if (ClassTemplateDecl *CTD =
615            dyn_cast<ClassTemplateDecl>(D->getFriendDecl())) {
616     Out << "friend ";
617     VisitRedeclarableTemplateDecl(CTD);
618   }
619 }
620
621 void DeclPrinter::VisitFieldDecl(FieldDecl *D) {
622   if (!Policy.SuppressSpecifiers && D->isMutable())
623     Out << "mutable ";
624   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
625     Out << "__module_private__ ";
626
627   Out << D->getASTContext().getUnqualifiedObjCPointerType(D->getType()).
628             stream(Policy, D->getName());
629
630   if (D->isBitField()) {
631     Out << " : ";
632     D->getBitWidth()->printPretty(Out, nullptr, Policy, Indentation);
633   }
634
635   Expr *Init = D->getInClassInitializer();
636   if (!Policy.SuppressInitializers && Init) {
637     if (D->getInClassInitStyle() == ICIS_ListInit)
638       Out << " ";
639     else
640       Out << " = ";
641     Init->printPretty(Out, nullptr, Policy, Indentation);
642   }
643   prettyPrintAttributes(D);
644 }
645
646 void DeclPrinter::VisitLabelDecl(LabelDecl *D) {
647   Out << *D << ":";
648 }
649
650
651 void DeclPrinter::VisitVarDecl(VarDecl *D) {
652   if (!Policy.SuppressSpecifiers) {
653     StorageClass SC = D->getStorageClass();
654     if (SC != SC_None)
655       Out << VarDecl::getStorageClassSpecifierString(SC) << " ";
656
657     switch (D->getTSCSpec()) {
658     case TSCS_unspecified:
659       break;
660     case TSCS___thread:
661       Out << "__thread ";
662       break;
663     case TSCS__Thread_local:
664       Out << "_Thread_local ";
665       break;
666     case TSCS_thread_local:
667       Out << "thread_local ";
668       break;
669     }
670
671     if (D->isModulePrivate())
672       Out << "__module_private__ ";
673   }
674
675   QualType T = D->getTypeSourceInfo()
676     ? D->getTypeSourceInfo()->getType()
677     : D->getASTContext().getUnqualifiedObjCPointerType(D->getType());
678   T.print(Out, Policy, D->getName());
679   Expr *Init = D->getInit();
680   if (!Policy.SuppressInitializers && Init) {
681     bool ImplicitInit = false;
682     if (CXXConstructExpr *Construct =
683             dyn_cast<CXXConstructExpr>(Init->IgnoreImplicit())) {
684       if (D->getInitStyle() == VarDecl::CallInit &&
685           !Construct->isListInitialization()) {
686         ImplicitInit = Construct->getNumArgs() == 0 ||
687           Construct->getArg(0)->isDefaultArgument();
688       }
689     }
690     if (!ImplicitInit) {
691       if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
692         Out << "(";
693       else if (D->getInitStyle() == VarDecl::CInit) {
694         Out << " = ";
695       }
696       Init->printPretty(Out, nullptr, Policy, Indentation);
697       if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
698         Out << ")";
699     }
700   }
701   prettyPrintAttributes(D);
702 }
703
704 void DeclPrinter::VisitParmVarDecl(ParmVarDecl *D) {
705   VisitVarDecl(D);
706 }
707
708 void DeclPrinter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) {
709   Out << "__asm (";
710   D->getAsmString()->printPretty(Out, nullptr, Policy, Indentation);
711   Out << ")";
712 }
713
714 void DeclPrinter::VisitImportDecl(ImportDecl *D) {
715   Out << "@import " << D->getImportedModule()->getFullModuleName()
716       << ";\n";
717 }
718
719 void DeclPrinter::VisitStaticAssertDecl(StaticAssertDecl *D) {
720   Out << "static_assert(";
721   D->getAssertExpr()->printPretty(Out, nullptr, Policy, Indentation);
722   Out << ", ";
723   D->getMessage()->printPretty(Out, nullptr, Policy, Indentation);
724   Out << ")";
725 }
726
727 //----------------------------------------------------------------------------
728 // C++ declarations
729 //----------------------------------------------------------------------------
730 void DeclPrinter::VisitNamespaceDecl(NamespaceDecl *D) {
731   if (D->isInline())
732     Out << "inline ";
733   Out << "namespace " << *D << " {\n";
734   VisitDeclContext(D);
735   Indent() << "}";
736 }
737
738 void DeclPrinter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
739   Out << "using namespace ";
740   if (D->getQualifier())
741     D->getQualifier()->print(Out, Policy);
742   Out << *D->getNominatedNamespaceAsWritten();
743 }
744
745 void DeclPrinter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
746   Out << "namespace " << *D << " = ";
747   if (D->getQualifier())
748     D->getQualifier()->print(Out, Policy);
749   Out << *D->getAliasedNamespace();
750 }
751
752 void DeclPrinter::VisitEmptyDecl(EmptyDecl *D) {
753   prettyPrintAttributes(D);
754 }
755
756 void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) {
757   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
758     Out << "__module_private__ ";
759   Out << D->getKindName();
760   if (D->getIdentifier())
761     Out << ' ' << *D;
762
763   if (D->isCompleteDefinition()) {
764     // Print the base classes
765     if (D->getNumBases()) {
766       Out << " : ";
767       for (CXXRecordDecl::base_class_iterator Base = D->bases_begin(),
768              BaseEnd = D->bases_end(); Base != BaseEnd; ++Base) {
769         if (Base != D->bases_begin())
770           Out << ", ";
771
772         if (Base->isVirtual())
773           Out << "virtual ";
774
775         AccessSpecifier AS = Base->getAccessSpecifierAsWritten();
776         if (AS != AS_none)
777           Print(AS);
778         Out << " " << Base->getType().getAsString(Policy);
779
780         if (Base->isPackExpansion())
781           Out << "...";
782       }
783     }
784
785     // Print the class definition
786     // FIXME: Doesn't print access specifiers, e.g., "public:"
787     Out << " {\n";
788     VisitDeclContext(D);
789     Indent() << "}";
790   }
791 }
792
793 void DeclPrinter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
794   const char *l;
795   if (D->getLanguage() == LinkageSpecDecl::lang_c)
796     l = "C";
797   else {
798     assert(D->getLanguage() == LinkageSpecDecl::lang_cxx &&
799            "unknown language in linkage specification");
800     l = "C++";
801   }
802
803   Out << "extern \"" << l << "\" ";
804   if (D->hasBraces()) {
805     Out << "{\n";
806     VisitDeclContext(D);
807     Indent() << "}";
808   } else
809     Visit(*D->decls_begin());
810 }
811
812 void DeclPrinter::PrintTemplateParameters(const TemplateParameterList *Params,
813                                           const TemplateArgumentList *Args) {
814   assert(Params);
815   assert(!Args || Params->size() == Args->size());
816
817   Out << "template <";
818
819   for (unsigned i = 0, e = Params->size(); i != e; ++i) {
820     if (i != 0)
821       Out << ", ";
822
823     const Decl *Param = Params->getParam(i);
824     if (const TemplateTypeParmDecl *TTP =
825           dyn_cast<TemplateTypeParmDecl>(Param)) {
826
827       if (TTP->wasDeclaredWithTypename())
828         Out << "typename ";
829       else
830         Out << "class ";
831
832       if (TTP->isParameterPack())
833         Out << "... ";
834
835       Out << *TTP;
836
837       if (Args) {
838         Out << " = ";
839         Args->get(i).print(Policy, Out);
840       } else if (TTP->hasDefaultArgument()) {
841         Out << " = ";
842         Out << TTP->getDefaultArgument().getAsString(Policy);
843       };
844     } else if (const NonTypeTemplateParmDecl *NTTP =
845                  dyn_cast<NonTypeTemplateParmDecl>(Param)) {
846       Out << NTTP->getType().getAsString(Policy);
847
848       if (NTTP->isParameterPack() && !isa<PackExpansionType>(NTTP->getType()))
849         Out << "...";
850         
851       if (IdentifierInfo *Name = NTTP->getIdentifier()) {
852         Out << ' ';
853         Out << Name->getName();
854       }
855
856       if (Args) {
857         Out << " = ";
858         Args->get(i).print(Policy, Out);
859       } else if (NTTP->hasDefaultArgument()) {
860         Out << " = ";
861         NTTP->getDefaultArgument()->printPretty(Out, nullptr, Policy,
862                                                 Indentation);
863       }
864     } else if (const TemplateTemplateParmDecl *TTPD =
865                  dyn_cast<TemplateTemplateParmDecl>(Param)) {
866       VisitTemplateDecl(TTPD);
867       // FIXME: print the default argument, if present.
868     }
869   }
870
871   Out << "> ";
872 }
873
874 void DeclPrinter::VisitTemplateDecl(const TemplateDecl *D) {
875   PrintTemplateParameters(D->getTemplateParameters());
876
877   if (const TemplateTemplateParmDecl *TTP =
878         dyn_cast<TemplateTemplateParmDecl>(D)) {
879     Out << "class ";
880     if (TTP->isParameterPack())
881       Out << "...";
882     Out << D->getName();
883   } else {
884     Visit(D->getTemplatedDecl());
885   }
886 }
887
888 void DeclPrinter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
889   if (PrintInstantiation) {
890     TemplateParameterList *Params = D->getTemplateParameters();
891     for (auto *I : D->specializations()) {
892       PrintTemplateParameters(Params, I->getTemplateSpecializationArgs());
893       Visit(I);
894     }
895   }
896
897   return VisitRedeclarableTemplateDecl(D);
898 }
899
900 void DeclPrinter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
901   if (PrintInstantiation) {
902     TemplateParameterList *Params = D->getTemplateParameters();
903     for (auto *I : D->specializations()) {
904       PrintTemplateParameters(Params, &I->getTemplateArgs());
905       Visit(I);
906       Out << '\n';
907     }
908   }
909
910   return VisitRedeclarableTemplateDecl(D);
911 }
912
913 //----------------------------------------------------------------------------
914 // Objective-C declarations
915 //----------------------------------------------------------------------------
916
917 void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) {
918   if (OMD->isInstanceMethod())
919     Out << "- ";
920   else
921     Out << "+ ";
922   if (!OMD->getReturnType().isNull())
923     Out << '(' << OMD->getASTContext()
924                       .getUnqualifiedObjCPointerType(OMD->getReturnType())
925                       .getAsString(Policy) << ")";
926
927   std::string name = OMD->getSelector().getAsString();
928   std::string::size_type pos, lastPos = 0;
929   for (const auto *PI : OMD->params()) {
930     // FIXME: selector is missing here!
931     pos = name.find_first_of(':', lastPos);
932     Out << " " << name.substr(lastPos, pos - lastPos);
933     Out << ":(" << PI->getASTContext().getUnqualifiedObjCPointerType(PI->getType()).
934                       getAsString(Policy) << ')' << *PI;
935     lastPos = pos + 1;
936   }
937
938   if (OMD->param_begin() == OMD->param_end())
939     Out << " " << name;
940
941   if (OMD->isVariadic())
942       Out << ", ...";
943
944   if (OMD->getBody() && !Policy.TerseOutput) {
945     Out << ' ';
946     OMD->getBody()->printPretty(Out, nullptr, Policy);
947     Out << '\n';
948   }
949   else if (Policy.PolishForDeclaration)
950     Out << ';';
951 }
952
953 void DeclPrinter::VisitObjCImplementationDecl(ObjCImplementationDecl *OID) {
954   std::string I = OID->getNameAsString();
955   ObjCInterfaceDecl *SID = OID->getSuperClass();
956
957   if (SID)
958     Out << "@implementation " << I << " : " << *SID;
959   else
960     Out << "@implementation " << I;
961   
962   if (OID->ivar_size() > 0) {
963     Out << "{\n";
964     Indentation += Policy.Indentation;
965     for (const auto *I : OID->ivars()) {
966       Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).
967                     getAsString(Policy) << ' ' << *I << ";\n";
968     }
969     Indentation -= Policy.Indentation;
970     Out << "}\n";
971   }
972   VisitDeclContext(OID, false);
973   Out << "@end";
974 }
975
976 void DeclPrinter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *OID) {
977   std::string I = OID->getNameAsString();
978   ObjCInterfaceDecl *SID = OID->getSuperClass();
979
980   if (!OID->isThisDeclarationADefinition()) {
981     Out << "@class " << I << ";";
982     return;
983   }
984   bool eolnOut = false;
985   if (SID)
986     Out << "@interface " << I << " : " << *SID;
987   else
988     Out << "@interface " << I;
989
990   // Protocols?
991   const ObjCList<ObjCProtocolDecl> &Protocols = OID->getReferencedProtocols();
992   if (!Protocols.empty()) {
993     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
994          E = Protocols.end(); I != E; ++I)
995       Out << (I == Protocols.begin() ? '<' : ',') << **I;
996     Out << "> ";
997   }
998
999   if (OID->ivar_size() > 0) {
1000     Out << "{\n";
1001     eolnOut = true;
1002     Indentation += Policy.Indentation;
1003     for (const auto *I : OID->ivars()) {
1004       Indent() << I->getASTContext()
1005                       .getUnqualifiedObjCPointerType(I->getType())
1006                       .getAsString(Policy) << ' ' << *I << ";\n";
1007     }
1008     Indentation -= Policy.Indentation;
1009     Out << "}\n";
1010   }
1011   else if (SID) {
1012     Out << "\n";
1013     eolnOut = true;
1014   }
1015
1016   VisitDeclContext(OID, false);
1017   if (!eolnOut)
1018     Out << ' ';
1019   Out << "@end";
1020   // FIXME: implement the rest...
1021 }
1022
1023 void DeclPrinter::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1024   if (!PID->isThisDeclarationADefinition()) {
1025     Out << "@protocol " << *PID << ";\n";
1026     return;
1027   }
1028   // Protocols?
1029   const ObjCList<ObjCProtocolDecl> &Protocols = PID->getReferencedProtocols();
1030   if (!Protocols.empty()) {
1031     Out << "@protocol " << *PID;
1032     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1033          E = Protocols.end(); I != E; ++I)
1034       Out << (I == Protocols.begin() ? '<' : ',') << **I;
1035     Out << ">\n";
1036   } else
1037     Out << "@protocol " << *PID << '\n';
1038   VisitDeclContext(PID, false);
1039   Out << "@end";
1040 }
1041
1042 void DeclPrinter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *PID) {
1043   Out << "@implementation " << *PID->getClassInterface() << '(' << *PID <<")\n";
1044
1045   VisitDeclContext(PID, false);
1046   Out << "@end";
1047   // FIXME: implement the rest...
1048 }
1049
1050 void DeclPrinter::VisitObjCCategoryDecl(ObjCCategoryDecl *PID) {
1051   Out << "@interface " << *PID->getClassInterface() << '(' << *PID << ")\n";
1052   if (PID->ivar_size() > 0) {
1053     Out << "{\n";
1054     Indentation += Policy.Indentation;
1055     for (const auto *I : PID->ivars())
1056       Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).
1057                     getAsString(Policy) << ' ' << *I << ";\n";
1058     Indentation -= Policy.Indentation;
1059     Out << "}\n";
1060   }
1061   
1062   VisitDeclContext(PID, false);
1063   Out << "@end";
1064
1065   // FIXME: implement the rest...
1066 }
1067
1068 void DeclPrinter::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *AID) {
1069   Out << "@compatibility_alias " << *AID
1070       << ' ' << *AID->getClassInterface() << ";\n";
1071 }
1072
1073 /// PrintObjCPropertyDecl - print a property declaration.
1074 ///
1075 void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) {
1076   if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Required)
1077     Out << "@required\n";
1078   else if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Optional)
1079     Out << "@optional\n";
1080
1081   Out << "@property";
1082   if (PDecl->getPropertyAttributes() != ObjCPropertyDecl::OBJC_PR_noattr) {
1083     bool first = true;
1084     Out << " (";
1085     if (PDecl->getPropertyAttributes() &
1086         ObjCPropertyDecl::OBJC_PR_readonly) {
1087       Out << (first ? ' ' : ',') << "readonly";
1088       first = false;
1089     }
1090
1091     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
1092       Out << (first ? ' ' : ',') << "getter = ";
1093       PDecl->getGetterName().print(Out);
1094       first = false;
1095     }
1096     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
1097       Out << (first ? ' ' : ',') << "setter = ";
1098       PDecl->getSetterName().print(Out);
1099       first = false;
1100     }
1101
1102     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_assign) {
1103       Out << (first ? ' ' : ',') << "assign";
1104       first = false;
1105     }
1106
1107     if (PDecl->getPropertyAttributes() &
1108         ObjCPropertyDecl::OBJC_PR_readwrite) {
1109       Out << (first ? ' ' : ',') << "readwrite";
1110       first = false;
1111     }
1112
1113     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain) {
1114       Out << (first ? ' ' : ',') << "retain";
1115       first = false;
1116     }
1117
1118     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_strong) {
1119       Out << (first ? ' ' : ',') << "strong";
1120       first = false;
1121     }
1122
1123     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy) {
1124       Out << (first ? ' ' : ',') << "copy";
1125       first = false;
1126     }
1127
1128     if (PDecl->getPropertyAttributes() &
1129         ObjCPropertyDecl::OBJC_PR_nonatomic) {
1130       Out << (first ? ' ' : ',') << "nonatomic";
1131       first = false;
1132     }
1133     if (PDecl->getPropertyAttributes() &
1134         ObjCPropertyDecl::OBJC_PR_atomic) {
1135       Out << (first ? ' ' : ',') << "atomic";
1136       first = false;
1137     }
1138     
1139     (void) first; // Silence dead store warning due to idiomatic code.
1140     Out << " )";
1141   }
1142   Out << ' ' << PDecl->getASTContext().getUnqualifiedObjCPointerType(PDecl->getType()).
1143                   getAsString(Policy) << ' ' << *PDecl;
1144   if (Policy.PolishForDeclaration)
1145     Out << ';';
1146 }
1147
1148 void DeclPrinter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PID) {
1149   if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize)
1150     Out << "@synthesize ";
1151   else
1152     Out << "@dynamic ";
1153   Out << *PID->getPropertyDecl();
1154   if (PID->getPropertyIvarDecl())
1155     Out << '=' << *PID->getPropertyIvarDecl();
1156 }
1157
1158 void DeclPrinter::VisitUsingDecl(UsingDecl *D) {
1159   if (!D->isAccessDeclaration())
1160     Out << "using ";
1161   if (D->hasTypename())
1162     Out << "typename ";
1163   D->getQualifier()->print(Out, Policy);
1164   Out << *D;
1165 }
1166
1167 void
1168 DeclPrinter::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
1169   Out << "using typename ";
1170   D->getQualifier()->print(Out, Policy);
1171   Out << D->getDeclName();
1172 }
1173
1174 void DeclPrinter::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1175   if (!D->isAccessDeclaration())
1176     Out << "using ";
1177   D->getQualifier()->print(Out, Policy);
1178   Out << D->getName();
1179 }
1180
1181 void DeclPrinter::VisitUsingShadowDecl(UsingShadowDecl *D) {
1182   // ignore
1183 }
1184
1185 void DeclPrinter::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
1186   Out << "#pragma omp threadprivate";
1187   if (!D->varlist_empty()) {
1188     for (OMPThreadPrivateDecl::varlist_iterator I = D->varlist_begin(),
1189                                                 E = D->varlist_end();
1190                                                 I != E; ++I) {
1191       Out << (I == D->varlist_begin() ? '(' : ',');
1192       NamedDecl *ND = cast<NamedDecl>(cast<DeclRefExpr>(*I)->getDecl());
1193       ND->printQualifiedName(Out);
1194     }
1195     Out << ")";
1196   }
1197 }
1198