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