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