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