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