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    /// Print an Objective-C method type in parentheses.
41    ///
42    /// \param Quals The Objective-C declaration qualifiers.
43    /// \param T The type to print.
44    void PrintObjCMethodType(ASTContext &Ctx, Decl::ObjCDeclQualifier Quals,
45                             QualType T);
46
47    void PrintObjCTypeParams(ObjCTypeParamList *Params);
48
49  public:
50    DeclPrinter(raw_ostream &Out, const PrintingPolicy &Policy,
51                unsigned Indentation = 0, bool PrintInstantiation = false)
52      : Out(Out), Policy(Policy), Indentation(Indentation),
53        PrintInstantiation(PrintInstantiation) { }
54
55    void VisitDeclContext(DeclContext *DC, bool Indent = true);
56
57    void VisitTranslationUnitDecl(TranslationUnitDecl *D);
58    void VisitTypedefDecl(TypedefDecl *D);
59    void VisitTypeAliasDecl(TypeAliasDecl *D);
60    void VisitEnumDecl(EnumDecl *D);
61    void VisitRecordDecl(RecordDecl *D);
62    void VisitEnumConstantDecl(EnumConstantDecl *D);
63    void VisitEmptyDecl(EmptyDecl *D);
64    void VisitFunctionDecl(FunctionDecl *D);
65    void VisitFriendDecl(FriendDecl *D);
66    void VisitFieldDecl(FieldDecl *D);
67    void VisitVarDecl(VarDecl *D);
68    void VisitLabelDecl(LabelDecl *D);
69    void VisitParmVarDecl(ParmVarDecl *D);
70    void VisitFileScopeAsmDecl(FileScopeAsmDecl *D);
71    void VisitImportDecl(ImportDecl *D);
72    void VisitStaticAssertDecl(StaticAssertDecl *D);
73    void VisitNamespaceDecl(NamespaceDecl *D);
74    void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
75    void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
76    void VisitCXXRecordDecl(CXXRecordDecl *D);
77    void VisitLinkageSpecDecl(LinkageSpecDecl *D);
78    void VisitTemplateDecl(const TemplateDecl *D);
79    void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
80    void VisitClassTemplateDecl(ClassTemplateDecl *D);
81    void VisitObjCMethodDecl(ObjCMethodDecl *D);
82    void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
83    void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
84    void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
85    void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
86    void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
87    void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
88    void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
89    void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
90    void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
91    void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
92    void VisitUsingDecl(UsingDecl *D);
93    void VisitUsingShadowDecl(UsingShadowDecl *D);
94    void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
95    void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D);
96    void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D);
97
98    void PrintTemplateParameters(const TemplateParameterList *Params,
99                                 const TemplateArgumentList *Args = nullptr);
100    void prettyPrintAttributes(Decl *D);
101    void prettyPrintPragmas(Decl *D);
102    void printDeclType(QualType T, StringRef DeclName, bool Pack = false);
103  };
104}
105
106void Decl::print(raw_ostream &Out, unsigned Indentation,
107                 bool PrintInstantiation) const {
108  print(Out, getASTContext().getPrintingPolicy(), Indentation, PrintInstantiation);
109}
110
111void Decl::print(raw_ostream &Out, const PrintingPolicy &Policy,
112                 unsigned Indentation, bool PrintInstantiation) const {
113  DeclPrinter Printer(Out, Policy, Indentation, PrintInstantiation);
114  Printer.Visit(const_cast<Decl*>(this));
115}
116
117static QualType GetBaseType(QualType T) {
118  // FIXME: This should be on the Type class!
119  QualType BaseType = T;
120  while (!BaseType->isSpecifierType()) {
121    if (isa<TypedefType>(BaseType))
122      break;
123    else if (const PointerType* PTy = BaseType->getAs<PointerType>())
124      BaseType = PTy->getPointeeType();
125    else if (const BlockPointerType *BPy = BaseType->getAs<BlockPointerType>())
126      BaseType = BPy->getPointeeType();
127    else if (const ArrayType* ATy = dyn_cast<ArrayType>(BaseType))
128      BaseType = ATy->getElementType();
129    else if (const FunctionType* FTy = BaseType->getAs<FunctionType>())
130      BaseType = FTy->getReturnType();
131    else if (const VectorType *VTy = BaseType->getAs<VectorType>())
132      BaseType = VTy->getElementType();
133    else if (const ReferenceType *RTy = BaseType->getAs<ReferenceType>())
134      BaseType = RTy->getPointeeType();
135    else if (const AutoType *ATy = BaseType->getAs<AutoType>())
136      BaseType = ATy->getDeducedType();
137    else
138      llvm_unreachable("Unknown declarator!");
139  }
140  return BaseType;
141}
142
143static QualType getDeclType(Decl* D) {
144  if (TypedefNameDecl* TDD = dyn_cast<TypedefNameDecl>(D))
145    return TDD->getUnderlyingType();
146  if (ValueDecl* VD = dyn_cast<ValueDecl>(D))
147    return VD->getType();
148  return QualType();
149}
150
151void Decl::printGroup(Decl** Begin, unsigned NumDecls,
152                      raw_ostream &Out, const PrintingPolicy &Policy,
153                      unsigned Indentation) {
154  if (NumDecls == 1) {
155    (*Begin)->print(Out, Policy, Indentation);
156    return;
157  }
158
159  Decl** End = Begin + NumDecls;
160  TagDecl* TD = dyn_cast<TagDecl>(*Begin);
161  if (TD)
162    ++Begin;
163
164  PrintingPolicy SubPolicy(Policy);
165
166  bool isFirst = true;
167  for ( ; Begin != End; ++Begin) {
168    if (isFirst) {
169      if(TD)
170        SubPolicy.IncludeTagDefinition = true;
171      SubPolicy.SuppressSpecifiers = false;
172      isFirst = false;
173    } else {
174      if (!isFirst) Out << ", ";
175      SubPolicy.IncludeTagDefinition = false;
176      SubPolicy.SuppressSpecifiers = true;
177    }
178
179    (*Begin)->print(Out, SubPolicy, Indentation);
180  }
181}
182
183LLVM_DUMP_METHOD void DeclContext::dumpDeclContext() const {
184  // Get the translation unit
185  const DeclContext *DC = this;
186  while (!DC->isTranslationUnit())
187    DC = DC->getParent();
188
189  ASTContext &Ctx = cast<TranslationUnitDecl>(DC)->getASTContext();
190  DeclPrinter Printer(llvm::errs(), Ctx.getPrintingPolicy(), 0);
191  Printer.VisitDeclContext(const_cast<DeclContext *>(this), /*Indent=*/false);
192}
193
194raw_ostream& DeclPrinter::Indent(unsigned Indentation) {
195  for (unsigned i = 0; i != Indentation; ++i)
196    Out << "  ";
197  return Out;
198}
199
200void DeclPrinter::prettyPrintAttributes(Decl *D) {
201  if (Policy.PolishForDeclaration)
202    return;
203
204  if (D->hasAttrs()) {
205    AttrVec &Attrs = D->getAttrs();
206    for (auto *A : Attrs) {
207      switch (A->getKind()) {
208#define ATTR(X)
209#define PRAGMA_SPELLING_ATTR(X) case attr::X:
210#include "clang/Basic/AttrList.inc"
211        break;
212      default:
213        A->printPretty(Out, Policy);
214        break;
215      }
216    }
217  }
218}
219
220void DeclPrinter::prettyPrintPragmas(Decl *D) {
221  if (Policy.PolishForDeclaration)
222    return;
223
224  if (D->hasAttrs()) {
225    AttrVec &Attrs = D->getAttrs();
226    for (auto *A : Attrs) {
227      switch (A->getKind()) {
228#define ATTR(X)
229#define PRAGMA_SPELLING_ATTR(X) case attr::X:
230#include "clang/Basic/AttrList.inc"
231        A->printPretty(Out, Policy);
232        Indent();
233        break;
234      default:
235        break;
236      }
237    }
238  }
239}
240
241void DeclPrinter::printDeclType(QualType T, StringRef DeclName, bool Pack) {
242  // Normally, a PackExpansionType is written as T[3]... (for instance, as a
243  // template argument), but if it is the type of a declaration, the ellipsis
244  // is placed before the name being declared.
245  if (auto *PET = T->getAs<PackExpansionType>()) {
246    Pack = true;
247    T = PET->getPattern();
248  }
249  T.print(Out, Policy, (Pack ? "..." : "") + DeclName, Indentation);
250}
251
252void DeclPrinter::ProcessDeclGroup(SmallVectorImpl<Decl*>& Decls) {
253  this->Indent();
254  Decl::printGroup(Decls.data(), Decls.size(), Out, Policy, Indentation);
255  Out << ";\n";
256  Decls.clear();
257
258}
259
260void DeclPrinter::Print(AccessSpecifier AS) {
261  switch(AS) {
262  case AS_none:      llvm_unreachable("No access specifier!");
263  case AS_public:    Out << "public"; break;
264  case AS_protected: Out << "protected"; break;
265  case AS_private:   Out << "private"; break;
266  }
267}
268
269//----------------------------------------------------------------------------
270// Common C declarations
271//----------------------------------------------------------------------------
272
273void DeclPrinter::VisitDeclContext(DeclContext *DC, bool Indent) {
274  if (Policy.TerseOutput)
275    return;
276
277  if (Indent)
278    Indentation += Policy.Indentation;
279
280  SmallVector<Decl*, 2> Decls;
281  for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
282       D != DEnd; ++D) {
283
284    // Don't print ObjCIvarDecls, as they are printed when visiting the
285    // containing ObjCInterfaceDecl.
286    if (isa<ObjCIvarDecl>(*D))
287      continue;
288
289    // Skip over implicit declarations in pretty-printing mode.
290    if (D->isImplicit())
291      continue;
292
293    // The next bits of code handles stuff like "struct {int x;} a,b"; we're
294    // forced to merge the declarations because there's no other way to
295    // refer to the struct in question.  This limited merging is safe without
296    // a bunch of other checks because it only merges declarations directly
297    // referring to the tag, not typedefs.
298    //
299    // Check whether the current declaration should be grouped with a previous
300    // unnamed struct.
301    QualType CurDeclType = getDeclType(*D);
302    if (!Decls.empty() && !CurDeclType.isNull()) {
303      QualType BaseType = GetBaseType(CurDeclType);
304      if (!BaseType.isNull() && isa<ElaboratedType>(BaseType))
305        BaseType = cast<ElaboratedType>(BaseType)->getNamedType();
306      if (!BaseType.isNull() && isa<TagType>(BaseType) &&
307          cast<TagType>(BaseType)->getDecl() == Decls[0]) {
308        Decls.push_back(*D);
309        continue;
310      }
311    }
312
313    // If we have a merged group waiting to be handled, handle it now.
314    if (!Decls.empty())
315      ProcessDeclGroup(Decls);
316
317    // If the current declaration is an unnamed tag type, save it
318    // so we can merge it with the subsequent declaration(s) using it.
319    if (isa<TagDecl>(*D) && !cast<TagDecl>(*D)->getIdentifier()) {
320      Decls.push_back(*D);
321      continue;
322    }
323
324    if (isa<AccessSpecDecl>(*D)) {
325      Indentation -= Policy.Indentation;
326      this->Indent();
327      Print(D->getAccess());
328      Out << ":\n";
329      Indentation += Policy.Indentation;
330      continue;
331    }
332
333    this->Indent();
334    Visit(*D);
335
336    // FIXME: Need to be able to tell the DeclPrinter when
337    const char *Terminator = nullptr;
338    if (isa<OMPThreadPrivateDecl>(*D) || isa<OMPDeclareReductionDecl>(*D))
339      Terminator = nullptr;
340    else if (isa<FunctionDecl>(*D) &&
341             cast<FunctionDecl>(*D)->isThisDeclarationADefinition())
342      Terminator = nullptr;
343    else if (isa<ObjCMethodDecl>(*D) && cast<ObjCMethodDecl>(*D)->getBody())
344      Terminator = nullptr;
345    else if (isa<NamespaceDecl>(*D) || isa<LinkageSpecDecl>(*D) ||
346             isa<ObjCImplementationDecl>(*D) ||
347             isa<ObjCInterfaceDecl>(*D) ||
348             isa<ObjCProtocolDecl>(*D) ||
349             isa<ObjCCategoryImplDecl>(*D) ||
350             isa<ObjCCategoryDecl>(*D))
351      Terminator = nullptr;
352    else if (isa<EnumConstantDecl>(*D)) {
353      DeclContext::decl_iterator Next = D;
354      ++Next;
355      if (Next != DEnd)
356        Terminator = ",";
357    } else
358      Terminator = ";";
359
360    if (Terminator)
361      Out << Terminator;
362    Out << "\n";
363
364    // Declare target attribute is special one, natural spelling for the pragma
365    // assumes "ending" construct so print it here.
366    if (D->hasAttr<OMPDeclareTargetDeclAttr>())
367      Out << "#pragma omp end declare target\n";
368  }
369
370  if (!Decls.empty())
371    ProcessDeclGroup(Decls);
372
373  if (Indent)
374    Indentation -= Policy.Indentation;
375}
376
377void DeclPrinter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
378  VisitDeclContext(D, false);
379}
380
381void DeclPrinter::VisitTypedefDecl(TypedefDecl *D) {
382  if (!Policy.SuppressSpecifiers) {
383    Out << "typedef ";
384
385    if (D->isModulePrivate())
386      Out << "__module_private__ ";
387  }
388  QualType Ty = D->getTypeSourceInfo()->getType();
389  Ty.print(Out, Policy, D->getName(), Indentation);
390  prettyPrintAttributes(D);
391}
392
393void DeclPrinter::VisitTypeAliasDecl(TypeAliasDecl *D) {
394  Out << "using " << *D;
395  prettyPrintAttributes(D);
396  Out << " = " << D->getTypeSourceInfo()->getType().getAsString(Policy);
397}
398
399void DeclPrinter::VisitEnumDecl(EnumDecl *D) {
400  if (!Policy.SuppressSpecifiers && D->isModulePrivate())
401    Out << "__module_private__ ";
402  Out << "enum ";
403  if (D->isScoped()) {
404    if (D->isScopedUsingClassTag())
405      Out << "class ";
406    else
407      Out << "struct ";
408  }
409  Out << *D;
410
411  if (D->isFixed())
412    Out << " : " << D->getIntegerType().stream(Policy);
413
414  if (D->isCompleteDefinition()) {
415    Out << " {\n";
416    VisitDeclContext(D);
417    Indent() << "}";
418  }
419  prettyPrintAttributes(D);
420}
421
422void DeclPrinter::VisitRecordDecl(RecordDecl *D) {
423  if (!Policy.SuppressSpecifiers && D->isModulePrivate())
424    Out << "__module_private__ ";
425  Out << D->getKindName();
426
427  prettyPrintAttributes(D);
428
429  if (D->getIdentifier())
430    Out << ' ' << *D;
431
432  if (D->isCompleteDefinition()) {
433    Out << " {\n";
434    VisitDeclContext(D);
435    Indent() << "}";
436  }
437}
438
439void DeclPrinter::VisitEnumConstantDecl(EnumConstantDecl *D) {
440  Out << *D;
441  if (Expr *Init = D->getInitExpr()) {
442    Out << " = ";
443    Init->printPretty(Out, nullptr, Policy, Indentation);
444  }
445}
446
447void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) {
448  if (!D->getDescribedFunctionTemplate() &&
449      !D->isFunctionTemplateSpecialization())
450    prettyPrintPragmas(D);
451
452  CXXConstructorDecl *CDecl = dyn_cast<CXXConstructorDecl>(D);
453  CXXConversionDecl *ConversionDecl = dyn_cast<CXXConversionDecl>(D);
454  if (!Policy.SuppressSpecifiers) {
455    switch (D->getStorageClass()) {
456    case SC_None: break;
457    case SC_Extern: Out << "extern "; break;
458    case SC_Static: Out << "static "; break;
459    case SC_PrivateExtern: Out << "__private_extern__ "; break;
460    case SC_Auto: case SC_Register:
461      llvm_unreachable("invalid for functions");
462    }
463
464    if (D->isInlineSpecified())  Out << "inline ";
465    if (D->isVirtualAsWritten()) Out << "virtual ";
466    if (D->isModulePrivate())    Out << "__module_private__ ";
467    if (D->isConstexpr() && !D->isExplicitlyDefaulted()) Out << "constexpr ";
468    if ((CDecl && CDecl->isExplicitSpecified()) ||
469        (ConversionDecl && ConversionDecl->isExplicit()))
470      Out << "explicit ";
471  }
472
473  PrintingPolicy SubPolicy(Policy);
474  SubPolicy.SuppressSpecifiers = false;
475  std::string Proto = D->getNameInfo().getAsString();
476
477  QualType Ty = D->getType();
478  while (const ParenType *PT = dyn_cast<ParenType>(Ty)) {
479    Proto = '(' + Proto + ')';
480    Ty = PT->getInnerType();
481  }
482
483  if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
484    const FunctionProtoType *FT = nullptr;
485    if (D->hasWrittenPrototype())
486      FT = dyn_cast<FunctionProtoType>(AFT);
487
488    Proto += "(";
489    if (FT) {
490      llvm::raw_string_ostream POut(Proto);
491      DeclPrinter ParamPrinter(POut, SubPolicy, Indentation);
492      for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
493        if (i) POut << ", ";
494        ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
495      }
496
497      if (FT->isVariadic()) {
498        if (D->getNumParams()) POut << ", ";
499        POut << "...";
500      }
501    } else if (D->doesThisDeclarationHaveABody() && !D->hasPrototype()) {
502      for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
503        if (i)
504          Proto += ", ";
505        Proto += D->getParamDecl(i)->getNameAsString();
506      }
507    }
508
509    Proto += ")";
510
511    if (FT) {
512      if (FT->isConst())
513        Proto += " const";
514      if (FT->isVolatile())
515        Proto += " volatile";
516      if (FT->isRestrict())
517        Proto += " restrict";
518
519      switch (FT->getRefQualifier()) {
520      case RQ_None:
521        break;
522      case RQ_LValue:
523        Proto += " &";
524        break;
525      case RQ_RValue:
526        Proto += " &&";
527        break;
528      }
529    }
530
531    if (FT && FT->hasDynamicExceptionSpec()) {
532      Proto += " throw(";
533      if (FT->getExceptionSpecType() == EST_MSAny)
534        Proto += "...";
535      else
536        for (unsigned I = 0, N = FT->getNumExceptions(); I != N; ++I) {
537          if (I)
538            Proto += ", ";
539
540          Proto += FT->getExceptionType(I).getAsString(SubPolicy);
541        }
542      Proto += ")";
543    } else if (FT && isNoexceptExceptionSpec(FT->getExceptionSpecType())) {
544      Proto += " noexcept";
545      if (FT->getExceptionSpecType() == EST_ComputedNoexcept) {
546        Proto += "(";
547        llvm::raw_string_ostream EOut(Proto);
548        FT->getNoexceptExpr()->printPretty(EOut, nullptr, SubPolicy,
549                                           Indentation);
550        EOut.flush();
551        Proto += EOut.str();
552        Proto += ")";
553      }
554    }
555
556    if (CDecl) {
557      bool HasInitializerList = false;
558      for (const auto *BMInitializer : CDecl->inits()) {
559        if (BMInitializer->isInClassMemberInitializer())
560          continue;
561
562        if (!HasInitializerList) {
563          Proto += " : ";
564          Out << Proto;
565          Proto.clear();
566          HasInitializerList = true;
567        } else
568          Out << ", ";
569
570        if (BMInitializer->isAnyMemberInitializer()) {
571          FieldDecl *FD = BMInitializer->getAnyMember();
572          Out << *FD;
573        } else {
574          Out << QualType(BMInitializer->getBaseClass(), 0).getAsString(Policy);
575        }
576
577        Out << "(";
578        if (!BMInitializer->getInit()) {
579          // Nothing to print
580        } else {
581          Expr *Init = BMInitializer->getInit();
582          if (ExprWithCleanups *Tmp = dyn_cast<ExprWithCleanups>(Init))
583            Init = Tmp->getSubExpr();
584
585          Init = Init->IgnoreParens();
586
587          Expr *SimpleInit = nullptr;
588          Expr **Args = nullptr;
589          unsigned NumArgs = 0;
590          if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
591            Args = ParenList->getExprs();
592            NumArgs = ParenList->getNumExprs();
593          } else if (CXXConstructExpr *Construct
594                                        = dyn_cast<CXXConstructExpr>(Init)) {
595            Args = Construct->getArgs();
596            NumArgs = Construct->getNumArgs();
597          } else
598            SimpleInit = Init;
599
600          if (SimpleInit)
601            SimpleInit->printPretty(Out, nullptr, Policy, Indentation);
602          else {
603            for (unsigned I = 0; I != NumArgs; ++I) {
604              assert(Args[I] != nullptr && "Expected non-null Expr");
605              if (isa<CXXDefaultArgExpr>(Args[I]))
606                break;
607
608              if (I)
609                Out << ", ";
610              Args[I]->printPretty(Out, nullptr, Policy, Indentation);
611            }
612          }
613        }
614        Out << ")";
615        if (BMInitializer->isPackExpansion())
616          Out << "...";
617      }
618    } else if (!ConversionDecl && !isa<CXXDestructorDecl>(D)) {
619      if (FT && FT->hasTrailingReturn()) {
620        Out << "auto " << Proto << " -> ";
621        Proto.clear();
622      }
623      AFT->getReturnType().print(Out, Policy, Proto);
624      Proto.clear();
625    }
626    Out << Proto;
627  } else {
628    Ty.print(Out, Policy, Proto);
629  }
630
631  prettyPrintAttributes(D);
632
633  if (D->isPure())
634    Out << " = 0";
635  else if (D->isDeletedAsWritten())
636    Out << " = delete";
637  else if (D->isExplicitlyDefaulted())
638    Out << " = default";
639  else if (D->doesThisDeclarationHaveABody() && !Policy.TerseOutput) {
640    if (!D->hasPrototype() && D->getNumParams()) {
641      // This is a K&R function definition, so we need to print the
642      // parameters.
643      Out << '\n';
644      DeclPrinter ParamPrinter(Out, SubPolicy, Indentation);
645      Indentation += Policy.Indentation;
646      for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
647        Indent();
648        ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
649        Out << ";\n";
650      }
651      Indentation -= Policy.Indentation;
652    } else
653      Out << ' ';
654
655    if (D->getBody())
656      D->getBody()->printPretty(Out, nullptr, SubPolicy, Indentation);
657    Out << '\n';
658  }
659}
660
661void DeclPrinter::VisitFriendDecl(FriendDecl *D) {
662  if (TypeSourceInfo *TSI = D->getFriendType()) {
663    unsigned NumTPLists = D->getFriendTypeNumTemplateParameterLists();
664    for (unsigned i = 0; i < NumTPLists; ++i)
665      PrintTemplateParameters(D->getFriendTypeTemplateParameterList(i));
666    Out << "friend ";
667    Out << " " << TSI->getType().getAsString(Policy);
668  }
669  else if (FunctionDecl *FD =
670      dyn_cast<FunctionDecl>(D->getFriendDecl())) {
671    Out << "friend ";
672    VisitFunctionDecl(FD);
673  }
674  else if (FunctionTemplateDecl *FTD =
675           dyn_cast<FunctionTemplateDecl>(D->getFriendDecl())) {
676    Out << "friend ";
677    VisitFunctionTemplateDecl(FTD);
678  }
679  else if (ClassTemplateDecl *CTD =
680           dyn_cast<ClassTemplateDecl>(D->getFriendDecl())) {
681    Out << "friend ";
682    VisitRedeclarableTemplateDecl(CTD);
683  }
684}
685
686void DeclPrinter::VisitFieldDecl(FieldDecl *D) {
687  // FIXME: add printing of pragma attributes if required.
688  if (!Policy.SuppressSpecifiers && D->isMutable())
689    Out << "mutable ";
690  if (!Policy.SuppressSpecifiers && D->isModulePrivate())
691    Out << "__module_private__ ";
692
693  Out << D->getASTContext().getUnqualifiedObjCPointerType(D->getType()).
694         stream(Policy, D->getName(), Indentation);
695
696  if (D->isBitField()) {
697    Out << " : ";
698    D->getBitWidth()->printPretty(Out, nullptr, Policy, Indentation);
699  }
700
701  Expr *Init = D->getInClassInitializer();
702  if (!Policy.SuppressInitializers && Init) {
703    if (D->getInClassInitStyle() == ICIS_ListInit)
704      Out << " ";
705    else
706      Out << " = ";
707    Init->printPretty(Out, nullptr, Policy, Indentation);
708  }
709  prettyPrintAttributes(D);
710}
711
712void DeclPrinter::VisitLabelDecl(LabelDecl *D) {
713  Out << *D << ":";
714}
715
716void DeclPrinter::VisitVarDecl(VarDecl *D) {
717  prettyPrintPragmas(D);
718
719  QualType T = D->getTypeSourceInfo()
720    ? D->getTypeSourceInfo()->getType()
721    : D->getASTContext().getUnqualifiedObjCPointerType(D->getType());
722
723  if (!Policy.SuppressSpecifiers) {
724    StorageClass SC = D->getStorageClass();
725    if (SC != SC_None)
726      Out << VarDecl::getStorageClassSpecifierString(SC) << " ";
727
728    switch (D->getTSCSpec()) {
729    case TSCS_unspecified:
730      break;
731    case TSCS___thread:
732      Out << "__thread ";
733      break;
734    case TSCS__Thread_local:
735      Out << "_Thread_local ";
736      break;
737    case TSCS_thread_local:
738      Out << "thread_local ";
739      break;
740    }
741
742    if (D->isModulePrivate())
743      Out << "__module_private__ ";
744
745    if (D->isConstexpr()) {
746      Out << "constexpr ";
747      T.removeLocalConst();
748    }
749  }
750
751  printDeclType(T, D->getName());
752  Expr *Init = D->getInit();
753  if (!Policy.SuppressInitializers && Init) {
754    bool ImplicitInit = false;
755    if (CXXConstructExpr *Construct =
756            dyn_cast<CXXConstructExpr>(Init->IgnoreImplicit())) {
757      if (D->getInitStyle() == VarDecl::CallInit &&
758          !Construct->isListInitialization()) {
759        ImplicitInit = Construct->getNumArgs() == 0 ||
760          Construct->getArg(0)->isDefaultArgument();
761      }
762    }
763    if (!ImplicitInit) {
764      if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
765        Out << "(";
766      else if (D->getInitStyle() == VarDecl::CInit) {
767        Out << " = ";
768      }
769      PrintingPolicy SubPolicy(Policy);
770      SubPolicy.SuppressSpecifiers = false;
771      SubPolicy.IncludeTagDefinition = false;
772      Init->printPretty(Out, nullptr, SubPolicy, Indentation);
773      if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
774        Out << ")";
775    }
776  }
777  prettyPrintAttributes(D);
778}
779
780void DeclPrinter::VisitParmVarDecl(ParmVarDecl *D) {
781  VisitVarDecl(D);
782}
783
784void DeclPrinter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) {
785  Out << "__asm (";
786  D->getAsmString()->printPretty(Out, nullptr, Policy, Indentation);
787  Out << ")";
788}
789
790void DeclPrinter::VisitImportDecl(ImportDecl *D) {
791  Out << "@import " << D->getImportedModule()->getFullModuleName()
792      << ";\n";
793}
794
795void DeclPrinter::VisitStaticAssertDecl(StaticAssertDecl *D) {
796  Out << "static_assert(";
797  D->getAssertExpr()->printPretty(Out, nullptr, Policy, Indentation);
798  if (StringLiteral *SL = D->getMessage()) {
799    Out << ", ";
800    SL->printPretty(Out, nullptr, Policy, Indentation);
801  }
802  Out << ")";
803}
804
805//----------------------------------------------------------------------------
806// C++ declarations
807//----------------------------------------------------------------------------
808void DeclPrinter::VisitNamespaceDecl(NamespaceDecl *D) {
809  if (D->isInline())
810    Out << "inline ";
811  Out << "namespace " << *D << " {\n";
812  VisitDeclContext(D);
813  Indent() << "}";
814}
815
816void DeclPrinter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
817  Out << "using namespace ";
818  if (D->getQualifier())
819    D->getQualifier()->print(Out, Policy);
820  Out << *D->getNominatedNamespaceAsWritten();
821}
822
823void DeclPrinter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
824  Out << "namespace " << *D << " = ";
825  if (D->getQualifier())
826    D->getQualifier()->print(Out, Policy);
827  Out << *D->getAliasedNamespace();
828}
829
830void DeclPrinter::VisitEmptyDecl(EmptyDecl *D) {
831  prettyPrintAttributes(D);
832}
833
834void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) {
835  // FIXME: add printing of pragma attributes if required.
836  if (!Policy.SuppressSpecifiers && D->isModulePrivate())
837    Out << "__module_private__ ";
838  Out << D->getKindName();
839
840  prettyPrintAttributes(D);
841
842  if (D->getIdentifier())
843    Out << ' ' << *D;
844
845  if (D->isCompleteDefinition()) {
846    // Print the base classes
847    if (D->getNumBases()) {
848      Out << " : ";
849      for (CXXRecordDecl::base_class_iterator Base = D->bases_begin(),
850             BaseEnd = D->bases_end(); Base != BaseEnd; ++Base) {
851        if (Base != D->bases_begin())
852          Out << ", ";
853
854        if (Base->isVirtual())
855          Out << "virtual ";
856
857        AccessSpecifier AS = Base->getAccessSpecifierAsWritten();
858        if (AS != AS_none) {
859          Print(AS);
860          Out << " ";
861        }
862        Out << Base->getType().getAsString(Policy);
863
864        if (Base->isPackExpansion())
865          Out << "...";
866      }
867    }
868
869    // Print the class definition
870    // FIXME: Doesn't print access specifiers, e.g., "public:"
871    Out << " {\n";
872    VisitDeclContext(D);
873    Indent() << "}";
874  }
875}
876
877void DeclPrinter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
878  const char *l;
879  if (D->getLanguage() == LinkageSpecDecl::lang_c)
880    l = "C";
881  else {
882    assert(D->getLanguage() == LinkageSpecDecl::lang_cxx &&
883           "unknown language in linkage specification");
884    l = "C++";
885  }
886
887  Out << "extern \"" << l << "\" ";
888  if (D->hasBraces()) {
889    Out << "{\n";
890    VisitDeclContext(D);
891    Indent() << "}";
892  } else
893    Visit(*D->decls_begin());
894}
895
896void DeclPrinter::PrintTemplateParameters(const TemplateParameterList *Params,
897                                          const TemplateArgumentList *Args) {
898  assert(Params);
899  assert(!Args || Params->size() == Args->size());
900
901  Out << "template <";
902
903  for (unsigned i = 0, e = Params->size(); i != e; ++i) {
904    if (i != 0)
905      Out << ", ";
906
907    const Decl *Param = Params->getParam(i);
908    if (const TemplateTypeParmDecl *TTP =
909          dyn_cast<TemplateTypeParmDecl>(Param)) {
910
911      if (TTP->wasDeclaredWithTypename())
912        Out << "typename ";
913      else
914        Out << "class ";
915
916      if (TTP->isParameterPack())
917        Out << "...";
918
919      Out << *TTP;
920
921      if (Args) {
922        Out << " = ";
923        Args->get(i).print(Policy, Out);
924      } else if (TTP->hasDefaultArgument()) {
925        Out << " = ";
926        Out << TTP->getDefaultArgument().getAsString(Policy);
927      };
928    } else if (const NonTypeTemplateParmDecl *NTTP =
929                 dyn_cast<NonTypeTemplateParmDecl>(Param)) {
930      StringRef Name;
931      if (IdentifierInfo *II = NTTP->getIdentifier())
932        Name = II->getName();
933      printDeclType(NTTP->getType(), Name, NTTP->isParameterPack());
934
935      if (Args) {
936        Out << " = ";
937        Args->get(i).print(Policy, Out);
938      } else if (NTTP->hasDefaultArgument()) {
939        Out << " = ";
940        NTTP->getDefaultArgument()->printPretty(Out, nullptr, Policy,
941                                                Indentation);
942      }
943    } else if (const TemplateTemplateParmDecl *TTPD =
944                 dyn_cast<TemplateTemplateParmDecl>(Param)) {
945      VisitTemplateDecl(TTPD);
946      // FIXME: print the default argument, if present.
947    }
948  }
949
950  Out << "> ";
951}
952
953void DeclPrinter::VisitTemplateDecl(const TemplateDecl *D) {
954  PrintTemplateParameters(D->getTemplateParameters());
955
956  if (const TemplateTemplateParmDecl *TTP =
957        dyn_cast<TemplateTemplateParmDecl>(D)) {
958    Out << "class ";
959    if (TTP->isParameterPack())
960      Out << "...";
961    Out << D->getName();
962  } else {
963    Visit(D->getTemplatedDecl());
964  }
965}
966
967void DeclPrinter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
968  if (PrintInstantiation) {
969    TemplateParameterList *Params = D->getTemplateParameters();
970    for (auto *I : D->specializations()) {
971      prettyPrintPragmas(I);
972      PrintTemplateParameters(Params, I->getTemplateSpecializationArgs());
973      Visit(I);
974    }
975  }
976
977  prettyPrintPragmas(D->getTemplatedDecl());
978  return VisitRedeclarableTemplateDecl(D);
979}
980
981void DeclPrinter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
982  if (PrintInstantiation) {
983    TemplateParameterList *Params = D->getTemplateParameters();
984    for (auto *I : D->specializations()) {
985      PrintTemplateParameters(Params, &I->getTemplateArgs());
986      Visit(I);
987      Out << '\n';
988    }
989  }
990
991  return VisitRedeclarableTemplateDecl(D);
992}
993
994//----------------------------------------------------------------------------
995// Objective-C declarations
996//----------------------------------------------------------------------------
997
998void DeclPrinter::PrintObjCMethodType(ASTContext &Ctx,
999                                      Decl::ObjCDeclQualifier Quals,
1000                                      QualType T) {
1001  Out << '(';
1002  if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_In)
1003    Out << "in ";
1004  if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Inout)
1005    Out << "inout ";
1006  if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Out)
1007    Out << "out ";
1008  if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Bycopy)
1009    Out << "bycopy ";
1010  if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Byref)
1011    Out << "byref ";
1012  if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Oneway)
1013    Out << "oneway ";
1014  if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_CSNullability) {
1015    if (auto nullability = AttributedType::stripOuterNullability(T))
1016      Out << getNullabilitySpelling(*nullability, true) << ' ';
1017  }
1018
1019  Out << Ctx.getUnqualifiedObjCPointerType(T).getAsString(Policy);
1020  Out << ')';
1021}
1022
1023void DeclPrinter::PrintObjCTypeParams(ObjCTypeParamList *Params) {
1024  Out << "<";
1025  unsigned First = true;
1026  for (auto *Param : *Params) {
1027    if (First) {
1028      First = false;
1029    } else {
1030      Out << ", ";
1031    }
1032
1033    switch (Param->getVariance()) {
1034    case ObjCTypeParamVariance::Invariant:
1035      break;
1036
1037    case ObjCTypeParamVariance::Covariant:
1038      Out << "__covariant ";
1039      break;
1040
1041    case ObjCTypeParamVariance::Contravariant:
1042      Out << "__contravariant ";
1043      break;
1044    }
1045
1046    Out << Param->getDeclName().getAsString();
1047
1048    if (Param->hasExplicitBound()) {
1049      Out << " : " << Param->getUnderlyingType().getAsString(Policy);
1050    }
1051  }
1052  Out << ">";
1053}
1054
1055void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) {
1056  if (OMD->isInstanceMethod())
1057    Out << "- ";
1058  else
1059    Out << "+ ";
1060  if (!OMD->getReturnType().isNull()) {
1061    PrintObjCMethodType(OMD->getASTContext(), OMD->getObjCDeclQualifier(),
1062                        OMD->getReturnType());
1063  }
1064
1065  std::string name = OMD->getSelector().getAsString();
1066  std::string::size_type pos, lastPos = 0;
1067  for (const auto *PI : OMD->parameters()) {
1068    // FIXME: selector is missing here!
1069    pos = name.find_first_of(':', lastPos);
1070    Out << " " << name.substr(lastPos, pos - lastPos) << ':';
1071    PrintObjCMethodType(OMD->getASTContext(),
1072                        PI->getObjCDeclQualifier(),
1073                        PI->getType());
1074    Out << *PI;
1075    lastPos = pos + 1;
1076  }
1077
1078  if (OMD->param_begin() == OMD->param_end())
1079    Out << " " << name;
1080
1081  if (OMD->isVariadic())
1082      Out << ", ...";
1083
1084  prettyPrintAttributes(OMD);
1085
1086  if (OMD->getBody() && !Policy.TerseOutput) {
1087    Out << ' ';
1088    OMD->getBody()->printPretty(Out, nullptr, Policy);
1089  }
1090  else if (Policy.PolishForDeclaration)
1091    Out << ';';
1092}
1093
1094void DeclPrinter::VisitObjCImplementationDecl(ObjCImplementationDecl *OID) {
1095  std::string I = OID->getNameAsString();
1096  ObjCInterfaceDecl *SID = OID->getSuperClass();
1097
1098  bool eolnOut = false;
1099  if (SID)
1100    Out << "@implementation " << I << " : " << *SID;
1101  else
1102    Out << "@implementation " << I;
1103
1104  if (OID->ivar_size() > 0) {
1105    Out << "{\n";
1106    eolnOut = true;
1107    Indentation += Policy.Indentation;
1108    for (const auto *I : OID->ivars()) {
1109      Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).
1110                    getAsString(Policy) << ' ' << *I << ";\n";
1111    }
1112    Indentation -= Policy.Indentation;
1113    Out << "}\n";
1114  }
1115  else if (SID || (OID->decls_begin() != OID->decls_end())) {
1116    Out << "\n";
1117    eolnOut = true;
1118  }
1119  VisitDeclContext(OID, false);
1120  if (!eolnOut)
1121    Out << "\n";
1122  Out << "@end";
1123}
1124
1125void DeclPrinter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *OID) {
1126  std::string I = OID->getNameAsString();
1127  ObjCInterfaceDecl *SID = OID->getSuperClass();
1128
1129  if (!OID->isThisDeclarationADefinition()) {
1130    Out << "@class " << I;
1131
1132    if (auto TypeParams = OID->getTypeParamListAsWritten()) {
1133      PrintObjCTypeParams(TypeParams);
1134    }
1135
1136    Out << ";";
1137    return;
1138  }
1139  bool eolnOut = false;
1140  Out << "@interface " << I;
1141
1142  if (auto TypeParams = OID->getTypeParamListAsWritten()) {
1143    PrintObjCTypeParams(TypeParams);
1144  }
1145
1146  if (SID)
1147    Out << " : " << QualType(OID->getSuperClassType(), 0).getAsString(Policy);
1148
1149  // Protocols?
1150  const ObjCList<ObjCProtocolDecl> &Protocols = OID->getReferencedProtocols();
1151  if (!Protocols.empty()) {
1152    for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1153         E = Protocols.end(); I != E; ++I)
1154      Out << (I == Protocols.begin() ? '<' : ',') << **I;
1155    Out << "> ";
1156  }
1157
1158  if (OID->ivar_size() > 0) {
1159    Out << "{\n";
1160    eolnOut = true;
1161    Indentation += Policy.Indentation;
1162    for (const auto *I : OID->ivars()) {
1163      Indent() << I->getASTContext()
1164                      .getUnqualifiedObjCPointerType(I->getType())
1165                      .getAsString(Policy) << ' ' << *I << ";\n";
1166    }
1167    Indentation -= Policy.Indentation;
1168    Out << "}\n";
1169  }
1170  else if (SID || (OID->decls_begin() != OID->decls_end())) {
1171    Out << "\n";
1172    eolnOut = true;
1173  }
1174
1175  VisitDeclContext(OID, false);
1176  if (!eolnOut)
1177    Out << "\n";
1178  Out << "@end";
1179  // FIXME: implement the rest...
1180}
1181
1182void DeclPrinter::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1183  if (!PID->isThisDeclarationADefinition()) {
1184    Out << "@protocol " << *PID << ";\n";
1185    return;
1186  }
1187  // Protocols?
1188  const ObjCList<ObjCProtocolDecl> &Protocols = PID->getReferencedProtocols();
1189  if (!Protocols.empty()) {
1190    Out << "@protocol " << *PID;
1191    for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1192         E = Protocols.end(); I != E; ++I)
1193      Out << (I == Protocols.begin() ? '<' : ',') << **I;
1194    Out << ">\n";
1195  } else
1196    Out << "@protocol " << *PID << '\n';
1197  VisitDeclContext(PID, false);
1198  Out << "@end";
1199}
1200
1201void DeclPrinter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *PID) {
1202  Out << "@implementation " << *PID->getClassInterface() << '(' << *PID <<")\n";
1203
1204  VisitDeclContext(PID, false);
1205  Out << "@end";
1206  // FIXME: implement the rest...
1207}
1208
1209void DeclPrinter::VisitObjCCategoryDecl(ObjCCategoryDecl *PID) {
1210  Out << "@interface " << *PID->getClassInterface();
1211  if (auto TypeParams = PID->getTypeParamList()) {
1212    PrintObjCTypeParams(TypeParams);
1213  }
1214  Out << "(" << *PID << ")\n";
1215  if (PID->ivar_size() > 0) {
1216    Out << "{\n";
1217    Indentation += Policy.Indentation;
1218    for (const auto *I : PID->ivars())
1219      Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).
1220                    getAsString(Policy) << ' ' << *I << ";\n";
1221    Indentation -= Policy.Indentation;
1222    Out << "}\n";
1223  }
1224
1225  VisitDeclContext(PID, false);
1226  Out << "@end";
1227
1228  // FIXME: implement the rest...
1229}
1230
1231void DeclPrinter::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *AID) {
1232  Out << "@compatibility_alias " << *AID
1233      << ' ' << *AID->getClassInterface() << ";\n";
1234}
1235
1236/// PrintObjCPropertyDecl - print a property declaration.
1237///
1238void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) {
1239  if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Required)
1240    Out << "@required\n";
1241  else if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Optional)
1242    Out << "@optional\n";
1243
1244  QualType T = PDecl->getType();
1245
1246  Out << "@property";
1247  if (PDecl->getPropertyAttributes() != ObjCPropertyDecl::OBJC_PR_noattr) {
1248    bool first = true;
1249    Out << " (";
1250    if (PDecl->getPropertyAttributes() &
1251        ObjCPropertyDecl::OBJC_PR_readonly) {
1252      Out << (first ? ' ' : ',') << "readonly";
1253      first = false;
1254    }
1255
1256    if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
1257      Out << (first ? ' ' : ',') << "getter = ";
1258      PDecl->getGetterName().print(Out);
1259      first = false;
1260    }
1261    if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
1262      Out << (first ? ' ' : ',') << "setter = ";
1263      PDecl->getSetterName().print(Out);
1264      first = false;
1265    }
1266
1267    if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_assign) {
1268      Out << (first ? ' ' : ',') << "assign";
1269      first = false;
1270    }
1271
1272    if (PDecl->getPropertyAttributes() &
1273        ObjCPropertyDecl::OBJC_PR_readwrite) {
1274      Out << (first ? ' ' : ',') << "readwrite";
1275      first = false;
1276    }
1277
1278    if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain) {
1279      Out << (first ? ' ' : ',') << "retain";
1280      first = false;
1281    }
1282
1283    if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_strong) {
1284      Out << (first ? ' ' : ',') << "strong";
1285      first = false;
1286    }
1287
1288    if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy) {
1289      Out << (first ? ' ' : ',') << "copy";
1290      first = false;
1291    }
1292
1293    if (PDecl->getPropertyAttributes() &
1294        ObjCPropertyDecl::OBJC_PR_nonatomic) {
1295      Out << (first ? ' ' : ',') << "nonatomic";
1296      first = false;
1297    }
1298    if (PDecl->getPropertyAttributes() &
1299        ObjCPropertyDecl::OBJC_PR_atomic) {
1300      Out << (first ? ' ' : ',') << "atomic";
1301      first = false;
1302    }
1303
1304    if (PDecl->getPropertyAttributes() &
1305        ObjCPropertyDecl::OBJC_PR_nullability) {
1306      if (auto nullability = AttributedType::stripOuterNullability(T)) {
1307        if (*nullability == NullabilityKind::Unspecified &&
1308            (PDecl->getPropertyAttributes() &
1309               ObjCPropertyDecl::OBJC_PR_null_resettable)) {
1310          Out << (first ? ' ' : ',') << "null_resettable";
1311        } else {
1312          Out << (first ? ' ' : ',')
1313              << getNullabilitySpelling(*nullability, true);
1314        }
1315        first = false;
1316      }
1317    }
1318
1319    if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_class) {
1320      Out << (first ? ' ' : ',') << "class";
1321      first = false;
1322    }
1323
1324    (void) first; // Silence dead store warning due to idiomatic code.
1325    Out << " )";
1326  }
1327  Out << ' ' << PDecl->getASTContext().getUnqualifiedObjCPointerType(T).
1328                  getAsString(Policy) << ' ' << *PDecl;
1329  if (Policy.PolishForDeclaration)
1330    Out << ';';
1331}
1332
1333void DeclPrinter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PID) {
1334  if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize)
1335    Out << "@synthesize ";
1336  else
1337    Out << "@dynamic ";
1338  Out << *PID->getPropertyDecl();
1339  if (PID->getPropertyIvarDecl())
1340    Out << '=' << *PID->getPropertyIvarDecl();
1341}
1342
1343void DeclPrinter::VisitUsingDecl(UsingDecl *D) {
1344  if (!D->isAccessDeclaration())
1345    Out << "using ";
1346  if (D->hasTypename())
1347    Out << "typename ";
1348  D->getQualifier()->print(Out, Policy);
1349  Out << *D;
1350}
1351
1352void
1353DeclPrinter::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
1354  Out << "using typename ";
1355  D->getQualifier()->print(Out, Policy);
1356  Out << D->getDeclName();
1357}
1358
1359void DeclPrinter::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1360  if (!D->isAccessDeclaration())
1361    Out << "using ";
1362  D->getQualifier()->print(Out, Policy);
1363  Out << D->getDeclName();
1364}
1365
1366void DeclPrinter::VisitUsingShadowDecl(UsingShadowDecl *D) {
1367  // ignore
1368}
1369
1370void DeclPrinter::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
1371  Out << "#pragma omp threadprivate";
1372  if (!D->varlist_empty()) {
1373    for (OMPThreadPrivateDecl::varlist_iterator I = D->varlist_begin(),
1374                                                E = D->varlist_end();
1375                                                I != E; ++I) {
1376      Out << (I == D->varlist_begin() ? '(' : ',');
1377      NamedDecl *ND = cast<NamedDecl>(cast<DeclRefExpr>(*I)->getDecl());
1378      ND->printQualifiedName(Out);
1379    }
1380    Out << ")";
1381  }
1382}
1383
1384void DeclPrinter::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
1385  if (!D->isInvalidDecl()) {
1386    Out << "#pragma omp declare reduction (";
1387    if (D->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) {
1388      static const char *const OperatorNames[NUM_OVERLOADED_OPERATORS] = {
1389          nullptr,
1390#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly)  \
1391          Spelling,
1392#include "clang/Basic/OperatorKinds.def"
1393      };
1394      const char *OpName =
1395          OperatorNames[D->getDeclName().getCXXOverloadedOperator()];
1396      assert(OpName && "not an overloaded operator");
1397      Out << OpName;
1398    } else {
1399      assert(D->getDeclName().isIdentifier());
1400      D->printName(Out);
1401    }
1402    Out << " : ";
1403    D->getType().print(Out, Policy);
1404    Out << " : ";
1405    D->getCombiner()->printPretty(Out, nullptr, Policy, 0);
1406    Out << ")";
1407    if (auto *Init = D->getInitializer()) {
1408      Out << " initializer(";
1409      Init->printPretty(Out, nullptr, Policy, 0);
1410      Out << ")";
1411    }
1412  }
1413}
1414
1415void DeclPrinter::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
1416  D->getInit()->printPretty(Out, nullptr, Policy, Indentation);
1417}
1418
1419