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