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