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