DeclPrinter.cpp revision 95ed7784a335aca53b0c6e952cf31a4cfb633360
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    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
91void Decl::print(raw_ostream &Out, unsigned Indentation,
92                 bool PrintInstantiation) const {
93  print(Out, getASTContext().PrintingPolicy, Indentation, PrintInstantiation);
94}
95
96void 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
102static 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      assert(0 && "Unknown declarator!");
118  }
119  return BaseType;
120}
121
122static 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
130void 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->isDefinition()) {
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
164void 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.PrintingPolicy, 0);
172  Printer.VisitDeclContext(const_cast<DeclContext *>(this), /*Indent=*/false);
173}
174
175void Decl::dump() const {
176  print(llvm::errs());
177}
178
179raw_ostream& DeclPrinter::Indent(unsigned Indentation) {
180  for (unsigned i = 0; i != Indentation; ++i)
181    Out << "  ";
182  return Out;
183}
184
185void 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
193void DeclPrinter::Print(AccessSpecifier AS) {
194  switch(AS) {
195  case AS_none:      assert(0 && "No access specifier!"); break;
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
206void 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
309void DeclPrinter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
310  VisitDeclContext(D, false);
311}
312
313void DeclPrinter::VisitTypedefDecl(TypedefDecl *D) {
314  std::string S = D->getNameAsString();
315  D->getUnderlyingType().getAsStringInternal(S, Policy);
316  if (!Policy.SuppressSpecifiers)
317    Out << "typedef ";
318  Out << S;
319}
320
321void DeclPrinter::VisitTypeAliasDecl(TypeAliasDecl *D) {
322  Out << "using " << D->getNameAsString() << " = "
323      << D->getUnderlyingType().getAsString(Policy);
324}
325
326void DeclPrinter::VisitEnumDecl(EnumDecl *D) {
327  Out << "enum ";
328  if (D->isScoped()) {
329    if (D->isScopedUsingClassTag())
330      Out << "class ";
331    else
332      Out << "struct ";
333  }
334  Out << D;
335
336  if (D->isFixed()) {
337    std::string Underlying;
338    D->getIntegerType().getAsStringInternal(Underlying, Policy);
339    Out << " : " << Underlying;
340  }
341
342  if (D->isDefinition()) {
343    Out << " {\n";
344    VisitDeclContext(D);
345    Indent() << "}";
346  }
347}
348
349void DeclPrinter::VisitRecordDecl(RecordDecl *D) {
350  Out << D->getKindName();
351  if (D->getIdentifier())
352    Out << ' ' << D;
353
354  if (D->isDefinition()) {
355    Out << " {\n";
356    VisitDeclContext(D);
357    Indent() << "}";
358  }
359}
360
361void DeclPrinter::VisitEnumConstantDecl(EnumConstantDecl *D) {
362  Out << D;
363  if (Expr *Init = D->getInitExpr()) {
364    Out << " = ";
365    Init->printPretty(Out, Context, 0, Policy, Indentation);
366  }
367}
368
369void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) {
370  if (!Policy.SuppressSpecifiers) {
371    switch (D->getStorageClass()) {
372    case SC_None: break;
373    case SC_Extern: Out << "extern "; break;
374    case SC_Static: Out << "static "; break;
375    case SC_PrivateExtern: Out << "__private_extern__ "; break;
376    case SC_Auto: case SC_Register: llvm_unreachable("invalid for functions");
377    }
378
379    if (D->isInlineSpecified())           Out << "inline ";
380    if (D->isVirtualAsWritten()) Out << "virtual ";
381  }
382
383  PrintingPolicy SubPolicy(Policy);
384  SubPolicy.SuppressSpecifiers = false;
385  std::string Proto = D->getNameInfo().getAsString();
386
387  QualType Ty = D->getType();
388  while (const ParenType *PT = dyn_cast<ParenType>(Ty)) {
389    Proto = '(' + Proto + ')';
390    Ty = PT->getInnerType();
391  }
392
393  if (isa<FunctionType>(Ty)) {
394    const FunctionType *AFT = Ty->getAs<FunctionType>();
395    const FunctionProtoType *FT = 0;
396    if (D->hasWrittenPrototype())
397      FT = dyn_cast<FunctionProtoType>(AFT);
398
399    Proto += "(";
400    if (FT) {
401      llvm::raw_string_ostream POut(Proto);
402      DeclPrinter ParamPrinter(POut, Context, SubPolicy, Indentation);
403      for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
404        if (i) POut << ", ";
405        ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
406      }
407
408      if (FT->isVariadic()) {
409        if (D->getNumParams()) POut << ", ";
410        POut << "...";
411      }
412    } else if (D->doesThisDeclarationHaveABody() && !D->hasPrototype()) {
413      for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
414        if (i)
415          Proto += ", ";
416        Proto += D->getParamDecl(i)->getNameAsString();
417      }
418    }
419
420    Proto += ")";
421
422    if (FT && FT->getTypeQuals()) {
423      unsigned TypeQuals = FT->getTypeQuals();
424      if (TypeQuals & Qualifiers::Const)
425        Proto += " const";
426      if (TypeQuals & Qualifiers::Volatile)
427        Proto += " volatile";
428      if (TypeQuals & Qualifiers::Restrict)
429        Proto += " restrict";
430    }
431
432    if (FT && FT->hasDynamicExceptionSpec()) {
433      Proto += " throw(";
434      if (FT->getExceptionSpecType() == EST_MSAny)
435        Proto += "...";
436      else
437        for (unsigned I = 0, N = FT->getNumExceptions(); I != N; ++I) {
438          if (I)
439            Proto += ", ";
440
441          std::string ExceptionType;
442          FT->getExceptionType(I).getAsStringInternal(ExceptionType, SubPolicy);
443          Proto += ExceptionType;
444        }
445      Proto += ")";
446    } else if (FT && isNoexceptExceptionSpec(FT->getExceptionSpecType())) {
447      Proto += " noexcept";
448      if (FT->getExceptionSpecType() == EST_ComputedNoexcept) {
449        Proto += "(";
450        llvm::raw_string_ostream EOut(Proto);
451        FT->getNoexceptExpr()->printPretty(EOut, Context, 0, SubPolicy,
452                                           Indentation);
453        EOut.flush();
454        Proto += EOut.str();
455        Proto += ")";
456      }
457    }
458
459    if (D->hasAttr<NoReturnAttr>())
460      Proto += " __attribute((noreturn))";
461    if (CXXConstructorDecl *CDecl = dyn_cast<CXXConstructorDecl>(D)) {
462      bool HasInitializerList = false;
463      for (CXXConstructorDecl::init_const_iterator B = CDecl->init_begin(),
464           E = CDecl->init_end();
465           B != E; ++B) {
466        CXXCtorInitializer * BMInitializer = (*B);
467        if (BMInitializer->isInClassMemberInitializer())
468          continue;
469
470        if (!HasInitializerList) {
471          Proto += " : ";
472          Out << Proto;
473          Proto.clear();
474          HasInitializerList = true;
475        } else
476          Out << ", ";
477
478        if (BMInitializer->isAnyMemberInitializer()) {
479          FieldDecl *FD = BMInitializer->getAnyMember();
480          Out << FD;
481        } else {
482          Out << QualType(BMInitializer->getBaseClass(),
483                          0).getAsString(Policy);
484        }
485
486        Out << "(";
487        if (!BMInitializer->getInit()) {
488          // Nothing to print
489        } else {
490          Expr *Init = BMInitializer->getInit();
491          if (ExprWithCleanups *Tmp = dyn_cast<ExprWithCleanups>(Init))
492            Init = Tmp->getSubExpr();
493
494          Init = Init->IgnoreParens();
495
496          Expr *SimpleInit = 0;
497          Expr **Args = 0;
498          unsigned NumArgs = 0;
499          if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
500            Args = ParenList->getExprs();
501            NumArgs = ParenList->getNumExprs();
502          } else if (CXXConstructExpr *Construct
503                                        = dyn_cast<CXXConstructExpr>(Init)) {
504            Args = Construct->getArgs();
505            NumArgs = Construct->getNumArgs();
506          } else
507            SimpleInit = Init;
508
509          if (SimpleInit)
510            SimpleInit->printPretty(Out, Context, 0, Policy, Indentation);
511          else {
512            for (unsigned I = 0; I != NumArgs; ++I) {
513              if (isa<CXXDefaultArgExpr>(Args[I]))
514                break;
515
516              if (I)
517                Out << ", ";
518              Args[I]->printPretty(Out, Context, 0, Policy, Indentation);
519            }
520          }
521        }
522        Out << ")";
523      }
524    }
525    else
526      AFT->getResultType().getAsStringInternal(Proto, Policy);
527  } else {
528    Ty.getAsStringInternal(Proto, Policy);
529  }
530
531  Out << Proto;
532
533  if (D->isPure())
534    Out << " = 0";
535  else if (D->isDeletedAsWritten())
536    Out << " = delete";
537  else if (D->doesThisDeclarationHaveABody()) {
538    if (!D->hasPrototype() && D->getNumParams()) {
539      // This is a K&R function definition, so we need to print the
540      // parameters.
541      Out << '\n';
542      DeclPrinter ParamPrinter(Out, Context, SubPolicy, Indentation);
543      Indentation += Policy.Indentation;
544      for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
545        Indent();
546        ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
547        Out << ";\n";
548      }
549      Indentation -= Policy.Indentation;
550    } else
551      Out << ' ';
552
553    D->getBody()->printPretty(Out, Context, 0, SubPolicy, Indentation);
554    Out << '\n';
555  }
556}
557
558void DeclPrinter::VisitFieldDecl(FieldDecl *D) {
559  if (!Policy.SuppressSpecifiers && D->isMutable())
560    Out << "mutable ";
561
562  std::string Name = D->getNameAsString();
563  D->getType().getAsStringInternal(Name, Policy);
564  Out << Name;
565
566  if (D->isBitField()) {
567    Out << " : ";
568    D->getBitWidth()->printPretty(Out, Context, 0, Policy, Indentation);
569  }
570
571  Expr *Init = D->getInClassInitializer();
572  if (!Policy.SuppressInitializers && Init) {
573    Out << " = ";
574    Init->printPretty(Out, Context, 0, Policy, Indentation);
575  }
576}
577
578void DeclPrinter::VisitLabelDecl(LabelDecl *D) {
579  Out << D->getNameAsString() << ":";
580}
581
582
583void DeclPrinter::VisitVarDecl(VarDecl *D) {
584  if (!Policy.SuppressSpecifiers && D->getStorageClass() != SC_None)
585    Out << VarDecl::getStorageClassSpecifierString(D->getStorageClass()) << " ";
586
587  if (!Policy.SuppressSpecifiers && D->isThreadSpecified())
588    Out << "__thread ";
589
590  std::string Name = D->getNameAsString();
591  QualType T = D->getType();
592  if (ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(D))
593    T = Parm->getOriginalType();
594  T.getAsStringInternal(Name, Policy);
595  Out << Name;
596  Expr *Init = D->getInit();
597  if (!Policy.SuppressInitializers && Init) {
598    if (D->hasCXXDirectInitializer())
599      Out << "(";
600    else {
601        CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init);
602        if (!CCE || CCE->getConstructor()->isCopyConstructor())
603          Out << " = ";
604    }
605    Init->printPretty(Out, Context, 0, Policy, Indentation);
606    if (D->hasCXXDirectInitializer())
607      Out << ")";
608  }
609}
610
611void DeclPrinter::VisitParmVarDecl(ParmVarDecl *D) {
612  VisitVarDecl(D);
613}
614
615void DeclPrinter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) {
616  Out << "__asm (";
617  D->getAsmString()->printPretty(Out, Context, 0, Policy, Indentation);
618  Out << ")";
619}
620
621void DeclPrinter::VisitStaticAssertDecl(StaticAssertDecl *D) {
622  Out << "static_assert(";
623  D->getAssertExpr()->printPretty(Out, Context, 0, Policy, Indentation);
624  Out << ", ";
625  D->getMessage()->printPretty(Out, Context, 0, Policy, Indentation);
626  Out << ")";
627}
628
629//----------------------------------------------------------------------------
630// C++ declarations
631//----------------------------------------------------------------------------
632void DeclPrinter::VisitNamespaceDecl(NamespaceDecl *D) {
633  Out << "namespace " << D << " {\n";
634  VisitDeclContext(D);
635  Indent() << "}";
636}
637
638void DeclPrinter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
639  Out << "using namespace ";
640  if (D->getQualifier())
641    D->getQualifier()->print(Out, Policy);
642  Out << D->getNominatedNamespaceAsWritten();
643}
644
645void DeclPrinter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
646  Out << "namespace " << D << " = ";
647  if (D->getQualifier())
648    D->getQualifier()->print(Out, Policy);
649  Out << D->getAliasedNamespace();
650}
651
652void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) {
653  Out << D->getKindName();
654  if (D->getIdentifier())
655    Out << ' ' << D;
656
657  if (D->isDefinition()) {
658    // Print the base classes
659    if (D->getNumBases()) {
660      Out << " : ";
661      for (CXXRecordDecl::base_class_iterator Base = D->bases_begin(),
662             BaseEnd = D->bases_end(); Base != BaseEnd; ++Base) {
663        if (Base != D->bases_begin())
664          Out << ", ";
665
666        if (Base->isVirtual())
667          Out << "virtual ";
668
669        AccessSpecifier AS = Base->getAccessSpecifierAsWritten();
670        if (AS != AS_none)
671          Print(AS);
672        Out << " " << Base->getType().getAsString(Policy);
673
674        if (Base->isPackExpansion())
675          Out << "...";
676      }
677    }
678
679    // Print the class definition
680    // FIXME: Doesn't print access specifiers, e.g., "public:"
681    Out << " {\n";
682    VisitDeclContext(D);
683    Indent() << "}";
684  }
685}
686
687void DeclPrinter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
688  const char *l;
689  if (D->getLanguage() == LinkageSpecDecl::lang_c)
690    l = "C";
691  else {
692    assert(D->getLanguage() == LinkageSpecDecl::lang_cxx &&
693           "unknown language in linkage specification");
694    l = "C++";
695  }
696
697  Out << "extern \"" << l << "\" ";
698  if (D->hasBraces()) {
699    Out << "{\n";
700    VisitDeclContext(D);
701    Indent() << "}";
702  } else
703    Visit(*D->decls_begin());
704}
705
706void DeclPrinter::PrintTemplateParameters(
707    const TemplateParameterList *Params, const TemplateArgumentList *Args = 0) {
708  assert(Params);
709  assert(!Args || Params->size() == Args->size());
710
711  Out << "template <";
712
713  for (unsigned i = 0, e = Params->size(); i != e; ++i) {
714    if (i != 0)
715      Out << ", ";
716
717    const Decl *Param = Params->getParam(i);
718    if (const TemplateTypeParmDecl *TTP =
719          dyn_cast<TemplateTypeParmDecl>(Param)) {
720
721      if (TTP->wasDeclaredWithTypename())
722        Out << "typename ";
723      else
724        Out << "class ";
725
726      if (TTP->isParameterPack())
727        Out << "... ";
728
729      Out << TTP->getNameAsString();
730
731      if (Args) {
732        Out << " = ";
733        Args->get(i).print(Policy, Out);
734      } else if (TTP->hasDefaultArgument()) {
735        Out << " = ";
736        Out << TTP->getDefaultArgument().getAsString(Policy);
737      };
738    } else if (const NonTypeTemplateParmDecl *NTTP =
739                 dyn_cast<NonTypeTemplateParmDecl>(Param)) {
740      Out << NTTP->getType().getAsString(Policy);
741
742      if (NTTP->isParameterPack() && !isa<PackExpansionType>(NTTP->getType()))
743        Out << "...";
744
745      if (IdentifierInfo *Name = NTTP->getIdentifier()) {
746        Out << ' ';
747        Out << Name->getName();
748      }
749
750      if (Args) {
751        Out << " = ";
752        Args->get(i).print(Policy, Out);
753      } else if (NTTP->hasDefaultArgument()) {
754        Out << " = ";
755        NTTP->getDefaultArgument()->printPretty(Out, Context, 0, Policy,
756                                                Indentation);
757      }
758    } else if (const TemplateTemplateParmDecl *TTPD =
759                 dyn_cast<TemplateTemplateParmDecl>(Param)) {
760      VisitTemplateDecl(TTPD);
761      // FIXME: print the default argument, if present.
762    }
763  }
764
765  Out << "> ";
766}
767
768void DeclPrinter::VisitTemplateDecl(const TemplateDecl *D) {
769  PrintTemplateParameters(D->getTemplateParameters());
770
771  if (const TemplateTemplateParmDecl *TTP =
772        dyn_cast<TemplateTemplateParmDecl>(D)) {
773    Out << "class ";
774    if (TTP->isParameterPack())
775      Out << "...";
776    Out << D->getName();
777  } else {
778    Visit(D->getTemplatedDecl());
779  }
780}
781
782void DeclPrinter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
783  if (PrintInstantiation) {
784    TemplateParameterList *Params = D->getTemplateParameters();
785    for (FunctionTemplateDecl::spec_iterator I = D->spec_begin(), E = D->spec_end();
786         I != E; ++I) {
787      PrintTemplateParameters(Params, (*I)->getTemplateSpecializationArgs());
788      Visit(*I);
789    }
790  }
791
792  return VisitRedeclarableTemplateDecl(D);
793}
794
795void DeclPrinter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
796  if (PrintInstantiation) {
797    TemplateParameterList *Params = D->getTemplateParameters();
798    for (ClassTemplateDecl::spec_iterator I = D->spec_begin(), E = D->spec_end();
799         I != E; ++I) {
800      PrintTemplateParameters(Params, &(*I)->getTemplateArgs());
801      Visit(*I);
802      Out << '\n';
803    }
804  }
805
806  return VisitRedeclarableTemplateDecl(D);
807}
808
809//----------------------------------------------------------------------------
810// Objective-C declarations
811//----------------------------------------------------------------------------
812
813void DeclPrinter::VisitObjCClassDecl(ObjCClassDecl *D) {
814  Out << "@class ";
815  Out << D->getForwardInterfaceDecl();
816}
817
818void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) {
819  if (OMD->isInstanceMethod())
820    Out << "- ";
821  else
822    Out << "+ ";
823  if (!OMD->getResultType().isNull())
824    Out << '(' << OMD->getResultType().getAsString(Policy) << ")";
825
826  std::string name = OMD->getSelector().getAsString();
827  std::string::size_type pos, lastPos = 0;
828  for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
829       E = OMD->param_end(); PI != E; ++PI) {
830    // FIXME: selector is missing here!
831    pos = name.find_first_of(":", lastPos);
832    Out << " " << name.substr(lastPos, pos - lastPos);
833    Out << ":(" << (*PI)->getType().getAsString(Policy) << ')' << *PI;
834    lastPos = pos + 1;
835  }
836
837  if (OMD->param_begin() == OMD->param_end())
838    Out << " " << name;
839
840  if (OMD->isVariadic())
841      Out << ", ...";
842
843  if (OMD->getBody()) {
844    Out << ' ';
845    OMD->getBody()->printPretty(Out, Context, 0, Policy);
846    Out << '\n';
847  }
848}
849
850void DeclPrinter::VisitObjCImplementationDecl(ObjCImplementationDecl *OID) {
851  std::string I = OID->getNameAsString();
852  ObjCInterfaceDecl *SID = OID->getSuperClass();
853
854  if (SID)
855    Out << "@implementation " << I << " : " << SID;
856  else
857    Out << "@implementation " << I;
858  Out << "\n";
859  VisitDeclContext(OID, false);
860  Out << "@end";
861}
862
863void DeclPrinter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *OID) {
864  std::string I = OID->getNameAsString();
865  ObjCInterfaceDecl *SID = OID->getSuperClass();
866
867  if (SID)
868    Out << "@interface " << I << " : " << SID;
869  else
870    Out << "@interface " << I;
871
872  // Protocols?
873  const ObjCList<ObjCProtocolDecl> &Protocols = OID->getReferencedProtocols();
874  if (!Protocols.empty()) {
875    for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
876         E = Protocols.end(); I != E; ++I)
877      Out << (I == Protocols.begin() ? '<' : ',') << *I;
878  }
879
880  if (!Protocols.empty())
881    Out << "> ";
882
883  if (OID->ivar_size() > 0) {
884    Out << "{\n";
885    Indentation += Policy.Indentation;
886    for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
887         E = OID->ivar_end(); I != E; ++I) {
888      Indent() << (*I)->getType().getAsString(Policy) << ' ' << *I << ";\n";
889    }
890    Indentation -= Policy.Indentation;
891    Out << "}\n";
892  }
893
894  VisitDeclContext(OID, false);
895  Out << "@end";
896  // FIXME: implement the rest...
897}
898
899void DeclPrinter::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
900  Out << "@protocol ";
901  for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
902         E = D->protocol_end();
903       I != E; ++I) {
904    if (I != D->protocol_begin()) Out << ", ";
905    Out << *I;
906  }
907}
908
909void DeclPrinter::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
910  Out << "@protocol " << PID << '\n';
911  VisitDeclContext(PID, false);
912  Out << "@end";
913}
914
915void DeclPrinter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *PID) {
916  Out << "@implementation " << PID->getClassInterface() << '(' << PID << ")\n";
917
918  VisitDeclContext(PID, false);
919  Out << "@end";
920  // FIXME: implement the rest...
921}
922
923void DeclPrinter::VisitObjCCategoryDecl(ObjCCategoryDecl *PID) {
924  Out << "@interface " << PID->getClassInterface() << '(' << PID << ")\n";
925  VisitDeclContext(PID, false);
926  Out << "@end";
927
928  // FIXME: implement the rest...
929}
930
931void DeclPrinter::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *AID) {
932  Out << "@compatibility_alias " << AID
933      << ' ' << AID->getClassInterface() << ";\n";
934}
935
936/// PrintObjCPropertyDecl - print a property declaration.
937///
938void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) {
939  if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Required)
940    Out << "@required\n";
941  else if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Optional)
942    Out << "@optional\n";
943
944  Out << "@property";
945  if (PDecl->getPropertyAttributes() != ObjCPropertyDecl::OBJC_PR_noattr) {
946    bool first = true;
947    Out << " (";
948    if (PDecl->getPropertyAttributes() &
949        ObjCPropertyDecl::OBJC_PR_readonly) {
950      Out << (first ? ' ' : ',') << "readonly";
951      first = false;
952    }
953
954    if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
955      Out << (first ? ' ' : ',') << "getter = "
956          << PDecl->getGetterName().getAsString();
957      first = false;
958    }
959    if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
960      Out << (first ? ' ' : ',') << "setter = "
961          << PDecl->getSetterName().getAsString();
962      first = false;
963    }
964
965    if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_assign) {
966      Out << (first ? ' ' : ',') << "assign";
967      first = false;
968    }
969
970    if (PDecl->getPropertyAttributes() &
971        ObjCPropertyDecl::OBJC_PR_readwrite) {
972      Out << (first ? ' ' : ',') << "readwrite";
973      first = false;
974    }
975
976    if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain) {
977      Out << (first ? ' ' : ',') << "retain";
978      first = false;
979    }
980
981    if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_strong) {
982      Out << (first ? ' ' : ',') << "strong";
983      first = false;
984    }
985
986    if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy) {
987      Out << (first ? ' ' : ',') << "copy";
988      first = false;
989    }
990
991    if (PDecl->getPropertyAttributes() &
992        ObjCPropertyDecl::OBJC_PR_nonatomic) {
993      Out << (first ? ' ' : ',') << "nonatomic";
994      first = false;
995    }
996    if (PDecl->getPropertyAttributes() &
997        ObjCPropertyDecl::OBJC_PR_atomic) {
998      Out << (first ? ' ' : ',') << "atomic";
999      first = false;
1000    }
1001
1002    (void) first; // Silence dead store warning due to idiomatic code.
1003    Out << " )";
1004  }
1005  Out << ' ' << PDecl->getType().getAsString(Policy) << ' ' << PDecl;
1006}
1007
1008void DeclPrinter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PID) {
1009  if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize)
1010    Out << "@synthesize ";
1011  else
1012    Out << "@dynamic ";
1013  Out << PID->getPropertyDecl();
1014  if (PID->getPropertyIvarDecl())
1015    Out << '=' << PID->getPropertyIvarDecl();
1016}
1017
1018void DeclPrinter::VisitUsingDecl(UsingDecl *D) {
1019  Out << "using ";
1020  D->getQualifier()->print(Out, Policy);
1021  Out << D;
1022}
1023
1024void
1025DeclPrinter::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
1026  Out << "using typename ";
1027  D->getQualifier()->print(Out, Policy);
1028  Out << D->getDeclName();
1029}
1030
1031void DeclPrinter::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1032  Out << "using ";
1033  D->getQualifier()->print(Out, Policy);
1034  Out << D->getDeclName();
1035}
1036
1037void DeclPrinter::VisitUsingShadowDecl(UsingShadowDecl *D) {
1038  // ignore
1039}
1040