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