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"
25 using namespace clang;
26 
27 namespace {
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 
93 void Decl::print(raw_ostream &Out, unsigned Indentation,
94                  bool PrintInstantiation) const {
95   print(Out, getASTContext().getPrintingPolicy(), Indentation, PrintInstantiation);
96 }
97 
98 void 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 
104 static 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->getReturnType();
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 
128 static 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 
136 void 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 
170 LLVM_DUMP_METHOD void 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 
181 raw_ostream& DeclPrinter::Indent(unsigned Indentation) {
182   for (unsigned i = 0; i != Indentation; ++i)
183     Out << "  ";
184   return Out;
185 }
186 
187 void 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 
200 void 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 
208 void 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 
221 void 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     // The next bits of code handles stuff like "struct {int x;} a,b"; we're
242     // forced to merge the declarations because there's no other way to
243     // refer to the struct in question.  This limited merging is safe without
244     // a bunch of other checks because it only merges declarations directly
245     // referring to the tag, not typedefs.
246     //
247     // Check whether the current declaration should be grouped with a previous
248     // unnamed struct.
249     QualType CurDeclType = getDeclType(*D);
250     if (!Decls.empty() && !CurDeclType.isNull()) {
251       QualType BaseType = GetBaseType(CurDeclType);
252       if (!BaseType.isNull() && isa<ElaboratedType>(BaseType))
253         BaseType = cast<ElaboratedType>(BaseType)->getNamedType();
254       if (!BaseType.isNull() && isa<TagType>(BaseType) &&
255           cast<TagType>(BaseType)->getDecl() == Decls[0]) {
256         Decls.push_back(*D);
257         continue;
258       }
259     }
260 
261     // If we have a merged group waiting to be handled, handle it now.
262     if (!Decls.empty())
263       ProcessDeclGroup(Decls);
264 
265     // If the current declaration is an unnamed tag type, save it
266     // so we can merge it with the subsequent declaration(s) using it.
267     if (isa<TagDecl>(*D) && !cast<TagDecl>(*D)->getIdentifier()) {
268       Decls.push_back(*D);
269       continue;
270     }
271 
272     if (isa<AccessSpecDecl>(*D)) {
273       Indentation -= Policy.Indentation;
274       this->Indent();
275       Print(D->getAccess());
276       Out << ":\n";
277       Indentation += Policy.Indentation;
278       continue;
279     }
280 
281     this->Indent();
282     Visit(*D);
283 
284     // FIXME: Need to be able to tell the DeclPrinter when
285     const char *Terminator = 0;
286     if (isa<OMPThreadPrivateDecl>(*D))
287       Terminator = 0;
288     else if (isa<FunctionDecl>(*D) &&
289              cast<FunctionDecl>(*D)->isThisDeclarationADefinition())
290       Terminator = 0;
291     else if (isa<ObjCMethodDecl>(*D) && cast<ObjCMethodDecl>(*D)->getBody())
292       Terminator = 0;
293     else if (isa<NamespaceDecl>(*D) || isa<LinkageSpecDecl>(*D) ||
294              isa<ObjCImplementationDecl>(*D) ||
295              isa<ObjCInterfaceDecl>(*D) ||
296              isa<ObjCProtocolDecl>(*D) ||
297              isa<ObjCCategoryImplDecl>(*D) ||
298              isa<ObjCCategoryDecl>(*D))
299       Terminator = 0;
300     else if (isa<EnumConstantDecl>(*D)) {
301       DeclContext::decl_iterator Next = D;
302       ++Next;
303       if (Next != DEnd)
304         Terminator = ",";
305     } else
306       Terminator = ";";
307 
308     if (Terminator)
309       Out << Terminator;
310     Out << "\n";
311   }
312 
313   if (!Decls.empty())
314     ProcessDeclGroup(Decls);
315 
316   if (Indent)
317     Indentation -= Policy.Indentation;
318 }
319 
320 void DeclPrinter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
321   VisitDeclContext(D, false);
322 }
323 
324 void DeclPrinter::VisitTypedefDecl(TypedefDecl *D) {
325   if (!Policy.SuppressSpecifiers) {
326     Out << "typedef ";
327 
328     if (D->isModulePrivate())
329       Out << "__module_private__ ";
330   }
331   D->getTypeSourceInfo()->getType().print(Out, Policy, D->getName());
332   prettyPrintAttributes(D);
333 }
334 
335 void DeclPrinter::VisitTypeAliasDecl(TypeAliasDecl *D) {
336   Out << "using " << *D;
337   prettyPrintAttributes(D);
338   Out << " = " << D->getTypeSourceInfo()->getType().getAsString(Policy);
339 }
340 
341 void DeclPrinter::VisitEnumDecl(EnumDecl *D) {
342   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
343     Out << "__module_private__ ";
344   Out << "enum ";
345   if (D->isScoped()) {
346     if (D->isScopedUsingClassTag())
347       Out << "class ";
348     else
349       Out << "struct ";
350   }
351   Out << *D;
352 
353   if (D->isFixed())
354     Out << " : " << D->getIntegerType().stream(Policy);
355 
356   if (D->isCompleteDefinition()) {
357     Out << " {\n";
358     VisitDeclContext(D);
359     Indent() << "}";
360   }
361   prettyPrintAttributes(D);
362 }
363 
364 void DeclPrinter::VisitRecordDecl(RecordDecl *D) {
365   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
366     Out << "__module_private__ ";
367   Out << D->getKindName();
368   if (D->getIdentifier())
369     Out << ' ' << *D;
370 
371   if (D->isCompleteDefinition()) {
372     Out << " {\n";
373     VisitDeclContext(D);
374     Indent() << "}";
375   }
376 }
377 
378 void DeclPrinter::VisitEnumConstantDecl(EnumConstantDecl *D) {
379   Out << *D;
380   if (Expr *Init = D->getInitExpr()) {
381     Out << " = ";
382     Init->printPretty(Out, 0, Policy, Indentation);
383   }
384 }
385 
386 void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) {
387   CXXConstructorDecl *CDecl = dyn_cast<CXXConstructorDecl>(D);
388   CXXConversionDecl *ConversionDecl = dyn_cast<CXXConversionDecl>(D);
389   if (!Policy.SuppressSpecifiers) {
390     switch (D->getStorageClass()) {
391     case SC_None: break;
392     case SC_Extern: Out << "extern "; break;
393     case SC_Static: Out << "static "; break;
394     case SC_PrivateExtern: Out << "__private_extern__ "; break;
395     case SC_Auto: case SC_Register: case SC_OpenCLWorkGroupLocal:
396       llvm_unreachable("invalid for functions");
397     }
398 
399     if (D->isInlineSpecified())  Out << "inline ";
400     if (D->isVirtualAsWritten()) Out << "virtual ";
401     if (D->isModulePrivate())    Out << "__module_private__ ";
402     if (D->isConstexpr() && !D->isExplicitlyDefaulted()) Out << "constexpr ";
403     if ((CDecl && CDecl->isExplicitSpecified()) ||
404         (ConversionDecl && ConversionDecl->isExplicit()))
405       Out << "explicit ";
406   }
407 
408   PrintingPolicy SubPolicy(Policy);
409   SubPolicy.SuppressSpecifiers = false;
410   std::string Proto = D->getNameInfo().getAsString();
411 
412   QualType Ty = D->getType();
413   while (const ParenType *PT = dyn_cast<ParenType>(Ty)) {
414     Proto = '(' + Proto + ')';
415     Ty = PT->getInnerType();
416   }
417 
418   if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
419     const FunctionProtoType *FT = 0;
420     if (D->hasWrittenPrototype())
421       FT = dyn_cast<FunctionProtoType>(AFT);
422 
423     Proto += "(";
424     if (FT) {
425       llvm::raw_string_ostream POut(Proto);
426       DeclPrinter ParamPrinter(POut, SubPolicy, Indentation);
427       for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
428         if (i) POut << ", ";
429         ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
430       }
431 
432       if (FT->isVariadic()) {
433         if (D->getNumParams()) POut << ", ";
434         POut << "...";
435       }
436     } else if (D->doesThisDeclarationHaveABody() && !D->hasPrototype()) {
437       for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
438         if (i)
439           Proto += ", ";
440         Proto += D->getParamDecl(i)->getNameAsString();
441       }
442     }
443 
444     Proto += ")";
445 
446     if (FT) {
447       if (FT->isConst())
448         Proto += " const";
449       if (FT->isVolatile())
450         Proto += " volatile";
451       if (FT->isRestrict())
452         Proto += " restrict";
453 
454       switch (FT->getRefQualifier()) {
455       case RQ_None:
456         break;
457       case RQ_LValue:
458         Proto += " &";
459         break;
460       case RQ_RValue:
461         Proto += " &&";
462         break;
463       }
464     }
465 
466     if (FT && FT->hasDynamicExceptionSpec()) {
467       Proto += " throw(";
468       if (FT->getExceptionSpecType() == EST_MSAny)
469         Proto += "...";
470       else
471         for (unsigned I = 0, N = FT->getNumExceptions(); I != N; ++I) {
472           if (I)
473             Proto += ", ";
474 
475           Proto += FT->getExceptionType(I).getAsString(SubPolicy);
476         }
477       Proto += ")";
478     } else if (FT && isNoexceptExceptionSpec(FT->getExceptionSpecType())) {
479       Proto += " noexcept";
480       if (FT->getExceptionSpecType() == EST_ComputedNoexcept) {
481         Proto += "(";
482         llvm::raw_string_ostream EOut(Proto);
483         FT->getNoexceptExpr()->printPretty(EOut, 0, SubPolicy,
484                                            Indentation);
485         EOut.flush();
486         Proto += EOut.str();
487         Proto += ")";
488       }
489     }
490 
491     if (CDecl) {
492       bool HasInitializerList = false;
493       for (CXXConstructorDecl::init_const_iterator B = CDecl->init_begin(),
494            E = CDecl->init_end();
495            B != E; ++B) {
496         CXXCtorInitializer *BMInitializer = (*B);
497         if (BMInitializer->isInClassMemberInitializer())
498           continue;
499 
500         if (!HasInitializerList) {
501           Proto += " : ";
502           Out << Proto;
503           Proto.clear();
504           HasInitializerList = true;
505         } else
506           Out << ", ";
507 
508         if (BMInitializer->isAnyMemberInitializer()) {
509           FieldDecl *FD = BMInitializer->getAnyMember();
510           Out << *FD;
511         } else {
512           Out << QualType(BMInitializer->getBaseClass(), 0).getAsString(Policy);
513         }
514 
515         Out << "(";
516         if (!BMInitializer->getInit()) {
517           // Nothing to print
518         } else {
519           Expr *Init = BMInitializer->getInit();
520           if (ExprWithCleanups *Tmp = dyn_cast<ExprWithCleanups>(Init))
521             Init = Tmp->getSubExpr();
522 
523           Init = Init->IgnoreParens();
524 
525           Expr *SimpleInit = 0;
526           Expr **Args = 0;
527           unsigned NumArgs = 0;
528           if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
529             Args = ParenList->getExprs();
530             NumArgs = ParenList->getNumExprs();
531           } else if (CXXConstructExpr *Construct
532                                         = dyn_cast<CXXConstructExpr>(Init)) {
533             Args = Construct->getArgs();
534             NumArgs = Construct->getNumArgs();
535           } else
536             SimpleInit = Init;
537 
538           if (SimpleInit)
539             SimpleInit->printPretty(Out, 0, Policy, Indentation);
540           else {
541             for (unsigned I = 0; I != NumArgs; ++I) {
542               if (isa<CXXDefaultArgExpr>(Args[I]))
543                 break;
544 
545               if (I)
546                 Out << ", ";
547               Args[I]->printPretty(Out, 0, Policy, Indentation);
548             }
549           }
550         }
551         Out << ")";
552         if (BMInitializer->isPackExpansion())
553           Out << "...";
554       }
555     } else if (!ConversionDecl && !isa<CXXDestructorDecl>(D)) {
556       if (FT && FT->hasTrailingReturn()) {
557         Out << "auto " << Proto << " -> ";
558         Proto.clear();
559       }
560       AFT->getReturnType().print(Out, Policy, Proto);
561       Proto.clear();
562     }
563     Out << Proto;
564   } else {
565     Ty.print(Out, Policy, Proto);
566   }
567 
568   prettyPrintAttributes(D);
569 
570   if (D->isPure())
571     Out << " = 0";
572   else if (D->isDeletedAsWritten())
573     Out << " = delete";
574   else if (D->isExplicitlyDefaulted())
575     Out << " = default";
576   else if (D->doesThisDeclarationHaveABody() && !Policy.TerseOutput) {
577     if (!D->hasPrototype() && D->getNumParams()) {
578       // This is a K&R function definition, so we need to print the
579       // parameters.
580       Out << '\n';
581       DeclPrinter ParamPrinter(Out, SubPolicy, Indentation);
582       Indentation += Policy.Indentation;
583       for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
584         Indent();
585         ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
586         Out << ";\n";
587       }
588       Indentation -= Policy.Indentation;
589     } else
590       Out << ' ';
591 
592     D->getBody()->printPretty(Out, 0, SubPolicy, Indentation);
593     Out << '\n';
594   }
595 }
596 
597 void DeclPrinter::VisitFriendDecl(FriendDecl *D) {
598   if (TypeSourceInfo *TSI = D->getFriendType()) {
599     unsigned NumTPLists = D->getFriendTypeNumTemplateParameterLists();
600     for (unsigned i = 0; i < NumTPLists; ++i)
601       PrintTemplateParameters(D->getFriendTypeTemplateParameterList(i));
602     Out << "friend ";
603     Out << " " << TSI->getType().getAsString(Policy);
604   }
605   else if (FunctionDecl *FD =
606       dyn_cast<FunctionDecl>(D->getFriendDecl())) {
607     Out << "friend ";
608     VisitFunctionDecl(FD);
609   }
610   else if (FunctionTemplateDecl *FTD =
611            dyn_cast<FunctionTemplateDecl>(D->getFriendDecl())) {
612     Out << "friend ";
613     VisitFunctionTemplateDecl(FTD);
614   }
615   else if (ClassTemplateDecl *CTD =
616            dyn_cast<ClassTemplateDecl>(D->getFriendDecl())) {
617     Out << "friend ";
618     VisitRedeclarableTemplateDecl(CTD);
619   }
620 }
621 
622 void DeclPrinter::VisitFieldDecl(FieldDecl *D) {
623   if (!Policy.SuppressSpecifiers && D->isMutable())
624     Out << "mutable ";
625   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
626     Out << "__module_private__ ";
627 
628   Out << D->getASTContext().getUnqualifiedObjCPointerType(D->getType()).
629             stream(Policy, D->getName());
630 
631   if (D->isBitField()) {
632     Out << " : ";
633     D->getBitWidth()->printPretty(Out, 0, Policy, Indentation);
634   }
635 
636   Expr *Init = D->getInClassInitializer();
637   if (!Policy.SuppressInitializers && Init) {
638     if (D->getInClassInitStyle() == ICIS_ListInit)
639       Out << " ";
640     else
641       Out << " = ";
642     Init->printPretty(Out, 0, Policy, Indentation);
643   }
644   prettyPrintAttributes(D);
645 }
646 
647 void DeclPrinter::VisitLabelDecl(LabelDecl *D) {
648   Out << *D << ":";
649 }
650 
651 
652 void DeclPrinter::VisitVarDecl(VarDecl *D) {
653   if (!Policy.SuppressSpecifiers) {
654     StorageClass SC = D->getStorageClass();
655     if (SC != SC_None)
656       Out << VarDecl::getStorageClassSpecifierString(SC) << " ";
657 
658     switch (D->getTSCSpec()) {
659     case TSCS_unspecified:
660       break;
661     case TSCS___thread:
662       Out << "__thread ";
663       break;
664     case TSCS__Thread_local:
665       Out << "_Thread_local ";
666       break;
667     case TSCS_thread_local:
668       Out << "thread_local ";
669       break;
670     }
671 
672     if (D->isModulePrivate())
673       Out << "__module_private__ ";
674   }
675 
676   QualType T = D->getTypeSourceInfo()
677     ? D->getTypeSourceInfo()->getType()
678     : D->getASTContext().getUnqualifiedObjCPointerType(D->getType());
679   T.print(Out, Policy, D->getName());
680   Expr *Init = D->getInit();
681   if (!Policy.SuppressInitializers && Init) {
682     bool ImplicitInit = false;
683     if (CXXConstructExpr *Construct =
684             dyn_cast<CXXConstructExpr>(Init->IgnoreImplicit())) {
685       if (D->getInitStyle() == VarDecl::CallInit &&
686           !Construct->isListInitialization()) {
687         ImplicitInit = Construct->getNumArgs() == 0 ||
688           Construct->getArg(0)->isDefaultArgument();
689       }
690     }
691     if (!ImplicitInit) {
692       if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
693         Out << "(";
694       else if (D->getInitStyle() == VarDecl::CInit) {
695         Out << " = ";
696       }
697       Init->printPretty(Out, 0, Policy, Indentation);
698       if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
699         Out << ")";
700     }
701   }
702   prettyPrintAttributes(D);
703 }
704 
705 void DeclPrinter::VisitParmVarDecl(ParmVarDecl *D) {
706   VisitVarDecl(D);
707 }
708 
709 void DeclPrinter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) {
710   Out << "__asm (";
711   D->getAsmString()->printPretty(Out, 0, Policy, Indentation);
712   Out << ")";
713 }
714 
715 void DeclPrinter::VisitImportDecl(ImportDecl *D) {
716   Out << "@import " << D->getImportedModule()->getFullModuleName()
717       << ";\n";
718 }
719 
720 void DeclPrinter::VisitStaticAssertDecl(StaticAssertDecl *D) {
721   Out << "static_assert(";
722   D->getAssertExpr()->printPretty(Out, 0, Policy, Indentation);
723   Out << ", ";
724   D->getMessage()->printPretty(Out, 0, Policy, Indentation);
725   Out << ")";
726 }
727 
728 //----------------------------------------------------------------------------
729 // C++ declarations
730 //----------------------------------------------------------------------------
731 void DeclPrinter::VisitNamespaceDecl(NamespaceDecl *D) {
732   if (D->isInline())
733     Out << "inline ";
734   Out << "namespace " << *D << " {\n";
735   VisitDeclContext(D);
736   Indent() << "}";
737 }
738 
739 void DeclPrinter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
740   Out << "using namespace ";
741   if (D->getQualifier())
742     D->getQualifier()->print(Out, Policy);
743   Out << *D->getNominatedNamespaceAsWritten();
744 }
745 
746 void DeclPrinter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
747   Out << "namespace " << *D << " = ";
748   if (D->getQualifier())
749     D->getQualifier()->print(Out, Policy);
750   Out << *D->getAliasedNamespace();
751 }
752 
753 void DeclPrinter::VisitEmptyDecl(EmptyDecl *D) {
754   prettyPrintAttributes(D);
755 }
756 
757 void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) {
758   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
759     Out << "__module_private__ ";
760   Out << D->getKindName();
761   if (D->getIdentifier())
762     Out << ' ' << *D;
763 
764   if (D->isCompleteDefinition()) {
765     // Print the base classes
766     if (D->getNumBases()) {
767       Out << " : ";
768       for (CXXRecordDecl::base_class_iterator Base = D->bases_begin(),
769              BaseEnd = D->bases_end(); Base != BaseEnd; ++Base) {
770         if (Base != D->bases_begin())
771           Out << ", ";
772 
773         if (Base->isVirtual())
774           Out << "virtual ";
775 
776         AccessSpecifier AS = Base->getAccessSpecifierAsWritten();
777         if (AS != AS_none)
778           Print(AS);
779         Out << " " << Base->getType().getAsString(Policy);
780 
781         if (Base->isPackExpansion())
782           Out << "...";
783       }
784     }
785 
786     // Print the class definition
787     // FIXME: Doesn't print access specifiers, e.g., "public:"
788     Out << " {\n";
789     VisitDeclContext(D);
790     Indent() << "}";
791   }
792 }
793 
794 void DeclPrinter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
795   const char *l;
796   if (D->getLanguage() == LinkageSpecDecl::lang_c)
797     l = "C";
798   else {
799     assert(D->getLanguage() == LinkageSpecDecl::lang_cxx &&
800            "unknown language in linkage specification");
801     l = "C++";
802   }
803 
804   Out << "extern \"" << l << "\" ";
805   if (D->hasBraces()) {
806     Out << "{\n";
807     VisitDeclContext(D);
808     Indent() << "}";
809   } else
810     Visit(*D->decls_begin());
811 }
812 
813 void DeclPrinter::PrintTemplateParameters(const TemplateParameterList *Params,
814                                           const TemplateArgumentList *Args) {
815   assert(Params);
816   assert(!Args || Params->size() == Args->size());
817 
818   Out << "template <";
819 
820   for (unsigned i = 0, e = Params->size(); i != e; ++i) {
821     if (i != 0)
822       Out << ", ";
823 
824     const Decl *Param = Params->getParam(i);
825     if (const TemplateTypeParmDecl *TTP =
826           dyn_cast<TemplateTypeParmDecl>(Param)) {
827 
828       if (TTP->wasDeclaredWithTypename())
829         Out << "typename ";
830       else
831         Out << "class ";
832 
833       if (TTP->isParameterPack())
834         Out << "... ";
835 
836       Out << *TTP;
837 
838       if (Args) {
839         Out << " = ";
840         Args->get(i).print(Policy, Out);
841       } else if (TTP->hasDefaultArgument()) {
842         Out << " = ";
843         Out << TTP->getDefaultArgument().getAsString(Policy);
844       };
845     } else if (const NonTypeTemplateParmDecl *NTTP =
846                  dyn_cast<NonTypeTemplateParmDecl>(Param)) {
847       Out << NTTP->getType().getAsString(Policy);
848 
849       if (NTTP->isParameterPack() && !isa<PackExpansionType>(NTTP->getType()))
850         Out << "...";
851 
852       if (IdentifierInfo *Name = NTTP->getIdentifier()) {
853         Out << ' ';
854         Out << Name->getName();
855       }
856 
857       if (Args) {
858         Out << " = ";
859         Args->get(i).print(Policy, Out);
860       } else if (NTTP->hasDefaultArgument()) {
861         Out << " = ";
862         NTTP->getDefaultArgument()->printPretty(Out, 0, Policy, Indentation);
863       }
864     } else if (const TemplateTemplateParmDecl *TTPD =
865                  dyn_cast<TemplateTemplateParmDecl>(Param)) {
866       VisitTemplateDecl(TTPD);
867       // FIXME: print the default argument, if present.
868     }
869   }
870 
871   Out << "> ";
872 }
873 
874 void DeclPrinter::VisitTemplateDecl(const TemplateDecl *D) {
875   PrintTemplateParameters(D->getTemplateParameters());
876 
877   if (const TemplateTemplateParmDecl *TTP =
878         dyn_cast<TemplateTemplateParmDecl>(D)) {
879     Out << "class ";
880     if (TTP->isParameterPack())
881       Out << "...";
882     Out << D->getName();
883   } else {
884     Visit(D->getTemplatedDecl());
885   }
886 }
887 
888 void DeclPrinter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
889   if (PrintInstantiation) {
890     TemplateParameterList *Params = D->getTemplateParameters();
891     for (FunctionTemplateDecl::spec_iterator I = D->spec_begin(), E = D->spec_end();
892          I != E; ++I) {
893       PrintTemplateParameters(Params, (*I)->getTemplateSpecializationArgs());
894       Visit(*I);
895     }
896   }
897 
898   return VisitRedeclarableTemplateDecl(D);
899 }
900 
901 void DeclPrinter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
902   if (PrintInstantiation) {
903     TemplateParameterList *Params = D->getTemplateParameters();
904     for (ClassTemplateDecl::spec_iterator I = D->spec_begin(), E = D->spec_end();
905          I != E; ++I) {
906       PrintTemplateParameters(Params, &(*I)->getTemplateArgs());
907       Visit(*I);
908       Out << '\n';
909     }
910   }
911 
912   return VisitRedeclarableTemplateDecl(D);
913 }
914 
915 //----------------------------------------------------------------------------
916 // Objective-C declarations
917 //----------------------------------------------------------------------------
918 
919 void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) {
920   if (OMD->isInstanceMethod())
921     Out << "- ";
922   else
923     Out << "+ ";
924   if (!OMD->getReturnType().isNull())
925     Out << '(' << OMD->getASTContext()
926                       .getUnqualifiedObjCPointerType(OMD->getReturnType())
927                       .getAsString(Policy) << ")";
928 
929   std::string name = OMD->getSelector().getAsString();
930   std::string::size_type pos, lastPos = 0;
931   for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
932        E = OMD->param_end(); PI != E; ++PI) {
933     // FIXME: selector is missing here!
934     pos = name.find_first_of(':', lastPos);
935     Out << " " << name.substr(lastPos, pos - lastPos);
936     Out << ":(" << (*PI)->getASTContext().getUnqualifiedObjCPointerType((*PI)->getType()).
937                       getAsString(Policy) << ')' << **PI;
938     lastPos = pos + 1;
939   }
940 
941   if (OMD->param_begin() == OMD->param_end())
942     Out << " " << name;
943 
944   if (OMD->isVariadic())
945       Out << ", ...";
946 
947   if (OMD->getBody() && !Policy.TerseOutput) {
948     Out << ' ';
949     OMD->getBody()->printPretty(Out, 0, Policy);
950     Out << '\n';
951   }
952   else if (Policy.PolishForDeclaration)
953     Out << ';';
954 }
955 
956 void DeclPrinter::VisitObjCImplementationDecl(ObjCImplementationDecl *OID) {
957   std::string I = OID->getNameAsString();
958   ObjCInterfaceDecl *SID = OID->getSuperClass();
959 
960   if (SID)
961     Out << "@implementation " << I << " : " << *SID;
962   else
963     Out << "@implementation " << I;
964 
965   if (OID->ivar_size() > 0) {
966     Out << "{\n";
967     Indentation += Policy.Indentation;
968     for (ObjCImplementationDecl::ivar_iterator I = OID->ivar_begin(),
969          E = OID->ivar_end(); I != E; ++I) {
970       Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).
971                     getAsString(Policy) << ' ' << **I << ";\n";
972     }
973     Indentation -= Policy.Indentation;
974     Out << "}\n";
975   }
976   VisitDeclContext(OID, false);
977   Out << "@end";
978 }
979 
980 void DeclPrinter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *OID) {
981   std::string I = OID->getNameAsString();
982   ObjCInterfaceDecl *SID = OID->getSuperClass();
983 
984   if (!OID->isThisDeclarationADefinition()) {
985     Out << "@class " << I << ";";
986     return;
987   }
988   bool eolnOut = false;
989   if (SID)
990     Out << "@interface " << I << " : " << *SID;
991   else
992     Out << "@interface " << I;
993 
994   // Protocols?
995   const ObjCList<ObjCProtocolDecl> &Protocols = OID->getReferencedProtocols();
996   if (!Protocols.empty()) {
997     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
998          E = Protocols.end(); I != E; ++I)
999       Out << (I == Protocols.begin() ? '<' : ',') << **I;
1000     Out << "> ";
1001   }
1002 
1003   if (OID->ivar_size() > 0) {
1004     Out << "{\n";
1005     eolnOut = true;
1006     Indentation += Policy.Indentation;
1007     for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
1008          E = OID->ivar_end(); I != E; ++I) {
1009       Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).
1010                     getAsString(Policy) << ' ' << **I << ";\n";
1011     }
1012     Indentation -= Policy.Indentation;
1013     Out << "}\n";
1014   }
1015   else if (SID) {
1016     Out << "\n";
1017     eolnOut = true;
1018   }
1019 
1020   VisitDeclContext(OID, false);
1021   if (!eolnOut)
1022     Out << ' ';
1023   Out << "@end";
1024   // FIXME: implement the rest...
1025 }
1026 
1027 void DeclPrinter::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1028   if (!PID->isThisDeclarationADefinition()) {
1029     Out << "@protocol " << *PID << ";\n";
1030     return;
1031   }
1032   // Protocols?
1033   const ObjCList<ObjCProtocolDecl> &Protocols = PID->getReferencedProtocols();
1034   if (!Protocols.empty()) {
1035     Out << "@protocol " << *PID;
1036     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1037          E = Protocols.end(); I != E; ++I)
1038       Out << (I == Protocols.begin() ? '<' : ',') << **I;
1039     Out << ">\n";
1040   } else
1041     Out << "@protocol " << *PID << '\n';
1042   VisitDeclContext(PID, false);
1043   Out << "@end";
1044 }
1045 
1046 void DeclPrinter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *PID) {
1047   Out << "@implementation " << *PID->getClassInterface() << '(' << *PID <<")\n";
1048 
1049   VisitDeclContext(PID, false);
1050   Out << "@end";
1051   // FIXME: implement the rest...
1052 }
1053 
1054 void DeclPrinter::VisitObjCCategoryDecl(ObjCCategoryDecl *PID) {
1055   Out << "@interface " << *PID->getClassInterface() << '(' << *PID << ")\n";
1056   if (PID->ivar_size() > 0) {
1057     Out << "{\n";
1058     Indentation += Policy.Indentation;
1059     for (ObjCCategoryDecl::ivar_iterator I = PID->ivar_begin(),
1060          E = PID->ivar_end(); I != E; ++I) {
1061       Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).
1062                     getAsString(Policy) << ' ' << **I << ";\n";
1063     }
1064     Indentation -= Policy.Indentation;
1065     Out << "}\n";
1066   }
1067 
1068   VisitDeclContext(PID, false);
1069   Out << "@end";
1070 
1071   // FIXME: implement the rest...
1072 }
1073 
1074 void DeclPrinter::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *AID) {
1075   Out << "@compatibility_alias " << *AID
1076       << ' ' << *AID->getClassInterface() << ";\n";
1077 }
1078 
1079 /// PrintObjCPropertyDecl - print a property declaration.
1080 ///
1081 void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) {
1082   if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Required)
1083     Out << "@required\n";
1084   else if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Optional)
1085     Out << "@optional\n";
1086 
1087   Out << "@property";
1088   if (PDecl->getPropertyAttributes() != ObjCPropertyDecl::OBJC_PR_noattr) {
1089     bool first = true;
1090     Out << " (";
1091     if (PDecl->getPropertyAttributes() &
1092         ObjCPropertyDecl::OBJC_PR_readonly) {
1093       Out << (first ? ' ' : ',') << "readonly";
1094       first = false;
1095     }
1096 
1097     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
1098       Out << (first ? ' ' : ',') << "getter = ";
1099       PDecl->getGetterName().print(Out);
1100       first = false;
1101     }
1102     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
1103       Out << (first ? ' ' : ',') << "setter = ";
1104       PDecl->getSetterName().print(Out);
1105       first = false;
1106     }
1107 
1108     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_assign) {
1109       Out << (first ? ' ' : ',') << "assign";
1110       first = false;
1111     }
1112 
1113     if (PDecl->getPropertyAttributes() &
1114         ObjCPropertyDecl::OBJC_PR_readwrite) {
1115       Out << (first ? ' ' : ',') << "readwrite";
1116       first = false;
1117     }
1118 
1119     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain) {
1120       Out << (first ? ' ' : ',') << "retain";
1121       first = false;
1122     }
1123 
1124     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_strong) {
1125       Out << (first ? ' ' : ',') << "strong";
1126       first = false;
1127     }
1128 
1129     if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy) {
1130       Out << (first ? ' ' : ',') << "copy";
1131       first = false;
1132     }
1133 
1134     if (PDecl->getPropertyAttributes() &
1135         ObjCPropertyDecl::OBJC_PR_nonatomic) {
1136       Out << (first ? ' ' : ',') << "nonatomic";
1137       first = false;
1138     }
1139     if (PDecl->getPropertyAttributes() &
1140         ObjCPropertyDecl::OBJC_PR_atomic) {
1141       Out << (first ? ' ' : ',') << "atomic";
1142       first = false;
1143     }
1144 
1145     (void) first; // Silence dead store warning due to idiomatic code.
1146     Out << " )";
1147   }
1148   Out << ' ' << PDecl->getASTContext().getUnqualifiedObjCPointerType(PDecl->getType()).
1149                   getAsString(Policy) << ' ' << *PDecl;
1150   if (Policy.PolishForDeclaration)
1151     Out << ';';
1152 }
1153 
1154 void DeclPrinter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PID) {
1155   if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize)
1156     Out << "@synthesize ";
1157   else
1158     Out << "@dynamic ";
1159   Out << *PID->getPropertyDecl();
1160   if (PID->getPropertyIvarDecl())
1161     Out << '=' << *PID->getPropertyIvarDecl();
1162 }
1163 
1164 void DeclPrinter::VisitUsingDecl(UsingDecl *D) {
1165   if (!D->isAccessDeclaration())
1166     Out << "using ";
1167   if (D->hasTypename())
1168     Out << "typename ";
1169   D->getQualifier()->print(Out, Policy);
1170   Out << *D;
1171 }
1172 
1173 void
1174 DeclPrinter::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
1175   Out << "using typename ";
1176   D->getQualifier()->print(Out, Policy);
1177   Out << D->getDeclName();
1178 }
1179 
1180 void DeclPrinter::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1181   if (!D->isAccessDeclaration())
1182     Out << "using ";
1183   D->getQualifier()->print(Out, Policy);
1184   Out << D->getName();
1185 }
1186 
1187 void DeclPrinter::VisitUsingShadowDecl(UsingShadowDecl *D) {
1188   // ignore
1189 }
1190 
1191 void DeclPrinter::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
1192   Out << "#pragma omp threadprivate";
1193   if (!D->varlist_empty()) {
1194     for (OMPThreadPrivateDecl::varlist_iterator I = D->varlist_begin(),
1195                                                 E = D->varlist_end();
1196                                                 I != E; ++I) {
1197       Out << (I == D->varlist_begin() ? '(' : ',');
1198       NamedDecl *ND = cast<NamedDecl>(cast<DeclRefExpr>(*I)->getDecl());
1199       ND->printQualifiedName(Out);
1200     }
1201     Out << ")";
1202   }
1203 }
1204 
1205