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 = 0); 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 = 0; 286 if (isa<OMPThreadPrivateDecl>(*D)) 287 Terminator = 0; 288 else if (isa<FunctionDecl>(*D) && 289 cast<FunctionDecl>(*D)->isThisDeclarationADefinition()) 290 Terminator = 0; 291 else if (isa<ObjCMethodDecl>(*D) && cast<ObjCMethodDecl>(*D)->getBody()) 292 Terminator = 0; 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 = 0; 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, 0, 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 = 0; 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, 0, SubPolicy, 484 Indentation); 485 EOut.flush(); 486 Proto += EOut.str(); 487 Proto += ")"; 488 } 489 } 490 491 if (CDecl) { 492 bool HasInitializerList = false; 493 for (CXXConstructorDecl::init_const_iterator B = CDecl->init_begin(), 494 E = CDecl->init_end(); 495 B != E; ++B) { 496 CXXCtorInitializer *BMInitializer = (*B); 497 if (BMInitializer->isInClassMemberInitializer()) 498 continue; 499 500 if (!HasInitializerList) { 501 Proto += " : "; 502 Out << Proto; 503 Proto.clear(); 504 HasInitializerList = true; 505 } else 506 Out << ", "; 507 508 if (BMInitializer->isAnyMemberInitializer()) { 509 FieldDecl *FD = BMInitializer->getAnyMember(); 510 Out << *FD; 511 } else { 512 Out << QualType(BMInitializer->getBaseClass(), 0).getAsString(Policy); 513 } 514 515 Out << "("; 516 if (!BMInitializer->getInit()) { 517 // Nothing to print 518 } else { 519 Expr *Init = BMInitializer->getInit(); 520 if (ExprWithCleanups *Tmp = dyn_cast<ExprWithCleanups>(Init)) 521 Init = Tmp->getSubExpr(); 522 523 Init = Init->IgnoreParens(); 524 525 Expr *SimpleInit = 0; 526 Expr **Args = 0; 527 unsigned NumArgs = 0; 528 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 529 Args = ParenList->getExprs(); 530 NumArgs = ParenList->getNumExprs(); 531 } else if (CXXConstructExpr *Construct 532 = dyn_cast<CXXConstructExpr>(Init)) { 533 Args = Construct->getArgs(); 534 NumArgs = Construct->getNumArgs(); 535 } else 536 SimpleInit = Init; 537 538 if (SimpleInit) 539 SimpleInit->printPretty(Out, 0, Policy, Indentation); 540 else { 541 for (unsigned I = 0; I != NumArgs; ++I) { 542 if (isa<CXXDefaultArgExpr>(Args[I])) 543 break; 544 545 if (I) 546 Out << ", "; 547 Args[I]->printPretty(Out, 0, Policy, Indentation); 548 } 549 } 550 } 551 Out << ")"; 552 if (BMInitializer->isPackExpansion()) 553 Out << "..."; 554 } 555 } else if (!ConversionDecl && !isa<CXXDestructorDecl>(D)) { 556 if (FT && FT->hasTrailingReturn()) { 557 Out << "auto " << Proto << " -> "; 558 Proto.clear(); 559 } 560 AFT->getReturnType().print(Out, Policy, Proto); 561 Proto.clear(); 562 } 563 Out << Proto; 564 } else { 565 Ty.print(Out, Policy, Proto); 566 } 567 568 prettyPrintAttributes(D); 569 570 if (D->isPure()) 571 Out << " = 0"; 572 else if (D->isDeletedAsWritten()) 573 Out << " = delete"; 574 else if (D->isExplicitlyDefaulted()) 575 Out << " = default"; 576 else if (D->doesThisDeclarationHaveABody() && !Policy.TerseOutput) { 577 if (!D->hasPrototype() && D->getNumParams()) { 578 // This is a K&R function definition, so we need to print the 579 // parameters. 580 Out << '\n'; 581 DeclPrinter ParamPrinter(Out, SubPolicy, Indentation); 582 Indentation += Policy.Indentation; 583 for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) { 584 Indent(); 585 ParamPrinter.VisitParmVarDecl(D->getParamDecl(i)); 586 Out << ";\n"; 587 } 588 Indentation -= Policy.Indentation; 589 } else 590 Out << ' '; 591 592 D->getBody()->printPretty(Out, 0, SubPolicy, Indentation); 593 Out << '\n'; 594 } 595 } 596 597 void DeclPrinter::VisitFriendDecl(FriendDecl *D) { 598 if (TypeSourceInfo *TSI = D->getFriendType()) { 599 unsigned NumTPLists = D->getFriendTypeNumTemplateParameterLists(); 600 for (unsigned i = 0; i < NumTPLists; ++i) 601 PrintTemplateParameters(D->getFriendTypeTemplateParameterList(i)); 602 Out << "friend "; 603 Out << " " << TSI->getType().getAsString(Policy); 604 } 605 else if (FunctionDecl *FD = 606 dyn_cast<FunctionDecl>(D->getFriendDecl())) { 607 Out << "friend "; 608 VisitFunctionDecl(FD); 609 } 610 else if (FunctionTemplateDecl *FTD = 611 dyn_cast<FunctionTemplateDecl>(D->getFriendDecl())) { 612 Out << "friend "; 613 VisitFunctionTemplateDecl(FTD); 614 } 615 else if (ClassTemplateDecl *CTD = 616 dyn_cast<ClassTemplateDecl>(D->getFriendDecl())) { 617 Out << "friend "; 618 VisitRedeclarableTemplateDecl(CTD); 619 } 620 } 621 622 void DeclPrinter::VisitFieldDecl(FieldDecl *D) { 623 if (!Policy.SuppressSpecifiers && D->isMutable()) 624 Out << "mutable "; 625 if (!Policy.SuppressSpecifiers && D->isModulePrivate()) 626 Out << "__module_private__ "; 627 628 Out << D->getASTContext().getUnqualifiedObjCPointerType(D->getType()). 629 stream(Policy, D->getName()); 630 631 if (D->isBitField()) { 632 Out << " : "; 633 D->getBitWidth()->printPretty(Out, 0, Policy, Indentation); 634 } 635 636 Expr *Init = D->getInClassInitializer(); 637 if (!Policy.SuppressInitializers && Init) { 638 if (D->getInClassInitStyle() == ICIS_ListInit) 639 Out << " "; 640 else 641 Out << " = "; 642 Init->printPretty(Out, 0, Policy, Indentation); 643 } 644 prettyPrintAttributes(D); 645 } 646 647 void DeclPrinter::VisitLabelDecl(LabelDecl *D) { 648 Out << *D << ":"; 649 } 650 651 652 void DeclPrinter::VisitVarDecl(VarDecl *D) { 653 if (!Policy.SuppressSpecifiers) { 654 StorageClass SC = D->getStorageClass(); 655 if (SC != SC_None) 656 Out << VarDecl::getStorageClassSpecifierString(SC) << " "; 657 658 switch (D->getTSCSpec()) { 659 case TSCS_unspecified: 660 break; 661 case TSCS___thread: 662 Out << "__thread "; 663 break; 664 case TSCS__Thread_local: 665 Out << "_Thread_local "; 666 break; 667 case TSCS_thread_local: 668 Out << "thread_local "; 669 break; 670 } 671 672 if (D->isModulePrivate()) 673 Out << "__module_private__ "; 674 } 675 676 QualType T = D->getTypeSourceInfo() 677 ? D->getTypeSourceInfo()->getType() 678 : D->getASTContext().getUnqualifiedObjCPointerType(D->getType()); 679 T.print(Out, Policy, D->getName()); 680 Expr *Init = D->getInit(); 681 if (!Policy.SuppressInitializers && Init) { 682 bool ImplicitInit = false; 683 if (CXXConstructExpr *Construct = 684 dyn_cast<CXXConstructExpr>(Init->IgnoreImplicit())) { 685 if (D->getInitStyle() == VarDecl::CallInit && 686 !Construct->isListInitialization()) { 687 ImplicitInit = Construct->getNumArgs() == 0 || 688 Construct->getArg(0)->isDefaultArgument(); 689 } 690 } 691 if (!ImplicitInit) { 692 if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init)) 693 Out << "("; 694 else if (D->getInitStyle() == VarDecl::CInit) { 695 Out << " = "; 696 } 697 Init->printPretty(Out, 0, Policy, Indentation); 698 if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init)) 699 Out << ")"; 700 } 701 } 702 prettyPrintAttributes(D); 703 } 704 705 void DeclPrinter::VisitParmVarDecl(ParmVarDecl *D) { 706 VisitVarDecl(D); 707 } 708 709 void DeclPrinter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) { 710 Out << "__asm ("; 711 D->getAsmString()->printPretty(Out, 0, Policy, Indentation); 712 Out << ")"; 713 } 714 715 void DeclPrinter::VisitImportDecl(ImportDecl *D) { 716 Out << "@import " << D->getImportedModule()->getFullModuleName() 717 << ";\n"; 718 } 719 720 void DeclPrinter::VisitStaticAssertDecl(StaticAssertDecl *D) { 721 Out << "static_assert("; 722 D->getAssertExpr()->printPretty(Out, 0, Policy, Indentation); 723 Out << ", "; 724 D->getMessage()->printPretty(Out, 0, Policy, Indentation); 725 Out << ")"; 726 } 727 728 //---------------------------------------------------------------------------- 729 // C++ declarations 730 //---------------------------------------------------------------------------- 731 void DeclPrinter::VisitNamespaceDecl(NamespaceDecl *D) { 732 if (D->isInline()) 733 Out << "inline "; 734 Out << "namespace " << *D << " {\n"; 735 VisitDeclContext(D); 736 Indent() << "}"; 737 } 738 739 void DeclPrinter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 740 Out << "using namespace "; 741 if (D->getQualifier()) 742 D->getQualifier()->print(Out, Policy); 743 Out << *D->getNominatedNamespaceAsWritten(); 744 } 745 746 void DeclPrinter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 747 Out << "namespace " << *D << " = "; 748 if (D->getQualifier()) 749 D->getQualifier()->print(Out, Policy); 750 Out << *D->getAliasedNamespace(); 751 } 752 753 void DeclPrinter::VisitEmptyDecl(EmptyDecl *D) { 754 prettyPrintAttributes(D); 755 } 756 757 void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) { 758 if (!Policy.SuppressSpecifiers && D->isModulePrivate()) 759 Out << "__module_private__ "; 760 Out << D->getKindName(); 761 if (D->getIdentifier()) 762 Out << ' ' << *D; 763 764 if (D->isCompleteDefinition()) { 765 // Print the base classes 766 if (D->getNumBases()) { 767 Out << " : "; 768 for (CXXRecordDecl::base_class_iterator Base = D->bases_begin(), 769 BaseEnd = D->bases_end(); Base != BaseEnd; ++Base) { 770 if (Base != D->bases_begin()) 771 Out << ", "; 772 773 if (Base->isVirtual()) 774 Out << "virtual "; 775 776 AccessSpecifier AS = Base->getAccessSpecifierAsWritten(); 777 if (AS != AS_none) 778 Print(AS); 779 Out << " " << Base->getType().getAsString(Policy); 780 781 if (Base->isPackExpansion()) 782 Out << "..."; 783 } 784 } 785 786 // Print the class definition 787 // FIXME: Doesn't print access specifiers, e.g., "public:" 788 Out << " {\n"; 789 VisitDeclContext(D); 790 Indent() << "}"; 791 } 792 } 793 794 void DeclPrinter::VisitLinkageSpecDecl(LinkageSpecDecl *D) { 795 const char *l; 796 if (D->getLanguage() == LinkageSpecDecl::lang_c) 797 l = "C"; 798 else { 799 assert(D->getLanguage() == LinkageSpecDecl::lang_cxx && 800 "unknown language in linkage specification"); 801 l = "C++"; 802 } 803 804 Out << "extern \"" << l << "\" "; 805 if (D->hasBraces()) { 806 Out << "{\n"; 807 VisitDeclContext(D); 808 Indent() << "}"; 809 } else 810 Visit(*D->decls_begin()); 811 } 812 813 void DeclPrinter::PrintTemplateParameters(const TemplateParameterList *Params, 814 const TemplateArgumentList *Args) { 815 assert(Params); 816 assert(!Args || Params->size() == Args->size()); 817 818 Out << "template <"; 819 820 for (unsigned i = 0, e = Params->size(); i != e; ++i) { 821 if (i != 0) 822 Out << ", "; 823 824 const Decl *Param = Params->getParam(i); 825 if (const TemplateTypeParmDecl *TTP = 826 dyn_cast<TemplateTypeParmDecl>(Param)) { 827 828 if (TTP->wasDeclaredWithTypename()) 829 Out << "typename "; 830 else 831 Out << "class "; 832 833 if (TTP->isParameterPack()) 834 Out << "... "; 835 836 Out << *TTP; 837 838 if (Args) { 839 Out << " = "; 840 Args->get(i).print(Policy, Out); 841 } else if (TTP->hasDefaultArgument()) { 842 Out << " = "; 843 Out << TTP->getDefaultArgument().getAsString(Policy); 844 }; 845 } else if (const NonTypeTemplateParmDecl *NTTP = 846 dyn_cast<NonTypeTemplateParmDecl>(Param)) { 847 Out << NTTP->getType().getAsString(Policy); 848 849 if (NTTP->isParameterPack() && !isa<PackExpansionType>(NTTP->getType())) 850 Out << "..."; 851 852 if (IdentifierInfo *Name = NTTP->getIdentifier()) { 853 Out << ' '; 854 Out << Name->getName(); 855 } 856 857 if (Args) { 858 Out << " = "; 859 Args->get(i).print(Policy, Out); 860 } else if (NTTP->hasDefaultArgument()) { 861 Out << " = "; 862 NTTP->getDefaultArgument()->printPretty(Out, 0, Policy, Indentation); 863 } 864 } else if (const TemplateTemplateParmDecl *TTPD = 865 dyn_cast<TemplateTemplateParmDecl>(Param)) { 866 VisitTemplateDecl(TTPD); 867 // FIXME: print the default argument, if present. 868 } 869 } 870 871 Out << "> "; 872 } 873 874 void DeclPrinter::VisitTemplateDecl(const TemplateDecl *D) { 875 PrintTemplateParameters(D->getTemplateParameters()); 876 877 if (const TemplateTemplateParmDecl *TTP = 878 dyn_cast<TemplateTemplateParmDecl>(D)) { 879 Out << "class "; 880 if (TTP->isParameterPack()) 881 Out << "..."; 882 Out << D->getName(); 883 } else { 884 Visit(D->getTemplatedDecl()); 885 } 886 } 887 888 void DeclPrinter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 889 if (PrintInstantiation) { 890 TemplateParameterList *Params = D->getTemplateParameters(); 891 for (FunctionTemplateDecl::spec_iterator I = D->spec_begin(), E = D->spec_end(); 892 I != E; ++I) { 893 PrintTemplateParameters(Params, (*I)->getTemplateSpecializationArgs()); 894 Visit(*I); 895 } 896 } 897 898 return VisitRedeclarableTemplateDecl(D); 899 } 900 901 void DeclPrinter::VisitClassTemplateDecl(ClassTemplateDecl *D) { 902 if (PrintInstantiation) { 903 TemplateParameterList *Params = D->getTemplateParameters(); 904 for (ClassTemplateDecl::spec_iterator I = D->spec_begin(), E = D->spec_end(); 905 I != E; ++I) { 906 PrintTemplateParameters(Params, &(*I)->getTemplateArgs()); 907 Visit(*I); 908 Out << '\n'; 909 } 910 } 911 912 return VisitRedeclarableTemplateDecl(D); 913 } 914 915 //---------------------------------------------------------------------------- 916 // Objective-C declarations 917 //---------------------------------------------------------------------------- 918 919 void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) { 920 if (OMD->isInstanceMethod()) 921 Out << "- "; 922 else 923 Out << "+ "; 924 if (!OMD->getReturnType().isNull()) 925 Out << '(' << OMD->getASTContext() 926 .getUnqualifiedObjCPointerType(OMD->getReturnType()) 927 .getAsString(Policy) << ")"; 928 929 std::string name = OMD->getSelector().getAsString(); 930 std::string::size_type pos, lastPos = 0; 931 for (const auto *PI : OMD->params()) { 932 // FIXME: selector is missing here! 933 pos = name.find_first_of(':', lastPos); 934 Out << " " << name.substr(lastPos, pos - lastPos); 935 Out << ":(" << PI->getASTContext().getUnqualifiedObjCPointerType(PI->getType()). 936 getAsString(Policy) << ')' << *PI; 937 lastPos = pos + 1; 938 } 939 940 if (OMD->param_begin() == OMD->param_end()) 941 Out << " " << name; 942 943 if (OMD->isVariadic()) 944 Out << ", ..."; 945 946 if (OMD->getBody() && !Policy.TerseOutput) { 947 Out << ' '; 948 OMD->getBody()->printPretty(Out, 0, Policy); 949 Out << '\n'; 950 } 951 else if (Policy.PolishForDeclaration) 952 Out << ';'; 953 } 954 955 void DeclPrinter::VisitObjCImplementationDecl(ObjCImplementationDecl *OID) { 956 std::string I = OID->getNameAsString(); 957 ObjCInterfaceDecl *SID = OID->getSuperClass(); 958 959 if (SID) 960 Out << "@implementation " << I << " : " << *SID; 961 else 962 Out << "@implementation " << I; 963 964 if (OID->ivar_size() > 0) { 965 Out << "{\n"; 966 Indentation += Policy.Indentation; 967 for (ObjCImplementationDecl::ivar_iterator I = OID->ivar_begin(), 968 E = OID->ivar_end(); I != E; ++I) { 969 Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()). 970 getAsString(Policy) << ' ' << **I << ";\n"; 971 } 972 Indentation -= Policy.Indentation; 973 Out << "}\n"; 974 } 975 VisitDeclContext(OID, false); 976 Out << "@end"; 977 } 978 979 void DeclPrinter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *OID) { 980 std::string I = OID->getNameAsString(); 981 ObjCInterfaceDecl *SID = OID->getSuperClass(); 982 983 if (!OID->isThisDeclarationADefinition()) { 984 Out << "@class " << I << ";"; 985 return; 986 } 987 bool eolnOut = false; 988 if (SID) 989 Out << "@interface " << I << " : " << *SID; 990 else 991 Out << "@interface " << I; 992 993 // Protocols? 994 const ObjCList<ObjCProtocolDecl> &Protocols = OID->getReferencedProtocols(); 995 if (!Protocols.empty()) { 996 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 997 E = Protocols.end(); I != E; ++I) 998 Out << (I == Protocols.begin() ? '<' : ',') << **I; 999 Out << "> "; 1000 } 1001 1002 if (OID->ivar_size() > 0) { 1003 Out << "{\n"; 1004 eolnOut = true; 1005 Indentation += Policy.Indentation; 1006 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(), 1007 E = OID->ivar_end(); I != E; ++I) { 1008 Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()). 1009 getAsString(Policy) << ' ' << **I << ";\n"; 1010 } 1011 Indentation -= Policy.Indentation; 1012 Out << "}\n"; 1013 } 1014 else if (SID) { 1015 Out << "\n"; 1016 eolnOut = true; 1017 } 1018 1019 VisitDeclContext(OID, false); 1020 if (!eolnOut) 1021 Out << ' '; 1022 Out << "@end"; 1023 // FIXME: implement the rest... 1024 } 1025 1026 void DeclPrinter::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) { 1027 if (!PID->isThisDeclarationADefinition()) { 1028 Out << "@protocol " << *PID << ";\n"; 1029 return; 1030 } 1031 // Protocols? 1032 const ObjCList<ObjCProtocolDecl> &Protocols = PID->getReferencedProtocols(); 1033 if (!Protocols.empty()) { 1034 Out << "@protocol " << *PID; 1035 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 1036 E = Protocols.end(); I != E; ++I) 1037 Out << (I == Protocols.begin() ? '<' : ',') << **I; 1038 Out << ">\n"; 1039 } else 1040 Out << "@protocol " << *PID << '\n'; 1041 VisitDeclContext(PID, false); 1042 Out << "@end"; 1043 } 1044 1045 void DeclPrinter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *PID) { 1046 Out << "@implementation " << *PID->getClassInterface() << '(' << *PID <<")\n"; 1047 1048 VisitDeclContext(PID, false); 1049 Out << "@end"; 1050 // FIXME: implement the rest... 1051 } 1052 1053 void DeclPrinter::VisitObjCCategoryDecl(ObjCCategoryDecl *PID) { 1054 Out << "@interface " << *PID->getClassInterface() << '(' << *PID << ")\n"; 1055 if (PID->ivar_size() > 0) { 1056 Out << "{\n"; 1057 Indentation += Policy.Indentation; 1058 for (ObjCCategoryDecl::ivar_iterator I = PID->ivar_begin(), 1059 E = PID->ivar_end(); I != E; ++I) { 1060 Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()). 1061 getAsString(Policy) << ' ' << **I << ";\n"; 1062 } 1063 Indentation -= Policy.Indentation; 1064 Out << "}\n"; 1065 } 1066 1067 VisitDeclContext(PID, false); 1068 Out << "@end"; 1069 1070 // FIXME: implement the rest... 1071 } 1072 1073 void DeclPrinter::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *AID) { 1074 Out << "@compatibility_alias " << *AID 1075 << ' ' << *AID->getClassInterface() << ";\n"; 1076 } 1077 1078 /// PrintObjCPropertyDecl - print a property declaration. 1079 /// 1080 void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) { 1081 if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Required) 1082 Out << "@required\n"; 1083 else if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Optional) 1084 Out << "@optional\n"; 1085 1086 Out << "@property"; 1087 if (PDecl->getPropertyAttributes() != ObjCPropertyDecl::OBJC_PR_noattr) { 1088 bool first = true; 1089 Out << " ("; 1090 if (PDecl->getPropertyAttributes() & 1091 ObjCPropertyDecl::OBJC_PR_readonly) { 1092 Out << (first ? ' ' : ',') << "readonly"; 1093 first = false; 1094 } 1095 1096 if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { 1097 Out << (first ? ' ' : ',') << "getter = "; 1098 PDecl->getGetterName().print(Out); 1099 first = false; 1100 } 1101 if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) { 1102 Out << (first ? ' ' : ',') << "setter = "; 1103 PDecl->getSetterName().print(Out); 1104 first = false; 1105 } 1106 1107 if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_assign) { 1108 Out << (first ? ' ' : ',') << "assign"; 1109 first = false; 1110 } 1111 1112 if (PDecl->getPropertyAttributes() & 1113 ObjCPropertyDecl::OBJC_PR_readwrite) { 1114 Out << (first ? ' ' : ',') << "readwrite"; 1115 first = false; 1116 } 1117 1118 if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain) { 1119 Out << (first ? ' ' : ',') << "retain"; 1120 first = false; 1121 } 1122 1123 if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_strong) { 1124 Out << (first ? ' ' : ',') << "strong"; 1125 first = false; 1126 } 1127 1128 if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy) { 1129 Out << (first ? ' ' : ',') << "copy"; 1130 first = false; 1131 } 1132 1133 if (PDecl->getPropertyAttributes() & 1134 ObjCPropertyDecl::OBJC_PR_nonatomic) { 1135 Out << (first ? ' ' : ',') << "nonatomic"; 1136 first = false; 1137 } 1138 if (PDecl->getPropertyAttributes() & 1139 ObjCPropertyDecl::OBJC_PR_atomic) { 1140 Out << (first ? ' ' : ',') << "atomic"; 1141 first = false; 1142 } 1143 1144 (void) first; // Silence dead store warning due to idiomatic code. 1145 Out << " )"; 1146 } 1147 Out << ' ' << PDecl->getASTContext().getUnqualifiedObjCPointerType(PDecl->getType()). 1148 getAsString(Policy) << ' ' << *PDecl; 1149 if (Policy.PolishForDeclaration) 1150 Out << ';'; 1151 } 1152 1153 void DeclPrinter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PID) { 1154 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) 1155 Out << "@synthesize "; 1156 else 1157 Out << "@dynamic "; 1158 Out << *PID->getPropertyDecl(); 1159 if (PID->getPropertyIvarDecl()) 1160 Out << '=' << *PID->getPropertyIvarDecl(); 1161 } 1162 1163 void DeclPrinter::VisitUsingDecl(UsingDecl *D) { 1164 if (!D->isAccessDeclaration()) 1165 Out << "using "; 1166 if (D->hasTypename()) 1167 Out << "typename "; 1168 D->getQualifier()->print(Out, Policy); 1169 Out << *D; 1170 } 1171 1172 void 1173 DeclPrinter::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) { 1174 Out << "using typename "; 1175 D->getQualifier()->print(Out, Policy); 1176 Out << D->getDeclName(); 1177 } 1178 1179 void DeclPrinter::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 1180 if (!D->isAccessDeclaration()) 1181 Out << "using "; 1182 D->getQualifier()->print(Out, Policy); 1183 Out << D->getName(); 1184 } 1185 1186 void DeclPrinter::VisitUsingShadowDecl(UsingShadowDecl *D) { 1187 // ignore 1188 } 1189 1190 void DeclPrinter::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) { 1191 Out << "#pragma omp threadprivate"; 1192 if (!D->varlist_empty()) { 1193 for (OMPThreadPrivateDecl::varlist_iterator I = D->varlist_begin(), 1194 E = D->varlist_end(); 1195 I != E; ++I) { 1196 Out << (I == D->varlist_begin() ? '(' : ','); 1197 NamedDecl *ND = cast<NamedDecl>(cast<DeclRefExpr>(*I)->getDecl()); 1198 ND->printQualifiedName(Out); 1199 } 1200 Out << ")"; 1201 } 1202 } 1203 1204