DeclPrinter.cpp 49 KB

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