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