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 } else if (!D->getNumParams() && !Context.getLangOpts().CPlusPlus) { 684 // The function has a prototype, so it needs to retain the prototype 685 // in C. 686 POut << "void"; 687 } 688 } else if (D->doesThisDeclarationHaveABody() && !D->hasPrototype()) { 689 for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) { 690 if (i) 691 Proto += ", "; 692 Proto += D->getParamDecl(i)->getNameAsString(); 693 } 694 } 695 696 Proto += ")"; 697 698 if (FT) { 699 if (FT->isConst()) 700 Proto += " const"; 701 if (FT->isVolatile()) 702 Proto += " volatile"; 703 if (FT->isRestrict()) 704 Proto += " restrict"; 705 706 switch (FT->getRefQualifier()) { 707 case RQ_None: 708 break; 709 case RQ_LValue: 710 Proto += " &"; 711 break; 712 case RQ_RValue: 713 Proto += " &&"; 714 break; 715 } 716 } 717 718 if (FT && FT->hasDynamicExceptionSpec()) { 719 Proto += " throw("; 720 if (FT->getExceptionSpecType() == EST_MSAny) 721 Proto += "..."; 722 else 723 for (unsigned I = 0, N = FT->getNumExceptions(); I != N; ++I) { 724 if (I) 725 Proto += ", "; 726 727 Proto += FT->getExceptionType(I).getAsString(SubPolicy); 728 } 729 Proto += ")"; 730 } else if (FT && isNoexceptExceptionSpec(FT->getExceptionSpecType())) { 731 Proto += " noexcept"; 732 if (isComputedNoexcept(FT->getExceptionSpecType())) { 733 Proto += "("; 734 llvm::raw_string_ostream EOut(Proto); 735 FT->getNoexceptExpr()->printPretty(EOut, nullptr, SubPolicy, 736 Indentation, "\n", &Context); 737 EOut.flush(); 738 Proto += ")"; 739 } 740 } 741 742 if (CDecl) { 743 if (!Policy.TerseOutput) 744 PrintConstructorInitializers(CDecl, Proto); 745 } else if (!ConversionDecl && !isa<CXXDestructorDecl>(D)) { 746 if (FT && FT->hasTrailingReturn()) { 747 if (!GuideDecl) 748 Out << "auto "; 749 Out << Proto << " -> "; 750 Proto.clear(); 751 } 752 AFT->getReturnType().print(Out, Policy, Proto); 753 Proto.clear(); 754 } 755 Out << Proto; 756 757 if (Expr *TrailingRequiresClause = D->getTrailingRequiresClause()) { 758 Out << " requires "; 759 TrailingRequiresClause->printPretty(Out, nullptr, SubPolicy, Indentation, 760 "\n", &Context); 761 } 762 } else { 763 Ty.print(Out, Policy, Proto); 764 } 765 766 prettyPrintAttributes(D); 767 768 if (D->isPure()) 769 Out << " = 0"; 770 else if (D->isDeletedAsWritten()) 771 Out << " = delete"; 772 else if (D->isExplicitlyDefaulted()) 773 Out << " = default"; 774 else if (D->doesThisDeclarationHaveABody()) { 775 if (!Policy.TerseOutput) { 776 if (!D->hasPrototype() && D->getNumParams()) { 777 // This is a K&R function definition, so we need to print the 778 // parameters. 779 Out << '\n'; 780 DeclPrinter ParamPrinter(Out, SubPolicy, Context, Indentation); 781 Indentation += Policy.Indentation; 782 for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) { 783 Indent(); 784 ParamPrinter.VisitParmVarDecl(D->getParamDecl(i)); 785 Out << ";\n"; 786 } 787 Indentation -= Policy.Indentation; 788 } 789 790 if (D->getBody()) 791 D->getBody()->printPrettyControlled(Out, nullptr, SubPolicy, Indentation, "\n", 792 &Context); 793 } else { 794 if (!Policy.TerseOutput && isa<CXXConstructorDecl>(*D)) 795 Out << " {}"; 796 } 797 } 798 } 799 800 void DeclPrinter::VisitFriendDecl(FriendDecl *D) { 801 if (TypeSourceInfo *TSI = D->getFriendType()) { 802 unsigned NumTPLists = D->getFriendTypeNumTemplateParameterLists(); 803 for (unsigned i = 0; i < NumTPLists; ++i) 804 printTemplateParameters(D->getFriendTypeTemplateParameterList(i)); 805 Out << "friend "; 806 Out << " " << TSI->getType().getAsString(Policy); 807 } 808 else if (FunctionDecl *FD = 809 dyn_cast<FunctionDecl>(D->getFriendDecl())) { 810 Out << "friend "; 811 VisitFunctionDecl(FD); 812 } 813 else if (FunctionTemplateDecl *FTD = 814 dyn_cast<FunctionTemplateDecl>(D->getFriendDecl())) { 815 Out << "friend "; 816 VisitFunctionTemplateDecl(FTD); 817 } 818 else if (ClassTemplateDecl *CTD = 819 dyn_cast<ClassTemplateDecl>(D->getFriendDecl())) { 820 Out << "friend "; 821 VisitRedeclarableTemplateDecl(CTD); 822 } 823 } 824 825 void DeclPrinter::VisitFieldDecl(FieldDecl *D) { 826 // FIXME: add printing of pragma attributes if required. 827 if (!Policy.SuppressSpecifiers && D->isMutable()) 828 Out << "mutable "; 829 if (!Policy.SuppressSpecifiers && D->isModulePrivate()) 830 Out << "__module_private__ "; 831 832 Out << D->getASTContext().getUnqualifiedObjCPointerType(D->getType()). 833 stream(Policy, D->getName(), Indentation); 834 835 if (D->isBitField()) { 836 Out << " : "; 837 D->getBitWidth()->printPretty(Out, nullptr, Policy, Indentation, "\n", 838 &Context); 839 } 840 841 Expr *Init = D->getInClassInitializer(); 842 if (!Policy.SuppressInitializers && Init) { 843 if (D->getInClassInitStyle() == ICIS_ListInit) 844 Out << " "; 845 else 846 Out << " = "; 847 Init->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context); 848 } 849 prettyPrintAttributes(D); 850 } 851 852 void DeclPrinter::VisitLabelDecl(LabelDecl *D) { 853 Out << *D << ":"; 854 } 855 856 void DeclPrinter::VisitVarDecl(VarDecl *D) { 857 prettyPrintPragmas(D); 858 859 QualType T = D->getTypeSourceInfo() 860 ? D->getTypeSourceInfo()->getType() 861 : D->getASTContext().getUnqualifiedObjCPointerType(D->getType()); 862 863 if (!Policy.SuppressSpecifiers) { 864 StorageClass SC = D->getStorageClass(); 865 if (SC != SC_None) 866 Out << VarDecl::getStorageClassSpecifierString(SC) << " "; 867 868 switch (D->getTSCSpec()) { 869 case TSCS_unspecified: 870 break; 871 case TSCS___thread: 872 Out << "__thread "; 873 break; 874 case TSCS__Thread_local: 875 Out << "_Thread_local "; 876 break; 877 case TSCS_thread_local: 878 Out << "thread_local "; 879 break; 880 } 881 882 if (D->isModulePrivate()) 883 Out << "__module_private__ "; 884 885 if (D->isConstexpr()) { 886 Out << "constexpr "; 887 T.removeLocalConst(); 888 } 889 } 890 891 printDeclType(T, (isa<ParmVarDecl>(D) && Policy.CleanUglifiedParameters && 892 D->getIdentifier()) 893 ? D->getIdentifier()->deuglifiedName() 894 : D->getName()); 895 Expr *Init = D->getInit(); 896 if (!Policy.SuppressInitializers && Init) { 897 bool ImplicitInit = false; 898 if (D->isCXXForRangeDecl()) { 899 // FIXME: We should print the range expression instead. 900 ImplicitInit = true; 901 } else if (CXXConstructExpr *Construct = 902 dyn_cast<CXXConstructExpr>(Init->IgnoreImplicit())) { 903 if (D->getInitStyle() == VarDecl::CallInit && 904 !Construct->isListInitialization()) { 905 ImplicitInit = Construct->getNumArgs() == 0 || 906 Construct->getArg(0)->isDefaultArgument(); 907 } 908 } 909 if (!ImplicitInit) { 910 if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init)) 911 Out << "("; 912 else if (D->getInitStyle() == VarDecl::CInit) { 913 Out << " = "; 914 } 915 PrintingPolicy SubPolicy(Policy); 916 SubPolicy.SuppressSpecifiers = false; 917 SubPolicy.IncludeTagDefinition = false; 918 Init->printPretty(Out, nullptr, SubPolicy, Indentation, "\n", &Context); 919 if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init)) 920 Out << ")"; 921 } 922 } 923 prettyPrintAttributes(D); 924 } 925 926 void DeclPrinter::VisitParmVarDecl(ParmVarDecl *D) { 927 VisitVarDecl(D); 928 } 929 930 void DeclPrinter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) { 931 Out << "__asm ("; 932 D->getAsmString()->printPretty(Out, nullptr, Policy, Indentation, "\n", 933 &Context); 934 Out << ")"; 935 } 936 937 void DeclPrinter::VisitImportDecl(ImportDecl *D) { 938 Out << "@import " << D->getImportedModule()->getFullModuleName() 939 << ";\n"; 940 } 941 942 void DeclPrinter::VisitStaticAssertDecl(StaticAssertDecl *D) { 943 Out << "static_assert("; 944 D->getAssertExpr()->printPretty(Out, nullptr, Policy, Indentation, "\n", 945 &Context); 946 if (StringLiteral *SL = D->getMessage()) { 947 Out << ", "; 948 SL->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context); 949 } 950 Out << ")"; 951 } 952 953 //---------------------------------------------------------------------------- 954 // C++ declarations 955 //---------------------------------------------------------------------------- 956 void DeclPrinter::VisitNamespaceDecl(NamespaceDecl *D) { 957 if (D->isInline()) 958 Out << "inline "; 959 960 Out << "namespace "; 961 if (D->getDeclName()) 962 Out << D->getDeclName() << ' '; 963 Out << "{\n"; 964 965 VisitDeclContext(D); 966 Indent() << "}"; 967 } 968 969 void DeclPrinter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 970 Out << "using namespace "; 971 if (D->getQualifier()) 972 D->getQualifier()->print(Out, Policy); 973 Out << *D->getNominatedNamespaceAsWritten(); 974 } 975 976 void DeclPrinter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 977 Out << "namespace " << *D << " = "; 978 if (D->getQualifier()) 979 D->getQualifier()->print(Out, Policy); 980 Out << *D->getAliasedNamespace(); 981 } 982 983 void DeclPrinter::VisitEmptyDecl(EmptyDecl *D) { 984 prettyPrintAttributes(D); 985 } 986 987 void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) { 988 // FIXME: add printing of pragma attributes if required. 989 if (!Policy.SuppressSpecifiers && D->isModulePrivate()) 990 Out << "__module_private__ "; 991 Out << D->getKindName(); 992 993 prettyPrintAttributes(D); 994 995 if (D->getIdentifier()) { 996 Out << ' ' << *D; 997 998 if (auto S = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 999 ArrayRef<TemplateArgument> Args = S->getTemplateArgs().asArray(); 1000 if (!Policy.PrintCanonicalTypes) 1001 if (const auto* TSI = S->getTypeAsWritten()) 1002 if (const auto *TST = 1003 dyn_cast<TemplateSpecializationType>(TSI->getType())) 1004 Args = TST->template_arguments(); 1005 printTemplateArguments( 1006 Args, S->getSpecializedTemplate()->getTemplateParameters()); 1007 } 1008 } 1009 1010 if (D->isCompleteDefinition()) { 1011 // Print the base classes 1012 if (D->getNumBases()) { 1013 Out << " : "; 1014 for (CXXRecordDecl::base_class_iterator Base = D->bases_begin(), 1015 BaseEnd = D->bases_end(); Base != BaseEnd; ++Base) { 1016 if (Base != D->bases_begin()) 1017 Out << ", "; 1018 1019 if (Base->isVirtual()) 1020 Out << "virtual "; 1021 1022 AccessSpecifier AS = Base->getAccessSpecifierAsWritten(); 1023 if (AS != AS_none) { 1024 Print(AS); 1025 Out << " "; 1026 } 1027 Out << Base->getType().getAsString(Policy); 1028 1029 if (Base->isPackExpansion()) 1030 Out << "..."; 1031 } 1032 } 1033 1034 // Print the class definition 1035 // FIXME: Doesn't print access specifiers, e.g., "public:" 1036 if (Policy.TerseOutput) { 1037 Out << " {}"; 1038 } else { 1039 Out << " {\n"; 1040 VisitDeclContext(D); 1041 Indent() << "}"; 1042 } 1043 } 1044 } 1045 1046 void DeclPrinter::VisitLinkageSpecDecl(LinkageSpecDecl *D) { 1047 const char *l; 1048 if (D->getLanguage() == LinkageSpecDecl::lang_c) 1049 l = "C"; 1050 else { 1051 assert(D->getLanguage() == LinkageSpecDecl::lang_cxx && 1052 "unknown language in linkage specification"); 1053 l = "C++"; 1054 } 1055 1056 Out << "extern \"" << l << "\" "; 1057 if (D->hasBraces()) { 1058 Out << "{\n"; 1059 VisitDeclContext(D); 1060 Indent() << "}"; 1061 } else 1062 Visit(*D->decls_begin()); 1063 } 1064 1065 void DeclPrinter::printTemplateParameters(const TemplateParameterList *Params, 1066 bool OmitTemplateKW) { 1067 assert(Params); 1068 1069 if (!OmitTemplateKW) 1070 Out << "template "; 1071 Out << '<'; 1072 1073 bool NeedComma = false; 1074 for (const Decl *Param : *Params) { 1075 if (Param->isImplicit()) 1076 continue; 1077 1078 if (NeedComma) 1079 Out << ", "; 1080 else 1081 NeedComma = true; 1082 1083 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 1084 VisitTemplateTypeParmDecl(TTP); 1085 } else if (auto NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 1086 VisitNonTypeTemplateParmDecl(NTTP); 1087 } else if (auto TTPD = dyn_cast<TemplateTemplateParmDecl>(Param)) { 1088 VisitTemplateDecl(TTPD); 1089 // FIXME: print the default argument, if present. 1090 } 1091 } 1092 1093 Out << '>'; 1094 if (!OmitTemplateKW) 1095 Out << ' '; 1096 } 1097 1098 void DeclPrinter::printTemplateArguments(ArrayRef<TemplateArgument> Args, 1099 const TemplateParameterList *Params) { 1100 Out << "<"; 1101 for (size_t I = 0, E = Args.size(); I < E; ++I) { 1102 if (I) 1103 Out << ", "; 1104 if (!Params) 1105 Args[I].print(Policy, Out, /*IncludeType*/ true); 1106 else 1107 Args[I].print(Policy, Out, 1108 TemplateParameterList::shouldIncludeTypeForArgument( 1109 Policy, Params, I)); 1110 } 1111 Out << ">"; 1112 } 1113 1114 void DeclPrinter::printTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, 1115 const TemplateParameterList *Params) { 1116 Out << "<"; 1117 for (size_t I = 0, E = Args.size(); I < E; ++I) { 1118 if (I) 1119 Out << ", "; 1120 if (!Params) 1121 Args[I].getArgument().print(Policy, Out, /*IncludeType*/ true); 1122 else 1123 Args[I].getArgument().print( 1124 Policy, Out, 1125 TemplateParameterList::shouldIncludeTypeForArgument(Policy, Params, 1126 I)); 1127 } 1128 Out << ">"; 1129 } 1130 1131 void DeclPrinter::VisitTemplateDecl(const TemplateDecl *D) { 1132 printTemplateParameters(D->getTemplateParameters()); 1133 1134 if (const TemplateTemplateParmDecl *TTP = 1135 dyn_cast<TemplateTemplateParmDecl>(D)) { 1136 Out << "class"; 1137 1138 if (TTP->isParameterPack()) 1139 Out << " ..."; 1140 else if (TTP->getDeclName()) 1141 Out << ' '; 1142 1143 if (TTP->getDeclName()) { 1144 if (Policy.CleanUglifiedParameters && TTP->getIdentifier()) 1145 Out << TTP->getIdentifier()->deuglifiedName(); 1146 else 1147 Out << TTP->getDeclName(); 1148 } 1149 } else if (auto *TD = D->getTemplatedDecl()) 1150 Visit(TD); 1151 else if (const auto *Concept = dyn_cast<ConceptDecl>(D)) { 1152 Out << "concept " << Concept->getName() << " = " ; 1153 Concept->getConstraintExpr()->printPretty(Out, nullptr, Policy, Indentation, 1154 "\n", &Context); 1155 } 1156 } 1157 1158 void DeclPrinter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 1159 prettyPrintPragmas(D->getTemplatedDecl()); 1160 // Print any leading template parameter lists. 1161 if (const FunctionDecl *FD = D->getTemplatedDecl()) { 1162 for (unsigned I = 0, NumTemplateParams = FD->getNumTemplateParameterLists(); 1163 I < NumTemplateParams; ++I) 1164 printTemplateParameters(FD->getTemplateParameterList(I)); 1165 } 1166 VisitRedeclarableTemplateDecl(D); 1167 // Declare target attribute is special one, natural spelling for the pragma 1168 // assumes "ending" construct so print it here. 1169 if (D->getTemplatedDecl()->hasAttr<OMPDeclareTargetDeclAttr>()) 1170 Out << "#pragma omp end declare target\n"; 1171 1172 // Never print "instantiations" for deduction guides (they don't really 1173 // have them). 1174 if (PrintInstantiation && 1175 !isa<CXXDeductionGuideDecl>(D->getTemplatedDecl())) { 1176 FunctionDecl *PrevDecl = D->getTemplatedDecl(); 1177 const FunctionDecl *Def; 1178 if (PrevDecl->isDefined(Def) && Def != PrevDecl) 1179 return; 1180 for (auto *I : D->specializations()) 1181 if (I->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) { 1182 if (!PrevDecl->isThisDeclarationADefinition()) 1183 Out << ";\n"; 1184 Indent(); 1185 prettyPrintPragmas(I); 1186 Visit(I); 1187 } 1188 } 1189 } 1190 1191 void DeclPrinter::VisitClassTemplateDecl(ClassTemplateDecl *D) { 1192 VisitRedeclarableTemplateDecl(D); 1193 1194 if (PrintInstantiation) { 1195 for (auto *I : D->specializations()) 1196 if (I->getSpecializationKind() == TSK_ImplicitInstantiation) { 1197 if (D->isThisDeclarationADefinition()) 1198 Out << ";"; 1199 Out << "\n"; 1200 Indent(); 1201 Visit(I); 1202 } 1203 } 1204 } 1205 1206 void DeclPrinter::VisitClassTemplateSpecializationDecl( 1207 ClassTemplateSpecializationDecl *D) { 1208 Out << "template<> "; 1209 VisitCXXRecordDecl(D); 1210 } 1211 1212 void DeclPrinter::VisitClassTemplatePartialSpecializationDecl( 1213 ClassTemplatePartialSpecializationDecl *D) { 1214 printTemplateParameters(D->getTemplateParameters()); 1215 VisitCXXRecordDecl(D); 1216 } 1217 1218 //---------------------------------------------------------------------------- 1219 // Objective-C declarations 1220 //---------------------------------------------------------------------------- 1221 1222 void DeclPrinter::PrintObjCMethodType(ASTContext &Ctx, 1223 Decl::ObjCDeclQualifier Quals, 1224 QualType T) { 1225 Out << '('; 1226 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_In) 1227 Out << "in "; 1228 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Inout) 1229 Out << "inout "; 1230 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Out) 1231 Out << "out "; 1232 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Bycopy) 1233 Out << "bycopy "; 1234 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Byref) 1235 Out << "byref "; 1236 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Oneway) 1237 Out << "oneway "; 1238 if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_CSNullability) { 1239 if (auto nullability = AttributedType::stripOuterNullability(T)) 1240 Out << getNullabilitySpelling(*nullability, true) << ' '; 1241 } 1242 1243 Out << Ctx.getUnqualifiedObjCPointerType(T).getAsString(Policy); 1244 Out << ')'; 1245 } 1246 1247 void DeclPrinter::PrintObjCTypeParams(ObjCTypeParamList *Params) { 1248 Out << "<"; 1249 unsigned First = true; 1250 for (auto *Param : *Params) { 1251 if (First) { 1252 First = false; 1253 } else { 1254 Out << ", "; 1255 } 1256 1257 switch (Param->getVariance()) { 1258 case ObjCTypeParamVariance::Invariant: 1259 break; 1260 1261 case ObjCTypeParamVariance::Covariant: 1262 Out << "__covariant "; 1263 break; 1264 1265 case ObjCTypeParamVariance::Contravariant: 1266 Out << "__contravariant "; 1267 break; 1268 } 1269 1270 Out << Param->getDeclName(); 1271 1272 if (Param->hasExplicitBound()) { 1273 Out << " : " << Param->getUnderlyingType().getAsString(Policy); 1274 } 1275 } 1276 Out << ">"; 1277 } 1278 1279 void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) { 1280 if (OMD->isInstanceMethod()) 1281 Out << "- "; 1282 else 1283 Out << "+ "; 1284 if (!OMD->getReturnType().isNull()) { 1285 PrintObjCMethodType(OMD->getASTContext(), OMD->getObjCDeclQualifier(), 1286 OMD->getReturnType()); 1287 } 1288 1289 std::string name = OMD->getSelector().getAsString(); 1290 std::string::size_type pos, lastPos = 0; 1291 for (const auto *PI : OMD->parameters()) { 1292 // FIXME: selector is missing here! 1293 pos = name.find_first_of(':', lastPos); 1294 if (lastPos != 0) 1295 Out << " "; 1296 Out << name.substr(lastPos, pos - lastPos) << ':'; 1297 PrintObjCMethodType(OMD->getASTContext(), 1298 PI->getObjCDeclQualifier(), 1299 PI->getType()); 1300 Out << *PI; 1301 lastPos = pos + 1; 1302 } 1303 1304 if (OMD->param_begin() == OMD->param_end()) 1305 Out << name; 1306 1307 if (OMD->isVariadic()) 1308 Out << ", ..."; 1309 1310 prettyPrintAttributes(OMD); 1311 1312 if (OMD->getBody() && !Policy.TerseOutput) { 1313 Out << ' '; 1314 OMD->getBody()->printPretty(Out, nullptr, Policy, Indentation, "\n", 1315 &Context); 1316 } 1317 else if (Policy.PolishForDeclaration) 1318 Out << ';'; 1319 } 1320 1321 void DeclPrinter::VisitObjCImplementationDecl(ObjCImplementationDecl *OID) { 1322 std::string I = OID->getNameAsString(); 1323 ObjCInterfaceDecl *SID = OID->getSuperClass(); 1324 1325 bool eolnOut = false; 1326 if (SID) 1327 Out << "@implementation " << I << " : " << *SID; 1328 else 1329 Out << "@implementation " << I; 1330 1331 if (OID->ivar_size() > 0) { 1332 Out << "{\n"; 1333 eolnOut = true; 1334 Indentation += Policy.Indentation; 1335 for (const auto *I : OID->ivars()) { 1336 Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()). 1337 getAsString(Policy) << ' ' << *I << ";\n"; 1338 } 1339 Indentation -= Policy.Indentation; 1340 Out << "}\n"; 1341 } 1342 else if (SID || (OID->decls_begin() != OID->decls_end())) { 1343 Out << "\n"; 1344 eolnOut = true; 1345 } 1346 VisitDeclContext(OID, false); 1347 if (!eolnOut) 1348 Out << "\n"; 1349 Out << "@end"; 1350 } 1351 1352 void DeclPrinter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *OID) { 1353 std::string I = OID->getNameAsString(); 1354 ObjCInterfaceDecl *SID = OID->getSuperClass(); 1355 1356 if (!OID->isThisDeclarationADefinition()) { 1357 Out << "@class " << I; 1358 1359 if (auto TypeParams = OID->getTypeParamListAsWritten()) { 1360 PrintObjCTypeParams(TypeParams); 1361 } 1362 1363 Out << ";"; 1364 return; 1365 } 1366 bool eolnOut = false; 1367 Out << "@interface " << I; 1368 1369 if (auto TypeParams = OID->getTypeParamListAsWritten()) { 1370 PrintObjCTypeParams(TypeParams); 1371 } 1372 1373 if (SID) 1374 Out << " : " << QualType(OID->getSuperClassType(), 0).getAsString(Policy); 1375 1376 // Protocols? 1377 const ObjCList<ObjCProtocolDecl> &Protocols = OID->getReferencedProtocols(); 1378 if (!Protocols.empty()) { 1379 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 1380 E = Protocols.end(); I != E; ++I) 1381 Out << (I == Protocols.begin() ? '<' : ',') << **I; 1382 Out << "> "; 1383 } 1384 1385 if (OID->ivar_size() > 0) { 1386 Out << "{\n"; 1387 eolnOut = true; 1388 Indentation += Policy.Indentation; 1389 for (const auto *I : OID->ivars()) { 1390 Indent() << I->getASTContext() 1391 .getUnqualifiedObjCPointerType(I->getType()) 1392 .getAsString(Policy) << ' ' << *I << ";\n"; 1393 } 1394 Indentation -= Policy.Indentation; 1395 Out << "}\n"; 1396 } 1397 else if (SID || (OID->decls_begin() != OID->decls_end())) { 1398 Out << "\n"; 1399 eolnOut = true; 1400 } 1401 1402 VisitDeclContext(OID, false); 1403 if (!eolnOut) 1404 Out << "\n"; 1405 Out << "@end"; 1406 // FIXME: implement the rest... 1407 } 1408 1409 void DeclPrinter::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) { 1410 if (!PID->isThisDeclarationADefinition()) { 1411 Out << "@protocol " << *PID << ";\n"; 1412 return; 1413 } 1414 // Protocols? 1415 const ObjCList<ObjCProtocolDecl> &Protocols = PID->getReferencedProtocols(); 1416 if (!Protocols.empty()) { 1417 Out << "@protocol " << *PID; 1418 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 1419 E = Protocols.end(); I != E; ++I) 1420 Out << (I == Protocols.begin() ? '<' : ',') << **I; 1421 Out << ">\n"; 1422 } else 1423 Out << "@protocol " << *PID << '\n'; 1424 VisitDeclContext(PID, false); 1425 Out << "@end"; 1426 } 1427 1428 void DeclPrinter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *PID) { 1429 Out << "@implementation "; 1430 if (const auto *CID = PID->getClassInterface()) 1431 Out << *CID; 1432 else 1433 Out << "<<error-type>>"; 1434 Out << '(' << *PID << ")\n"; 1435 1436 VisitDeclContext(PID, false); 1437 Out << "@end"; 1438 // FIXME: implement the rest... 1439 } 1440 1441 void DeclPrinter::VisitObjCCategoryDecl(ObjCCategoryDecl *PID) { 1442 Out << "@interface "; 1443 if (const auto *CID = PID->getClassInterface()) 1444 Out << *CID; 1445 else 1446 Out << "<<error-type>>"; 1447 if (auto TypeParams = PID->getTypeParamList()) { 1448 PrintObjCTypeParams(TypeParams); 1449 } 1450 Out << "(" << *PID << ")\n"; 1451 if (PID->ivar_size() > 0) { 1452 Out << "{\n"; 1453 Indentation += Policy.Indentation; 1454 for (const auto *I : PID->ivars()) 1455 Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()). 1456 getAsString(Policy) << ' ' << *I << ";\n"; 1457 Indentation -= Policy.Indentation; 1458 Out << "}\n"; 1459 } 1460 1461 VisitDeclContext(PID, false); 1462 Out << "@end"; 1463 1464 // FIXME: implement the rest... 1465 } 1466 1467 void DeclPrinter::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *AID) { 1468 Out << "@compatibility_alias " << *AID 1469 << ' ' << *AID->getClassInterface() << ";\n"; 1470 } 1471 1472 /// PrintObjCPropertyDecl - print a property declaration. 1473 /// 1474 /// Print attributes in the following order: 1475 /// - class 1476 /// - nonatomic | atomic 1477 /// - assign | retain | strong | copy | weak | unsafe_unretained 1478 /// - readwrite | readonly 1479 /// - getter & setter 1480 /// - nullability 1481 void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) { 1482 if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Required) 1483 Out << "@required\n"; 1484 else if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Optional) 1485 Out << "@optional\n"; 1486 1487 QualType T = PDecl->getType(); 1488 1489 Out << "@property"; 1490 if (PDecl->getPropertyAttributes() != ObjCPropertyAttribute::kind_noattr) { 1491 bool first = true; 1492 Out << "("; 1493 if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_class) { 1494 Out << (first ? "" : ", ") << "class"; 1495 first = false; 1496 } 1497 1498 if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_direct) { 1499 Out << (first ? "" : ", ") << "direct"; 1500 first = false; 1501 } 1502 1503 if (PDecl->getPropertyAttributes() & 1504 ObjCPropertyAttribute::kind_nonatomic) { 1505 Out << (first ? "" : ", ") << "nonatomic"; 1506 first = false; 1507 } 1508 if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_atomic) { 1509 Out << (first ? "" : ", ") << "atomic"; 1510 first = false; 1511 } 1512 1513 if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_assign) { 1514 Out << (first ? "" : ", ") << "assign"; 1515 first = false; 1516 } 1517 if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain) { 1518 Out << (first ? "" : ", ") << "retain"; 1519 first = false; 1520 } 1521 1522 if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_strong) { 1523 Out << (first ? "" : ", ") << "strong"; 1524 first = false; 1525 } 1526 if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy) { 1527 Out << (first ? "" : ", ") << "copy"; 1528 first = false; 1529 } 1530 if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak) { 1531 Out << (first ? "" : ", ") << "weak"; 1532 first = false; 1533 } 1534 if (PDecl->getPropertyAttributes() & 1535 ObjCPropertyAttribute::kind_unsafe_unretained) { 1536 Out << (first ? "" : ", ") << "unsafe_unretained"; 1537 first = false; 1538 } 1539 1540 if (PDecl->getPropertyAttributes() & 1541 ObjCPropertyAttribute::kind_readwrite) { 1542 Out << (first ? "" : ", ") << "readwrite"; 1543 first = false; 1544 } 1545 if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_readonly) { 1546 Out << (first ? "" : ", ") << "readonly"; 1547 first = false; 1548 } 1549 1550 if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) { 1551 Out << (first ? "" : ", ") << "getter = "; 1552 PDecl->getGetterName().print(Out); 1553 first = false; 1554 } 1555 if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) { 1556 Out << (first ? "" : ", ") << "setter = "; 1557 PDecl->getSetterName().print(Out); 1558 first = false; 1559 } 1560 1561 if (PDecl->getPropertyAttributes() & 1562 ObjCPropertyAttribute::kind_nullability) { 1563 if (auto nullability = AttributedType::stripOuterNullability(T)) { 1564 if (*nullability == NullabilityKind::Unspecified && 1565 (PDecl->getPropertyAttributes() & 1566 ObjCPropertyAttribute::kind_null_resettable)) { 1567 Out << (first ? "" : ", ") << "null_resettable"; 1568 } else { 1569 Out << (first ? "" : ", ") 1570 << getNullabilitySpelling(*nullability, true); 1571 } 1572 first = false; 1573 } 1574 } 1575 1576 (void) first; // Silence dead store warning due to idiomatic code. 1577 Out << ")"; 1578 } 1579 std::string TypeStr = PDecl->getASTContext().getUnqualifiedObjCPointerType(T). 1580 getAsString(Policy); 1581 Out << ' ' << TypeStr; 1582 if (!StringRef(TypeStr).endswith("*")) 1583 Out << ' '; 1584 Out << *PDecl; 1585 if (Policy.PolishForDeclaration) 1586 Out << ';'; 1587 } 1588 1589 void DeclPrinter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PID) { 1590 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) 1591 Out << "@synthesize "; 1592 else 1593 Out << "@dynamic "; 1594 Out << *PID->getPropertyDecl(); 1595 if (PID->getPropertyIvarDecl()) 1596 Out << '=' << *PID->getPropertyIvarDecl(); 1597 } 1598 1599 void DeclPrinter::VisitUsingDecl(UsingDecl *D) { 1600 if (!D->isAccessDeclaration()) 1601 Out << "using "; 1602 if (D->hasTypename()) 1603 Out << "typename "; 1604 D->getQualifier()->print(Out, Policy); 1605 1606 // Use the correct record name when the using declaration is used for 1607 // inheriting constructors. 1608 for (const auto *Shadow : D->shadows()) { 1609 if (const auto *ConstructorShadow = 1610 dyn_cast<ConstructorUsingShadowDecl>(Shadow)) { 1611 assert(Shadow->getDeclContext() == ConstructorShadow->getDeclContext()); 1612 Out << *ConstructorShadow->getNominatedBaseClass(); 1613 return; 1614 } 1615 } 1616 Out << *D; 1617 } 1618 1619 void DeclPrinter::VisitUsingEnumDecl(UsingEnumDecl *D) { 1620 Out << "using enum " << D->getEnumDecl(); 1621 } 1622 1623 void 1624 DeclPrinter::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) { 1625 Out << "using typename "; 1626 D->getQualifier()->print(Out, Policy); 1627 Out << D->getDeclName(); 1628 } 1629 1630 void DeclPrinter::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 1631 if (!D->isAccessDeclaration()) 1632 Out << "using "; 1633 D->getQualifier()->print(Out, Policy); 1634 Out << D->getDeclName(); 1635 } 1636 1637 void DeclPrinter::VisitUsingShadowDecl(UsingShadowDecl *D) { 1638 // ignore 1639 } 1640 1641 void DeclPrinter::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) { 1642 Out << "#pragma omp threadprivate"; 1643 if (!D->varlist_empty()) { 1644 for (OMPThreadPrivateDecl::varlist_iterator I = D->varlist_begin(), 1645 E = D->varlist_end(); 1646 I != E; ++I) { 1647 Out << (I == D->varlist_begin() ? '(' : ','); 1648 NamedDecl *ND = cast<DeclRefExpr>(*I)->getDecl(); 1649 ND->printQualifiedName(Out); 1650 } 1651 Out << ")"; 1652 } 1653 } 1654 1655 void DeclPrinter::VisitOMPAllocateDecl(OMPAllocateDecl *D) { 1656 Out << "#pragma omp allocate"; 1657 if (!D->varlist_empty()) { 1658 for (OMPAllocateDecl::varlist_iterator I = D->varlist_begin(), 1659 E = D->varlist_end(); 1660 I != E; ++I) { 1661 Out << (I == D->varlist_begin() ? '(' : ','); 1662 NamedDecl *ND = cast<DeclRefExpr>(*I)->getDecl(); 1663 ND->printQualifiedName(Out); 1664 } 1665 Out << ")"; 1666 } 1667 if (!D->clauselist_empty()) { 1668 OMPClausePrinter Printer(Out, Policy); 1669 for (OMPClause *C : D->clauselists()) { 1670 Out << " "; 1671 Printer.Visit(C); 1672 } 1673 } 1674 } 1675 1676 void DeclPrinter::VisitOMPRequiresDecl(OMPRequiresDecl *D) { 1677 Out << "#pragma omp requires "; 1678 if (!D->clauselist_empty()) { 1679 OMPClausePrinter Printer(Out, Policy); 1680 for (auto I = D->clauselist_begin(), E = D->clauselist_end(); I != E; ++I) 1681 Printer.Visit(*I); 1682 } 1683 } 1684 1685 void DeclPrinter::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) { 1686 if (!D->isInvalidDecl()) { 1687 Out << "#pragma omp declare reduction ("; 1688 if (D->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) { 1689 const char *OpName = 1690 getOperatorSpelling(D->getDeclName().getCXXOverloadedOperator()); 1691 assert(OpName && "not an overloaded operator"); 1692 Out << OpName; 1693 } else { 1694 assert(D->getDeclName().isIdentifier()); 1695 D->printName(Out); 1696 } 1697 Out << " : "; 1698 D->getType().print(Out, Policy); 1699 Out << " : "; 1700 D->getCombiner()->printPretty(Out, nullptr, Policy, 0, "\n", &Context); 1701 Out << ")"; 1702 if (auto *Init = D->getInitializer()) { 1703 Out << " initializer("; 1704 switch (D->getInitializerKind()) { 1705 case OMPDeclareReductionDecl::DirectInit: 1706 Out << "omp_priv("; 1707 break; 1708 case OMPDeclareReductionDecl::CopyInit: 1709 Out << "omp_priv = "; 1710 break; 1711 case OMPDeclareReductionDecl::CallInit: 1712 break; 1713 } 1714 Init->printPretty(Out, nullptr, Policy, 0, "\n", &Context); 1715 if (D->getInitializerKind() == OMPDeclareReductionDecl::DirectInit) 1716 Out << ")"; 1717 Out << ")"; 1718 } 1719 } 1720 } 1721 1722 void DeclPrinter::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) { 1723 if (!D->isInvalidDecl()) { 1724 Out << "#pragma omp declare mapper ("; 1725 D->printName(Out); 1726 Out << " : "; 1727 D->getType().print(Out, Policy); 1728 Out << " "; 1729 Out << D->getVarName(); 1730 Out << ")"; 1731 if (!D->clauselist_empty()) { 1732 OMPClausePrinter Printer(Out, Policy); 1733 for (auto *C : D->clauselists()) { 1734 Out << " "; 1735 Printer.Visit(C); 1736 } 1737 } 1738 } 1739 } 1740 1741 void DeclPrinter::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) { 1742 D->getInit()->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context); 1743 } 1744 1745 void DeclPrinter::VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *TTP) { 1746 if (const TypeConstraint *TC = TTP->getTypeConstraint()) 1747 TC->print(Out, Policy); 1748 else if (TTP->wasDeclaredWithTypename()) 1749 Out << "typename"; 1750 else 1751 Out << "class"; 1752 1753 if (TTP->isParameterPack()) 1754 Out << " ..."; 1755 else if (TTP->getDeclName()) 1756 Out << ' '; 1757 1758 if (TTP->getDeclName()) { 1759 if (Policy.CleanUglifiedParameters && TTP->getIdentifier()) 1760 Out << TTP->getIdentifier()->deuglifiedName(); 1761 else 1762 Out << TTP->getDeclName(); 1763 } 1764 1765 if (TTP->hasDefaultArgument()) { 1766 Out << " = "; 1767 Out << TTP->getDefaultArgument().getAsString(Policy); 1768 } 1769 } 1770 1771 void DeclPrinter::VisitNonTypeTemplateParmDecl( 1772 const NonTypeTemplateParmDecl *NTTP) { 1773 StringRef Name; 1774 if (IdentifierInfo *II = NTTP->getIdentifier()) 1775 Name = 1776 Policy.CleanUglifiedParameters ? II->deuglifiedName() : II->getName(); 1777 printDeclType(NTTP->getType(), Name, NTTP->isParameterPack()); 1778 1779 if (NTTP->hasDefaultArgument()) { 1780 Out << " = "; 1781 NTTP->getDefaultArgument()->printPretty(Out, nullptr, Policy, Indentation, 1782 "\n", &Context); 1783 } 1784 } 1785