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