diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index 56fdaf1c724ac..34bed375cb965 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -613,7 +613,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { /// Return the name of the provided `Ty` (that must be a reference) with a synthesized lifetime /// name where required. pub(super) fn get_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String { - let mut printer = ty::print::FmtPrinter::new(self.infcx.tcx, Namespace::TypeNS); + let mut p = ty::print::FmtPrinter::new(self.infcx.tcx, Namespace::TypeNS); // We need to add synthesized lifetimes where appropriate. We do // this by hooking into the pretty printer and telling it to label the @@ -624,19 +624,19 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { | ty::RePlaceholder(ty::PlaceholderRegion { bound: ty::BoundRegion { kind: br, .. }, .. - }) => printer.region_highlight_mode.highlighting_bound_region(br, counter), + }) => p.region_highlight_mode.highlighting_bound_region(br, counter), _ => {} } } - ty.print(&mut printer).unwrap(); - printer.into_buffer() + ty.print(&mut p).unwrap(); + p.into_buffer() } /// Returns the name of the provided `Ty` (that must be a reference)'s region with a /// synthesized lifetime name where required. pub(super) fn get_region_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String { - let mut printer = ty::print::FmtPrinter::new(self.infcx.tcx, Namespace::TypeNS); + let mut p = ty::print::FmtPrinter::new(self.infcx.tcx, Namespace::TypeNS); let region = if let ty::Ref(region, ..) = ty.kind() { match region.kind() { @@ -644,7 +644,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { | ty::RePlaceholder(ty::PlaceholderRegion { bound: ty::BoundRegion { kind: br, .. }, .. - }) => printer.region_highlight_mode.highlighting_bound_region(br, counter), + }) => p.region_highlight_mode.highlighting_bound_region(br, counter), _ => {} } region @@ -652,8 +652,8 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { bug!("ty for annotation of borrow region is not a reference"); }; - region.print(&mut printer).unwrap(); - printer.into_buffer() + region.print(&mut p).unwrap(); + p.into_buffer() } /// Add a note to region errors and borrow explanations when higher-ranked regions in predicates diff --git a/compiler/rustc_const_eval/src/interpret/operand.rs b/compiler/rustc_const_eval/src/interpret/operand.rs index 4171345790864..1454180907001 100644 --- a/compiler/rustc_const_eval/src/interpret/operand.rs +++ b/compiler/rustc_const_eval/src/interpret/operand.rs @@ -188,18 +188,18 @@ pub struct ImmTy<'tcx, Prov: Provenance = CtfeProvenance> { impl std::fmt::Display for ImmTy<'_, Prov> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { /// Helper function for printing a scalar to a FmtPrinter - fn p<'a, 'tcx, Prov: Provenance>( - cx: &mut FmtPrinter<'a, 'tcx>, + fn print_scalar<'a, 'tcx, Prov: Provenance>( + p: &mut FmtPrinter<'a, 'tcx>, s: Scalar, ty: Ty<'tcx>, ) -> Result<(), std::fmt::Error> { match s { - Scalar::Int(int) => cx.pretty_print_const_scalar_int(int, ty, true), + Scalar::Int(int) => p.pretty_print_const_scalar_int(int, ty, true), Scalar::Ptr(ptr, _sz) => { // Just print the ptr value. `pretty_print_const_scalar_ptr` would also try to // print what is points to, which would fail since it has no access to the local // memory. - cx.pretty_print_const_pointer(ptr, ty) + p.pretty_print_const_pointer(ptr, ty) } } } @@ -207,8 +207,9 @@ impl std::fmt::Display for ImmTy<'_, Prov> { match self.imm { Immediate::Scalar(s) => { if let Some(ty) = tcx.lift(self.layout.ty) { - let s = - FmtPrinter::print_string(tcx, Namespace::ValueNS, |cx| p(cx, s, ty))?; + let s = FmtPrinter::print_string(tcx, Namespace::ValueNS, |p| { + print_scalar(p, s, ty) + })?; f.write_str(&s)?; return Ok(()); } diff --git a/compiler/rustc_const_eval/src/util/type_name.rs b/compiler/rustc_const_eval/src/util/type_name.rs index e8f2728a7728f..e6b9759819f1b 100644 --- a/compiler/rustc_const_eval/src/util/type_name.rs +++ b/compiler/rustc_const_eval/src/util/type_name.rs @@ -4,7 +4,7 @@ use rustc_data_structures::intern::Interned; use rustc_hir::def_id::CrateNum; use rustc_hir::definitions::DisambiguatedDefPathData; use rustc_middle::bug; -use rustc_middle::ty::print::{PrettyPrinter, Print, PrintError, Printer}; +use rustc_middle::ty::print::{PrettyPrinter, PrintError, Printer}; use rustc_middle::ty::{self, GenericArg, GenericArgKind, Ty, TyCtxt}; struct AbsolutePathPrinter<'tcx> { @@ -18,7 +18,7 @@ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> { } fn print_region(&mut self, _region: ty::Region<'_>) -> Result<(), PrintError> { - Ok(()) + unreachable!(); // because `::should_print_region` returns false } fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> { @@ -89,7 +89,6 @@ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> { fn path_append_impl( &mut self, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, - _disambiguated_data: &DisambiguatedDefPathData, self_ty: Ty<'tcx>, trait_ref: Option>, ) -> Result<(), PrintError> { @@ -138,19 +137,6 @@ impl<'tcx> PrettyPrinter<'tcx> for AbsolutePathPrinter<'tcx> { fn should_print_region(&self, _region: ty::Region<'_>) -> bool { false } - fn comma_sep(&mut self, mut elems: impl Iterator) -> Result<(), PrintError> - where - T: Print<'tcx, Self>, - { - if let Some(first) = elems.next() { - first.print(self)?; - for elem in elems { - self.path.push_str(", "); - elem.print(self)?; - } - } - Ok(()) - } fn generic_delimiters( &mut self, @@ -179,7 +165,7 @@ impl Write for AbsolutePathPrinter<'_> { } pub fn type_name<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> String { - let mut printer = AbsolutePathPrinter { tcx, path: String::new() }; - printer.print_type(ty).unwrap(); - printer.path + let mut p = AbsolutePathPrinter { tcx, path: String::new() }; + p.print_type(ty).unwrap(); + p.path } diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index b694d3dd49b79..11181d10af5ee 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -756,22 +756,22 @@ impl<'tcx> LateContext<'tcx> { } fn print_region(&mut self, _region: ty::Region<'_>) -> Result<(), PrintError> { - Ok(()) + unreachable!(); // because `path_generic_args` ignores the `GenericArgs` } fn print_type(&mut self, _ty: Ty<'tcx>) -> Result<(), PrintError> { - Ok(()) + unreachable!(); // because `path_generic_args` ignores the `GenericArgs` } fn print_dyn_existential( &mut self, _predicates: &'tcx ty::List>, ) -> Result<(), PrintError> { - Ok(()) + unreachable!(); // because `path_generic_args` ignores the `GenericArgs` } fn print_const(&mut self, _ct: ty::Const<'tcx>) -> Result<(), PrintError> { - Ok(()) + unreachable!(); // because `path_generic_args` ignores the `GenericArgs` } fn path_crate(&mut self, cnum: CrateNum) -> Result<(), PrintError> { @@ -784,10 +784,10 @@ impl<'tcx> LateContext<'tcx> { self_ty: Ty<'tcx>, trait_ref: Option>, ) -> Result<(), PrintError> { - if trait_ref.is_none() { - if let ty::Adt(def, args) = self_ty.kind() { - return self.print_def_path(def.did(), args); - } + if trait_ref.is_none() + && let ty::Adt(def, args) = self_ty.kind() + { + return self.print_def_path(def.did(), args); } // This shouldn't ever be needed, but just in case: @@ -803,7 +803,6 @@ impl<'tcx> LateContext<'tcx> { fn path_append_impl( &mut self, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, - _disambiguated_data: &DisambiguatedDefPathData, self_ty: Ty<'tcx>, trait_ref: Option>, ) -> Result<(), PrintError> { @@ -854,9 +853,9 @@ impl<'tcx> LateContext<'tcx> { } } - let mut printer = AbsolutePathPrinter { tcx: self.tcx, path: vec![] }; - printer.print_def_path(def_id, &[]).unwrap(); - printer.path + let mut p = AbsolutePathPrinter { tcx: self.tcx, path: vec![] }; + p.print_def_path(def_id, &[]).unwrap(); + p.path } /// Returns the associated type `name` for `self_ty` as an implementation of `trait_id`. diff --git a/compiler/rustc_middle/src/mir/pretty.rs b/compiler/rustc_middle/src/mir/pretty.rs index 809cdb329f79e..f8a48005a7363 100644 --- a/compiler/rustc_middle/src/mir/pretty.rs +++ b/compiler/rustc_middle/src/mir/pretty.rs @@ -1197,8 +1197,8 @@ impl<'tcx> Debug for Rvalue<'tcx> { ty::tls::with(|tcx| { let variant_def = &tcx.adt_def(adt_did).variant(variant); let args = tcx.lift(args).expect("could not lift for printing"); - let name = FmtPrinter::print_string(tcx, Namespace::ValueNS, |cx| { - cx.print_def_path(variant_def.def_id, args) + let name = FmtPrinter::print_string(tcx, Namespace::ValueNS, |p| { + p.print_def_path(variant_def.def_id, args) })?; match variant_def.ctor_kind() { @@ -1473,9 +1473,9 @@ impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> { }; let fmt_valtree = |cv: &ty::Value<'tcx>| { - let mut cx = FmtPrinter::new(self.tcx, Namespace::ValueNS); - cx.pretty_print_const_valtree(*cv, /*print_ty*/ true).unwrap(); - cx.into_buffer() + let mut p = FmtPrinter::new(self.tcx, Namespace::ValueNS); + p.pretty_print_const_valtree(*cv, /*print_ty*/ true).unwrap(); + p.into_buffer() }; let val = match const_ { @@ -1967,10 +1967,10 @@ fn pretty_print_const_value_tcx<'tcx>( .expect("destructed mir constant of adt without variant idx"); let variant_def = &def.variant(variant_idx); let args = tcx.lift(args).unwrap(); - let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS); - cx.print_alloc_ids = true; - cx.print_value_path(variant_def.def_id, args)?; - fmt.write_str(&cx.into_buffer())?; + let mut p = FmtPrinter::new(tcx, Namespace::ValueNS); + p.print_alloc_ids = true; + p.print_value_path(variant_def.def_id, args)?; + fmt.write_str(&p.into_buffer())?; match variant_def.ctor_kind() { Some(CtorKind::Const) => {} @@ -2001,18 +2001,18 @@ fn pretty_print_const_value_tcx<'tcx>( } } (ConstValue::Scalar(scalar), _) => { - let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS); - cx.print_alloc_ids = true; + let mut p = FmtPrinter::new(tcx, Namespace::ValueNS); + p.print_alloc_ids = true; let ty = tcx.lift(ty).unwrap(); - cx.pretty_print_const_scalar(scalar, ty)?; - fmt.write_str(&cx.into_buffer())?; + p.pretty_print_const_scalar(scalar, ty)?; + fmt.write_str(&p.into_buffer())?; return Ok(()); } (ConstValue::ZeroSized, ty::FnDef(d, s)) => { - let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS); - cx.print_alloc_ids = true; - cx.print_value_path(*d, s)?; - fmt.write_str(&cx.into_buffer())?; + let mut p = FmtPrinter::new(tcx, Namespace::ValueNS); + p.print_alloc_ids = true; + p.print_value_path(*d, s)?; + fmt.write_str(&p.into_buffer())?; return Ok(()); } // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading diff --git a/compiler/rustc_middle/src/ty/error.rs b/compiler/rustc_middle/src/ty/error.rs index 13723874ad3a1..c24dc983d2160 100644 --- a/compiler/rustc_middle/src/ty/error.rs +++ b/compiler/rustc_middle/src/ty/error.rs @@ -213,13 +213,13 @@ impl<'tcx> Ty<'tcx> { } impl<'tcx> TyCtxt<'tcx> { - pub fn string_with_limit(self, p: T, length_limit: usize) -> String + pub fn string_with_limit(self, t: T, length_limit: usize) -> String where T: Copy + for<'a, 'b> Lift, Lifted: Print<'b, FmtPrinter<'a, 'b>>>, { let mut type_limit = 50; - let regular = FmtPrinter::print_string(self, hir::def::Namespace::TypeNS, |cx| { - self.lift(p).expect("could not lift for printing").print(cx) + let regular = FmtPrinter::print_string(self, hir::def::Namespace::TypeNS, |p| { + self.lift(t).expect("could not lift for printing").print(p) }) .expect("could not write to `String`"); if regular.len() <= length_limit { @@ -229,16 +229,16 @@ impl<'tcx> TyCtxt<'tcx> { loop { // Look for the longest properly trimmed path that still fits in length_limit. short = with_forced_trimmed_paths!({ - let mut cx = FmtPrinter::new_with_limit( + let mut p = FmtPrinter::new_with_limit( self, hir::def::Namespace::TypeNS, rustc_session::Limit(type_limit), ); - self.lift(p) + self.lift(t) .expect("could not lift for printing") - .print(&mut cx) + .print(&mut p) .expect("could not print type"); - cx.into_buffer() + p.into_buffer() }); if short.len() <= length_limit || type_limit == 0 { break; @@ -252,12 +252,12 @@ impl<'tcx> TyCtxt<'tcx> { /// `tcx.short_string(ty, diag.long_ty_path())`. The diagnostic itself is the one that keeps /// the existence of a "long type" anywhere in the diagnostic, so the note telling the user /// where we wrote the file to is only printed once. - pub fn short_string(self, p: T, path: &mut Option) -> String + pub fn short_string(self, t: T, path: &mut Option) -> String where T: Copy + Hash + for<'a, 'b> Lift, Lifted: Print<'b, FmtPrinter<'a, 'b>>>, { - let regular = FmtPrinter::print_string(self, hir::def::Namespace::TypeNS, |cx| { - self.lift(p).expect("could not lift for printing").print(cx) + let regular = FmtPrinter::print_string(self, hir::def::Namespace::TypeNS, |p| { + self.lift(t).expect("could not lift for printing").print(p) }) .expect("could not write to `String`"); @@ -270,13 +270,13 @@ impl<'tcx> TyCtxt<'tcx> { if regular.len() <= width * 2 / 3 { return regular; } - let short = self.string_with_limit(p, length_limit); + let short = self.string_with_limit(t, length_limit); if regular == short { return regular; } // Ensure we create an unique file for the type passed in when we create a file. let mut s = DefaultHasher::new(); - p.hash(&mut s); + t.hash(&mut s); let hash = s.finish(); *path = Some(path.take().unwrap_or_else(|| { self.output_filenames(()).temp_path_for_diagnostic(&format!("long-type-{hash}.txt")) diff --git a/compiler/rustc_middle/src/ty/instance.rs b/compiler/rustc_middle/src/ty/instance.rs index eb35a95203261..16873b6ee21ad 100644 --- a/compiler/rustc_middle/src/ty/instance.rs +++ b/compiler/rustc_middle/src/ty/instance.rs @@ -397,13 +397,13 @@ pub fn fmt_instance( ty::tls::with(|tcx| { let args = tcx.lift(instance.args).expect("could not lift for printing"); - let mut cx = if let Some(type_length) = type_length { + let mut p = if let Some(type_length) = type_length { FmtPrinter::new_with_limit(tcx, Namespace::ValueNS, type_length) } else { FmtPrinter::new(tcx, Namespace::ValueNS) }; - cx.print_def_path(instance.def_id(), args)?; - let s = cx.into_buffer(); + p.print_def_path(instance.def_id(), args)?; + let s = p.into_buffer(); f.write_str(&s) })?; diff --git a/compiler/rustc_middle/src/ty/print/mod.rs b/compiler/rustc_middle/src/ty/print/mod.rs index 9172c5d3ab752..8a125c7fe2840 100644 --- a/compiler/rustc_middle/src/ty/print/mod.rs +++ b/compiler/rustc_middle/src/ty/print/mod.rs @@ -18,7 +18,7 @@ use super::Lift; pub type PrintError = std::fmt::Error; pub trait Print<'tcx, P> { - fn print(&self, cx: &mut P) -> Result<(), PrintError>; + fn print(&self, p: &mut P) -> Result<(), PrintError>; } /// Interface for outputting user-facing "type-system entities" @@ -88,7 +88,6 @@ pub trait Printer<'tcx>: Sized { fn path_append_impl( &mut self, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, - disambiguated_data: &DisambiguatedDefPathData, self_ty: Ty<'tcx>, trait_ref: Option>, ) -> Result<(), PrintError>; @@ -148,7 +147,7 @@ pub trait Printer<'tcx>: Sized { && args.len() > parent_args.len() { return self.path_generic_args( - |cx| cx.print_def_path(def_id, parent_args), + |p| p.print_def_path(def_id, parent_args), &args[..parent_args.len() + 1][..1], ); } else { @@ -170,7 +169,7 @@ pub trait Printer<'tcx>: Sized { if !generics.is_own_empty() && args.len() >= generics.count() { let args = generics.own_args_no_defaults(self.tcx(), args); return self.path_generic_args( - |cx| cx.print_def_path(def_id, parent_args), + |p| p.print_def_path(def_id, parent_args), args, ); } @@ -186,16 +185,16 @@ pub trait Printer<'tcx>: Sized { } self.path_append( - |cx: &mut Self| { + |p: &mut Self| { if trait_qualify_parent { let trait_ref = ty::TraitRef::new( - cx.tcx(), + p.tcx(), parent_def_id, parent_args.iter().copied(), ); - cx.path_qualified(trait_ref.self_ty(), Some(trait_ref)) + p.path_qualified(trait_ref.self_ty(), Some(trait_ref)) } else { - cx.print_def_path(parent_def_id, parent_args) + p.print_def_path(parent_def_id, parent_args) } }, &key.disambiguated_data, @@ -236,12 +235,7 @@ pub trait Printer<'tcx>: Sized { // If the impl is not co-located with either self-type or // trait-type, then fallback to a format that identifies // the module more clearly. - self.path_append_impl( - |cx| cx.print_def_path(parent_def_id, &[]), - &key.disambiguated_data, - self_ty, - impl_trait_ref, - ) + self.path_append_impl(|p| p.print_def_path(parent_def_id, &[]), self_ty, impl_trait_ref) } else { // Otherwise, try to give a good form that would be valid language // syntax. Preferably using associated item notation. @@ -312,26 +306,26 @@ pub fn characteristic_def_id_of_type(ty: Ty<'_>) -> Option { } impl<'tcx, P: Printer<'tcx>> Print<'tcx, P> for ty::Region<'tcx> { - fn print(&self, cx: &mut P) -> Result<(), PrintError> { - cx.print_region(*self) + fn print(&self, p: &mut P) -> Result<(), PrintError> { + p.print_region(*self) } } impl<'tcx, P: Printer<'tcx>> Print<'tcx, P> for Ty<'tcx> { - fn print(&self, cx: &mut P) -> Result<(), PrintError> { - cx.print_type(*self) + fn print(&self, p: &mut P) -> Result<(), PrintError> { + p.print_type(*self) } } impl<'tcx, P: Printer<'tcx>> Print<'tcx, P> for &'tcx ty::List> { - fn print(&self, cx: &mut P) -> Result<(), PrintError> { - cx.print_dyn_existential(self) + fn print(&self, p: &mut P) -> Result<(), PrintError> { + p.print_dyn_existential(self) } } impl<'tcx, P: Printer<'tcx>> Print<'tcx, P> for ty::Const<'tcx> { - fn print(&self, cx: &mut P) -> Result<(), PrintError> { - cx.print_const(*self) + fn print(&self, p: &mut P) -> Result<(), PrintError> { + p.print_const(*self) } } @@ -351,9 +345,9 @@ where { fn print(t: &T, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { ty::tls::with(|tcx| { - let mut cx = FmtPrinter::new(tcx, Namespace::TypeNS); - tcx.lift(*t).expect("could not lift for printing").print(&mut cx)?; - fmt.write_str(&cx.into_buffer())?; + let mut p = FmtPrinter::new(tcx, Namespace::TypeNS); + tcx.lift(*t).expect("could not lift for printing").print(&mut p)?; + fmt.write_str(&p.into_buffer())?; Ok(()) }) } diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 71eac294f1554..b381d62be47e6 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -29,33 +29,6 @@ use crate::ty::{ TypeFoldable, TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, }; -macro_rules! p { - (@$lit:literal) => { - write!(scoped_cx!(), $lit)? - }; - (@write($($data:expr),+)) => { - write!(scoped_cx!(), $($data),+)? - }; - (@print($x:expr)) => { - $x.print(scoped_cx!())? - }; - (@$method:ident($($arg:expr),*)) => { - scoped_cx!().$method($($arg),*)? - }; - ($($elem:tt $(($($args:tt)*))?),+) => {{ - $(p!(@ $elem $(($($args)*))?);)+ - }}; -} -macro_rules! define_scoped_cx { - ($cx:ident) => { - macro_rules! scoped_cx { - () => { - $cx - }; - } - }; -} - thread_local! { static FORCE_IMPL_FILENAME_LINE: Cell = const { Cell::new(false) }; static SHOULD_PREFIX_WITH_CRATE: Cell = const { Cell::new(false) }; @@ -689,12 +662,11 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } } - self.generic_delimiters(|cx| { - define_scoped_cx!(cx); - - p!(print(self_ty)); + self.generic_delimiters(|p| { + self_ty.print(p)?; if let Some(trait_ref) = trait_ref { - p!(" as ", print(trait_ref.print_only_trait_path())); + write!(p, " as ")?; + trait_ref.print_only_trait_path().print(p)?; } Ok(()) }) @@ -708,121 +680,121 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ) -> Result<(), PrintError> { print_prefix(self)?; - self.generic_delimiters(|cx| { - define_scoped_cx!(cx); - - p!("impl "); + self.generic_delimiters(|p| { + write!(p, "impl ")?; if let Some(trait_ref) = trait_ref { - p!(print(trait_ref.print_only_trait_path()), " for "); + trait_ref.print_only_trait_path().print(p)?; + write!(p, " for ")?; } - p!(print(self_ty)); + self_ty.print(p)?; Ok(()) }) } fn pretty_print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> { - define_scoped_cx!(self); - match *ty.kind() { - ty::Bool => p!("bool"), - ty::Char => p!("char"), - ty::Int(t) => p!(write("{}", t.name_str())), - ty::Uint(t) => p!(write("{}", t.name_str())), - ty::Float(t) => p!(write("{}", t.name_str())), + ty::Bool => write!(self, "bool")?, + ty::Char => write!(self, "char")?, + ty::Int(t) => write!(self, "{}", t.name_str())?, + ty::Uint(t) => write!(self, "{}", t.name_str())?, + ty::Float(t) => write!(self, "{}", t.name_str())?, ty::Pat(ty, pat) => { - p!("(", print(ty), ") is ", write("{pat:?}")) + write!(self, "(")?; + ty.print(self)?; + write!(self, ") is {pat:?}")?; } ty::RawPtr(ty, mutbl) => { - p!(write("*{} ", mutbl.ptr_str())); - p!(print(ty)) + write!(self, "*{} ", mutbl.ptr_str())?; + ty.print(self)?; } ty::Ref(r, ty, mutbl) => { - p!("&"); + write!(self, "&")?; if self.should_print_region(r) { - p!(print(r), " "); + r.print(self)?; + write!(self, " ")?; } - p!(print(ty::TypeAndMut { ty, mutbl })) + ty::TypeAndMut { ty, mutbl }.print(self)?; } - ty::Never => p!("!"), + ty::Never => write!(self, "!")?, ty::Tuple(tys) => { - p!("(", comma_sep(tys.iter())); + write!(self, "(")?; + self.comma_sep(tys.iter())?; if tys.len() == 1 { - p!(","); + write!(self, ",")?; } - p!(")") + write!(self, ")")?; } ty::FnDef(def_id, args) => { if with_reduced_queries() { - p!(print_def_path(def_id, args)); + self.print_def_path(def_id, args)?; } else { let mut sig = self.tcx().fn_sig(def_id).instantiate(self.tcx(), args); if self.tcx().codegen_fn_attrs(def_id).safe_target_features { - p!("#[target_features] "); + write!(self, "#[target_features] ")?; sig = sig.map_bound(|mut sig| { sig.safety = hir::Safety::Safe; sig }); } - p!(print(sig), " {{", print_value_path(def_id, args), "}}"); + sig.print(self)?; + write!(self, " {{")?; + self.print_value_path(def_id, args)?; + write!(self, "}}")?; } } - ty::FnPtr(ref sig_tys, hdr) => p!(print(sig_tys.with(hdr))), + ty::FnPtr(ref sig_tys, hdr) => sig_tys.with(hdr).print(self)?, ty::UnsafeBinder(ref bound_ty) => { - self.wrap_binder(bound_ty, WrapBinderMode::Unsafe, |ty, cx| { - cx.pretty_print_type(*ty) + self.wrap_binder(bound_ty, WrapBinderMode::Unsafe, |ty, p| { + p.pretty_print_type(*ty) })?; } ty::Infer(infer_ty) => { if self.should_print_verbose() { - p!(write("{:?}", ty.kind())); + write!(self, "{:?}", ty.kind())?; return Ok(()); } if let ty::TyVar(ty_vid) = infer_ty { if let Some(name) = self.ty_infer_name(ty_vid) { - p!(write("{}", name)) + write!(self, "{name}")?; } else { - p!(write("{}", infer_ty)) + write!(self, "{infer_ty}")?; } } else { - p!(write("{}", infer_ty)) + write!(self, "{infer_ty}")?; } } - ty::Error(_) => p!("{{type error}}"), - ty::Param(ref param_ty) => p!(print(param_ty)), + ty::Error(_) => write!(self, "{{type error}}")?, + ty::Param(ref param_ty) => param_ty.print(self)?, ty::Bound(debruijn, bound_ty) => match bound_ty.kind { ty::BoundTyKind::Anon => { rustc_type_ir::debug_bound_var(self, debruijn, bound_ty.var)? } ty::BoundTyKind::Param(def_id) => match self.should_print_verbose() { - true => p!(write("{:?}", ty.kind())), - false => p!(write("{}", self.tcx().item_name(def_id))), + true => write!(self, "{:?}", ty.kind())?, + false => write!(self, "{}", self.tcx().item_name(def_id))?, }, }, - ty::Adt(def, args) => { - p!(print_def_path(def.did(), args)); - } + ty::Adt(def, args) => self.print_def_path(def.did(), args)?, ty::Dynamic(data, r, repr) => { let print_r = self.should_print_region(r); if print_r { - p!("("); + write!(self, "(")?; } match repr { - ty::Dyn => p!("dyn "), + ty::Dyn => write!(self, "dyn ")?, } - p!(print(data)); + data.print(self)?; if print_r { - p!(" + ", print(r), ")"); + write!(self, " + ")?; + r.print(self)?; + write!(self, ")")?; } } - ty::Foreign(def_id) => { - p!(print_def_path(def_id, &[])); - } - ty::Alias(ty::Projection | ty::Inherent | ty::Free, ref data) => { - p!(print(data)) - } - ty::Placeholder(placeholder) => p!(print(placeholder)), + ty::Foreign(def_id) => self.print_def_path(def_id, &[])?, + ty::Alias(ty::Projection | ty::Inherent | ty::Free, ref data) => data.print(self)?, + ty::Placeholder(placeholder) => placeholder.print(self)?, ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => { // We use verbose printing in 'NO_QUERIES' mode, to // avoid needing to call `predicates_of`. This should @@ -834,7 +806,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { // example.] if self.should_print_verbose() { // FIXME(eddyb) print this with `print_def_path`. - p!(write("Opaque({:?}, {})", def_id, args.print_as_list())); + write!(self, "Opaque({:?}, {})", def_id, args.print_as_list())?; return Ok(()); } @@ -849,17 +821,17 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { if d == def_id { // If the type alias directly starts with the `impl` of the // opaque type we're printing, then skip the `::{opaque#1}`. - p!(print_def_path(parent, args)); + self.print_def_path(parent, args)?; return Ok(()); } } // Complex opaque type, e.g. `type Foo = (i32, impl Debug);` - p!(print_def_path(def_id, args)); + self.print_def_path(def_id, args)?; return Ok(()); } _ => { if with_reduced_queries() { - p!(print_def_path(def_id, &[])); + self.print_def_path(def_id, &[])?; return Ok(()); } else { return self.pretty_print_opaque_impl_type(def_id, args); @@ -867,9 +839,9 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } } } - ty::Str => p!("str"), + ty::Str => write!(self, "str")?, ty::Coroutine(did, args) => { - p!("{{"); + write!(self, "{{")?; let coroutine_kind = self.tcx().coroutine_kind(did).unwrap(); let should_print_movability = self.should_print_verbose() || matches!(coroutine_kind, hir::CoroutineKind::Coroutine(_)); @@ -877,12 +849,12 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { if should_print_movability { match coroutine_kind.movability() { hir::Movability::Movable => {} - hir::Movability::Static => p!("static "), + hir::Movability::Static => write!(self, "static ")?, } } if !self.should_print_verbose() { - p!(write("{}", coroutine_kind)); + write!(self, "{coroutine_kind}")?; if coroutine_kind.is_fn_like() { // If we are printing an `async fn` coroutine type, then give the path // of the fn, instead of its span, because that will in most cases be @@ -891,66 +863,71 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { // This will look like: // {async fn body of some_fn()} let did_of_the_fn_item = self.tcx().parent(did); - p!(" of ", print_def_path(did_of_the_fn_item, args), "()"); + write!(self, " of ")?; + self.print_def_path(did_of_the_fn_item, args)?; + write!(self, "()")?; } else if let Some(local_did) = did.as_local() { let span = self.tcx().def_span(local_did); - p!(write( + write!( + self, "@{}", // This may end up in stderr diagnostics but it may also be emitted // into MIR. Hence we use the remapped path if available self.tcx().sess.source_map().span_to_embeddable_string(span) - )); + )?; } else { - p!("@", print_def_path(did, args)); + write!(self, "@")?; + self.print_def_path(did, args)?; } } else { - p!(print_def_path(did, args)); - p!( - " upvar_tys=", - print(args.as_coroutine().tupled_upvars_ty()), - " resume_ty=", - print(args.as_coroutine().resume_ty()), - " yield_ty=", - print(args.as_coroutine().yield_ty()), - " return_ty=", - print(args.as_coroutine().return_ty()) - ); + self.print_def_path(did, args)?; + write!(self, " upvar_tys=")?; + args.as_coroutine().tupled_upvars_ty().print(self)?; + write!(self, " resume_ty=")?; + args.as_coroutine().resume_ty().print(self)?; + write!(self, " yield_ty=")?; + args.as_coroutine().yield_ty().print(self)?; + write!(self, " return_ty=")?; + args.as_coroutine().return_ty().print(self)?; } - p!("}}") + write!(self, "}}")? } ty::CoroutineWitness(did, args) => { - p!(write("{{")); + write!(self, "{{")?; if !self.tcx().sess.verbose_internals() { - p!("coroutine witness"); + write!(self, "coroutine witness")?; if let Some(did) = did.as_local() { let span = self.tcx().def_span(did); - p!(write( + write!( + self, "@{}", // This may end up in stderr diagnostics but it may also be emitted // into MIR. Hence we use the remapped path if available self.tcx().sess.source_map().span_to_embeddable_string(span) - )); + )?; } else { - p!(write("@"), print_def_path(did, args)); + write!(self, "@")?; + self.print_def_path(did, args)?; } } else { - p!(print_def_path(did, args)); + self.print_def_path(did, args)?; } - p!("}}") + write!(self, "}}")? } ty::Closure(did, args) => { - p!(write("{{")); + write!(self, "{{")?; if !self.should_print_verbose() { - p!(write("closure")); + write!(self, "closure")?; if self.should_truncate() { write!(self, "@...}}")?; return Ok(()); } else { if let Some(did) = did.as_local() { if self.tcx().sess.opts.unstable_opts.span_free_formats { - p!("@", print_def_path(did.to_def_id(), args)); + write!(self, "@")?; + self.print_def_path(did.to_def_id(), args)?; } else { let span = self.tcx().def_span(did); let preference = if with_forced_trimmed_paths() { @@ -958,54 +935,56 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } else { FileNameDisplayPreference::Remapped }; - p!(write( + write!( + self, "@{}", - // This may end up in stderr diagnostics but it may also be emitted - // into MIR. Hence we use the remapped path if available + // This may end up in stderr diagnostics but it may also be + // emitted into MIR. Hence we use the remapped path if + // available self.tcx().sess.source_map().span_to_string(span, preference) - )); + )?; } } else { - p!(write("@"), print_def_path(did, args)); + write!(self, "@")?; + self.print_def_path(did, args)?; } } } else { - p!(print_def_path(did, args)); - p!( - " closure_kind_ty=", - print(args.as_closure().kind_ty()), - " closure_sig_as_fn_ptr_ty=", - print(args.as_closure().sig_as_fn_ptr_ty()), - " upvar_tys=", - print(args.as_closure().tupled_upvars_ty()) - ); + self.print_def_path(did, args)?; + write!(self, " closure_kind_ty=")?; + args.as_closure().kind_ty().print(self)?; + write!(self, " closure_sig_as_fn_ptr_ty=")?; + args.as_closure().sig_as_fn_ptr_ty().print(self)?; + write!(self, " upvar_tys=")?; + args.as_closure().tupled_upvars_ty().print(self)?; } - p!("}}"); + write!(self, "}}")?; } ty::CoroutineClosure(did, args) => { - p!(write("{{")); + write!(self, "{{")?; if !self.should_print_verbose() { match self.tcx().coroutine_kind(self.tcx().coroutine_for_closure(did)).unwrap() { hir::CoroutineKind::Desugared( hir::CoroutineDesugaring::Async, hir::CoroutineSource::Closure, - ) => p!("async closure"), + ) => write!(self, "async closure")?, hir::CoroutineKind::Desugared( hir::CoroutineDesugaring::AsyncGen, hir::CoroutineSource::Closure, - ) => p!("async gen closure"), + ) => write!(self, "async gen closure")?, hir::CoroutineKind::Desugared( hir::CoroutineDesugaring::Gen, hir::CoroutineSource::Closure, - ) => p!("gen closure"), + ) => write!(self, "gen closure")?, _ => unreachable!( "coroutine from coroutine-closure should have CoroutineSource::Closure" ), } if let Some(did) = did.as_local() { if self.tcx().sess.opts.unstable_opts.span_free_formats { - p!("@", print_def_path(did.to_def_id(), args)); + write!(self, "@")?; + self.print_def_path(did.to_def_id(), args)?; } else { let span = self.tcx().def_span(did); let preference = if with_forced_trimmed_paths() { @@ -1013,33 +992,43 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } else { FileNameDisplayPreference::Remapped }; - p!(write( + write!( + self, "@{}", // This may end up in stderr diagnostics but it may also be emitted // into MIR. Hence we use the remapped path if available self.tcx().sess.source_map().span_to_string(span, preference) - )); + )?; } } else { - p!(write("@"), print_def_path(did, args)); + write!(self, "@")?; + self.print_def_path(did, args)?; } } else { - p!(print_def_path(did, args)); - p!( - " closure_kind_ty=", - print(args.as_coroutine_closure().kind_ty()), - " signature_parts_ty=", - print(args.as_coroutine_closure().signature_parts_ty()), - " upvar_tys=", - print(args.as_coroutine_closure().tupled_upvars_ty()), - " coroutine_captures_by_ref_ty=", - print(args.as_coroutine_closure().coroutine_captures_by_ref_ty()) - ); + self.print_def_path(did, args)?; + write!(self, " closure_kind_ty=")?; + args.as_coroutine_closure().kind_ty().print(self)?; + write!(self, " signature_parts_ty=")?; + args.as_coroutine_closure().signature_parts_ty().print(self)?; + write!(self, " upvar_tys=")?; + args.as_coroutine_closure().tupled_upvars_ty().print(self)?; + write!(self, " coroutine_captures_by_ref_ty=")?; + args.as_coroutine_closure().coroutine_captures_by_ref_ty().print(self)?; } - p!("}}"); + write!(self, "}}")?; + } + ty::Array(ty, sz) => { + write!(self, "[")?; + ty.print(self)?; + write!(self, "; ")?; + sz.print(self)?; + write!(self, "]")?; + } + ty::Slice(ty) => { + write!(self, "[")?; + ty.print(self)?; + write!(self, "]")?; } - ty::Array(ty, sz) => p!("[", print(ty), "; ", print(sz), "]"), - ty::Slice(ty) => p!("[", print(ty), "]"), } Ok(()) @@ -1137,25 +1126,25 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { self.wrap_binder( &bound_args_and_self_ty, WrapBinderMode::ForAll, - |(args, _), cx| { - define_scoped_cx!(cx); - p!(write("{}", tcx.item_name(trait_def_id))); - p!("("); + |(args, _), p| { + write!(p, "{}", tcx.item_name(trait_def_id))?; + write!(p, "(")?; for (idx, ty) in args.iter().enumerate() { if idx > 0 { - p!(", "); + write!(p, ", ")?; } - p!(print(ty)); + ty.print(p)?; } - p!(")"); + write!(p, ")")?; if let Some(ty) = return_ty.skip_binder().as_type() { if !ty.is_unit() { - p!(" -> ", print(return_ty)); + write!(p, " -> ")?; + return_ty.print(p)?; } } - p!(write("{}", if paren_needed { ")" } else { "" })); + write!(p, "{}", if paren_needed { ")" } else { "" })?; first = false; Ok(()) @@ -1181,13 +1170,11 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { for (trait_pred, assoc_items) in traits { write!(self, "{}", if first { "" } else { " + " })?; - self.wrap_binder(&trait_pred, WrapBinderMode::ForAll, |trait_pred, cx| { - define_scoped_cx!(cx); - + self.wrap_binder(&trait_pred, WrapBinderMode::ForAll, |trait_pred, p| { if trait_pred.polarity == ty::PredicatePolarity::Negative { - p!("!"); + write!(p, "!")?; } - p!(print(trait_pred.trait_ref.print_only_trait_name())); + trait_pred.trait_ref.print_only_trait_name().print(p)?; let generics = tcx.generics_of(trait_pred.def_id()); let own_args = generics.own_args_no_defaults(tcx, trait_pred.trait_ref.args); @@ -1197,32 +1184,32 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { for ty in own_args { if first { - p!("<"); + write!(p, "<")?; first = false; } else { - p!(", "); + write!(p, ", ")?; } - p!(print(ty)); + ty.print(p)?; } for (assoc_item_def_id, term) in assoc_items { if first { - p!("<"); + write!(p, "<")?; first = false; } else { - p!(", "); + write!(p, ", ")?; } - p!(write("{} = ", tcx.associated_item(assoc_item_def_id).name())); + write!(p, "{} = ", tcx.associated_item(assoc_item_def_id).name())?; match term.skip_binder().kind() { - TermKind::Ty(ty) => p!(print(ty)), - TermKind::Const(c) => p!(print(c)), + TermKind::Ty(ty) => ty.print(p)?, + TermKind::Const(c) => c.print(p)?, }; } if !first { - p!(">"); + write!(p, ">")?; } } @@ -1322,9 +1309,9 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ) -> Result<(), PrintError> { let def_key = self.tcx().def_key(alias_ty.def_id); self.path_generic_args( - |cx| { - cx.path_append( - |cx| cx.path_qualified(alias_ty.self_ty(), None), + |p| { + p.path_append( + |p| p.path_qualified(alias_ty.self_ty(), None), &def_key.disambiguated_data, ) }, @@ -1388,23 +1375,22 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { let mut first = true; if let Some(bound_principal) = predicates.principal() { - self.wrap_binder(&bound_principal, WrapBinderMode::ForAll, |principal, cx| { - define_scoped_cx!(cx); - p!(print_def_path(principal.def_id, &[])); + self.wrap_binder(&bound_principal, WrapBinderMode::ForAll, |principal, p| { + p.print_def_path(principal.def_id, &[])?; let mut resugared = false; // Special-case `Fn(...) -> ...` and re-sugar it. - let fn_trait_kind = cx.tcx().fn_trait_kind_from_def_id(principal.def_id); - if !cx.should_print_verbose() && fn_trait_kind.is_some() { + let fn_trait_kind = p.tcx().fn_trait_kind_from_def_id(principal.def_id); + if !p.should_print_verbose() && fn_trait_kind.is_some() { if let ty::Tuple(tys) = principal.args.type_at(0).kind() { let mut projections = predicates.projection_bounds(); if let (Some(proj), None) = (projections.next(), projections.next()) { - p!(pretty_fn_sig( + p.pretty_fn_sig( tys, false, - proj.skip_binder().term.as_type().expect("Return type was a const") - )); + proj.skip_binder().term.as_type().expect("Return type was a const"), + )?; resugared = true; } } @@ -1414,18 +1400,18 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { // in order to place the projections inside the `<...>`. if !resugared { let principal_with_self = - principal.with_self_ty(cx.tcx(), cx.tcx().types.trait_object_dummy_self); + principal.with_self_ty(p.tcx(), p.tcx().types.trait_object_dummy_self); - let args = cx + let args = p .tcx() .generics_of(principal_with_self.def_id) - .own_args_no_defaults(cx.tcx(), principal_with_self.args); + .own_args_no_defaults(p.tcx(), principal_with_self.args); let bound_principal_with_self = bound_principal - .with_self_ty(cx.tcx(), cx.tcx().types.trait_object_dummy_self); + .with_self_ty(p.tcx(), p.tcx().types.trait_object_dummy_self); - let clause: ty::Clause<'tcx> = bound_principal_with_self.upcast(cx.tcx()); - let super_projections: Vec<_> = elaborate::elaborate(cx.tcx(), [clause]) + let clause: ty::Clause<'tcx> = bound_principal_with_self.upcast(p.tcx()); + let super_projections: Vec<_> = elaborate::elaborate(p.tcx(), [clause]) .filter_only_self() .filter_map(|clause| clause.as_projection_clause()) .collect(); @@ -1436,15 +1422,15 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { // Filter out projections that are implied by the super predicates. let proj_is_implied = super_projections.iter().any(|&super_proj| { let super_proj = super_proj.map_bound(|super_proj| { - ty::ExistentialProjection::erase_self_ty(cx.tcx(), super_proj) + ty::ExistentialProjection::erase_self_ty(p.tcx(), super_proj) }); // This function is sometimes called on types with erased and // anonymized regions, but the super projections can still // contain named regions. So we erase and anonymize everything // here to compare the types modulo regions below. - let proj = cx.tcx().erase_regions(proj); - let super_proj = cx.tcx().erase_regions(super_proj); + let proj = p.tcx().erase_regions(proj); + let super_proj = p.tcx().erase_regions(super_proj); proj == super_proj }); @@ -1458,16 +1444,16 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { .collect(); projections - .sort_by_cached_key(|proj| cx.tcx().item_name(proj.def_id).to_string()); + .sort_by_cached_key(|proj| p.tcx().item_name(proj.def_id).to_string()); if !args.is_empty() || !projections.is_empty() { - p!(generic_delimiters(|cx| { - cx.comma_sep(args.iter().copied())?; + p.generic_delimiters(|p| { + p.comma_sep(args.iter().copied())?; if !args.is_empty() && !projections.is_empty() { - write!(cx, ", ")?; + write!(p, ", ")?; } - cx.comma_sep(projections.iter().copied()) - })); + p.comma_sep(projections.iter().copied()) + })?; } } Ok(()) @@ -1476,11 +1462,9 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { first = false; } - define_scoped_cx!(self); - // Builtin bounds. // FIXME(eddyb) avoid printing twice (needed to ensure - // that the auto traits are sorted *and* printed via cx). + // that the auto traits are sorted *and* printed via p). let mut auto_traits: Vec<_> = predicates.auto_traits().collect(); // The auto traits come ordered by `DefPathHash`. While @@ -1494,11 +1478,11 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { for def_id in auto_traits { if !first { - p!(" + "); + write!(self, " + ")?; } first = false; - p!(print_def_path(def_id, &[])); + self.print_def_path(def_id, &[])?; } Ok(()) @@ -1510,18 +1494,18 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { c_variadic: bool, output: Ty<'tcx>, ) -> Result<(), PrintError> { - define_scoped_cx!(self); - - p!("(", comma_sep(inputs.iter().copied())); + write!(self, "(")?; + self.comma_sep(inputs.iter().copied())?; if c_variadic { if !inputs.is_empty() { - p!(", "); + write!(self, ", ")?; } - p!("..."); + write!(self, "...")?; } - p!(")"); + write!(self, ")")?; if !output.is_unit() { - p!(" -> ", print(output)); + write!(self, " -> ")?; + output.print(self)?; } Ok(()) @@ -1532,10 +1516,8 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ct: ty::Const<'tcx>, print_ty: bool, ) -> Result<(), PrintError> { - define_scoped_cx!(self); - if self.should_print_verbose() { - p!(write("{:?}", ct)); + write!(self, "{ct:?}")?; return Ok(()); } @@ -1543,25 +1525,28 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, args }) => { match self.tcx().def_kind(def) { DefKind::Const | DefKind::AssocConst => { - p!(print_value_path(def, args)) + self.print_value_path(def, args)?; } DefKind::AnonConst => { if def.is_local() && let span = self.tcx().def_span(def) && let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span) { - p!(write("{}", snip)) + write!(self, "{snip}")?; } else { - // Do not call `print_value_path` as if a parent of this anon const is an impl it will - // attempt to print out the impl trait ref i.e. `::{constant#0}`. This would - // cause printing to enter an infinite recursion if the anon const is in the self type i.e. - // `impl Default for [T; 32 - 1 - 1 - 1] {` - // where we would try to print `<[T; /* print `constant#0` again */] as Default>::{constant#0}` - p!(write( + // Do not call `print_value_path` as if a parent of this anon const is + // an impl it will attempt to print out the impl trait ref i.e. `::{constant#0}`. This would cause printing to enter an + // infinite recursion if the anon const is in the self type i.e. + // `impl Default for [T; 32 - 1 - 1 - 1] {` where we would + // try to print + // `<[T; /* print constant#0 again */] as // Default>::{constant#0}`. + write!( + self, "{}::{}", self.tcx().crate_name(def.krate), self.tcx().def_path(def).to_string_no_crate_verbose() - )) + )?; } } defkind => bug!("`{:?}` has unexpected defkind {:?}", ct, defkind), @@ -1569,11 +1554,11 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } ty::ConstKind::Infer(infer_ct) => match infer_ct { ty::InferConst::Var(ct_vid) if let Some(name) = self.const_infer_name(ct_vid) => { - p!(write("{}", name)) + write!(self, "{name}")?; } _ => write!(self, "_")?, }, - ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)), + ty::ConstKind::Param(ParamConst { name, .. }) => write!(self, "{name}")?, ty::ConstKind::Value(cv) => { return self.pretty_print_const_valtree(cv, print_ty); } @@ -1581,11 +1566,11 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ty::ConstKind::Bound(debruijn, bound_var) => { rustc_type_ir::debug_bound_var(self, debruijn, bound_var)? } - ty::ConstKind::Placeholder(placeholder) => p!(write("{placeholder:?}")), + ty::ConstKind::Placeholder(placeholder) => write!(self, "{placeholder:?}")?, // FIXME(generic_const_exprs): // write out some legible representation of an abstract const? ty::ConstKind::Expr(expr) => self.pretty_print_const_expr(expr, print_ty)?, - ty::ConstKind::Error(_) => p!("{{const error}}"), + ty::ConstKind::Error(_) => write!(self, "{{const error}}")?, }; Ok(()) } @@ -1595,7 +1580,6 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { expr: Expr<'tcx>, print_ty: bool, ) -> Result<(), PrintError> { - define_scoped_cx!(self); match expr.kind { ty::ExprKind::Binop(op) => { let (_, _, c1, c2) = expr.binop_args(); @@ -1634,7 +1618,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { |this| this.pretty_print_const(c1, print_ty), lhs_parenthesized, )?; - p!(write(" {formatted_op} ")); + write!(self, " {formatted_op} ")?; self.maybe_parenthesized( |this| this.pretty_print_const(c2, print_ty), rhs_parenthesized, @@ -1657,7 +1641,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ty::ConstKind::Expr(_) => true, _ => false, }; - p!(write("{formatted_op}")); + write!(self, "{formatted_op}")?; self.maybe_parenthesized( |this| this.pretty_print_const(ct, print_ty), parenthesized, @@ -1668,7 +1652,9 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { write!(self, "(")?; self.pretty_print_const(fn_def, print_ty)?; - p!(")(", comma_sep(fn_args), ")"); + write!(self, ")(")?; + self.comma_sep(fn_args)?; + write!(self, ")")?; } ty::ExprKind::Cast(kind) => { let (_, value, to_ty) = expr.cast_args(); @@ -1718,8 +1704,6 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ptr: Pointer, ty: Ty<'tcx>, ) -> Result<(), PrintError> { - define_scoped_cx!(self); - let (prov, offset) = ptr.prov_and_relative_offset(); match ty.kind() { // Byte strings (&[u8; N]) @@ -1734,19 +1718,19 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { if let Ok(byte_str) = alloc.inner().get_bytes_strip_provenance(&self.tcx(), range) { - p!(pretty_print_byte_str(byte_str)) + self.pretty_print_byte_str(byte_str)?; } else { - p!("") + write!(self, "")?; } } // FIXME: for statics, vtables, and functions, we could in principle print more detail. Some(GlobalAlloc::Static(def_id)) => { - p!(write("", def_id)) + write!(self, "")?; } - Some(GlobalAlloc::Function { .. }) => p!(""), - Some(GlobalAlloc::VTable(..)) => p!(""), - Some(GlobalAlloc::TypeId { .. }) => p!(""), - None => p!(""), + Some(GlobalAlloc::Function { .. }) => write!(self, "")?, + Some(GlobalAlloc::VTable(..)) => write!(self, "")?, + Some(GlobalAlloc::TypeId { .. }) => write!(self, "")?, + None => write!(self, "")?, } return Ok(()); } @@ -1778,40 +1762,38 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ty: Ty<'tcx>, print_ty: bool, ) -> Result<(), PrintError> { - define_scoped_cx!(self); - match ty.kind() { // Bool - ty::Bool if int == ScalarInt::FALSE => p!("false"), - ty::Bool if int == ScalarInt::TRUE => p!("true"), + ty::Bool if int == ScalarInt::FALSE => write!(self, "false")?, + ty::Bool if int == ScalarInt::TRUE => write!(self, "true")?, // Float ty::Float(fty) => match fty { ty::FloatTy::F16 => { let val = Half::try_from(int).unwrap(); - p!(write("{}{}f16", val, if val.is_finite() { "" } else { "_" })) + write!(self, "{}{}f16", val, if val.is_finite() { "" } else { "_" })?; } ty::FloatTy::F32 => { let val = Single::try_from(int).unwrap(); - p!(write("{}{}f32", val, if val.is_finite() { "" } else { "_" })) + write!(self, "{}{}f32", val, if val.is_finite() { "" } else { "_" })?; } ty::FloatTy::F64 => { let val = Double::try_from(int).unwrap(); - p!(write("{}{}f64", val, if val.is_finite() { "" } else { "_" })) + write!(self, "{}{}f64", val, if val.is_finite() { "" } else { "_" })?; } ty::FloatTy::F128 => { let val = Quad::try_from(int).unwrap(); - p!(write("{}{}f128", val, if val.is_finite() { "" } else { "_" })) + write!(self, "{}{}f128", val, if val.is_finite() { "" } else { "_" })?; } }, // Int ty::Uint(_) | ty::Int(_) => { let int = ConstInt::new(int, matches!(ty.kind(), ty::Int(_)), ty.is_ptr_sized_integral()); - if print_ty { p!(write("{:#?}", int)) } else { p!(write("{:?}", int)) } + if print_ty { write!(self, "{int:#?}")? } else { write!(self, "{int:?}")? } } // Char ty::Char if char::try_from(int).is_ok() => { - p!(write("{:?}", char::try_from(int).unwrap())) + write!(self, "{:?}", char::try_from(int).unwrap())?; } // Pointer types ty::Ref(..) | ty::RawPtr(_, _) | ty::FnPtr(..) => { @@ -1827,7 +1809,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } ty::Pat(base_ty, pat) if self.tcx().validate_scalar_in_layout(int, ty) => { self.pretty_print_const_scalar_int(int, *base_ty, print_ty)?; - p!(write(" is {pat:?}")); + write!(self, " is {pat:?}")?; } // Nontrivial types with scalar bit representation _ => { @@ -1876,10 +1858,10 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { cv: ty::Value<'tcx>, print_ty: bool, ) -> Result<(), PrintError> { - define_scoped_cx!(self); - if with_reduced_queries() || self.should_print_verbose() { - p!(write("ValTree({:?}: ", cv.valtree), print(cv.ty), ")"); + write!(self, "ValTree({:?}: ", cv.valtree)?; + cv.ty.print(self)?; + write!(self, ")")?; return Ok(()); } @@ -1900,13 +1882,13 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { let bytes = cv.try_to_raw_bytes(self.tcx()).unwrap_or_else(|| { bug!("expected to convert valtree to raw bytes for type {:?}", cv.ty) }); - p!(write("{:?}", String::from_utf8_lossy(bytes))); + write!(self, "{:?}", String::from_utf8_lossy(bytes))?; return Ok(()); } _ => { let cv = ty::Value { valtree: cv.valtree, ty: inner_ty }; - p!("&"); - p!(pretty_print_const_valtree(cv, print_ty)); + write!(self, "&")?; + self.pretty_print_const_valtree(cv, print_ty)?; return Ok(()); } }, @@ -1914,8 +1896,8 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { let bytes = cv.try_to_raw_bytes(self.tcx()).unwrap_or_else(|| { bug!("expected to convert valtree to raw bytes for type {:?}", t) }); - p!("*"); - p!(pretty_print_byte_str(bytes)); + write!(self, "*")?; + self.pretty_print_byte_str(bytes)?; return Ok(()); } // Aggregates, printed as array/tuple/struct/variant construction syntax. @@ -1928,14 +1910,17 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { let fields = contents.fields.iter().copied(); match *cv.ty.kind() { ty::Array(..) => { - p!("[", comma_sep(fields), "]"); + write!(self, "[")?; + self.comma_sep(fields)?; + write!(self, "]")?; } ty::Tuple(..) => { - p!("(", comma_sep(fields)); + write!(self, "(")?; + self.comma_sep(fields)?; if contents.fields.len() == 1 { - p!(","); + write!(self, ",")?; } - p!(")"); + write!(self, ")")?; } ty::Adt(def, _) if def.variants().is_empty() => { self.typed_value( @@ -1951,23 +1936,26 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { let variant_idx = contents.variant.expect("destructed const of adt without variant idx"); let variant_def = &def.variant(variant_idx); - p!(print_value_path(variant_def.def_id, args)); + self.print_value_path(variant_def.def_id, args)?; match variant_def.ctor_kind() { Some(CtorKind::Const) => {} Some(CtorKind::Fn) => { - p!("(", comma_sep(fields), ")"); + write!(self, "(")?; + self.comma_sep(fields)?; + write!(self, ")")?; } None => { - p!(" {{ "); + write!(self, " {{ ")?; let mut first = true; for (field_def, field) in iter::zip(&variant_def.fields, fields) { if !first { - p!(", "); + write!(self, ", ")?; } - p!(write("{}: ", field_def.name), print(field)); + write!(self, "{}: ", field_def.name)?; + field.print(self)?; first = false; } - p!(" }}"); + write!(self, " }}")?; } } } @@ -1976,7 +1964,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { return Ok(()); } (ty::ValTreeKind::Leaf(leaf), ty::Ref(_, inner_ty, _)) => { - p!(write("&")); + write!(self, "&")?; return self.pretty_print_const_scalar_int(*leaf, inner_ty, print_ty); } (ty::ValTreeKind::Leaf(leaf), _) => { @@ -1984,7 +1972,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } (_, ty::FnDef(def_id, args)) => { // Never allowed today, but we still encounter them in invalid const args. - p!(print_value_path(def_id, args)); + self.print_value_path(def_id, args)?; return Ok(()); } // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading @@ -1994,12 +1982,13 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { // fallback if cv.valtree.is_zst() { - p!(write("")); + write!(self, "")?; } else { - p!(write("{:?}", cv.valtree)); + write!(self, "{:?}", cv.valtree)?; } if print_ty { - p!(": ", print(cv.ty)); + write!(self, ": ")?; + cv.ty.print(self)?; } Ok(()) } @@ -2012,20 +2001,19 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { let kind = closure.kind_ty().to_opt_closure_kind().unwrap_or(ty::ClosureKind::Fn); write!(self, "impl ")?; - self.wrap_binder(&sig, WrapBinderMode::ForAll, |sig, cx| { - define_scoped_cx!(cx); - - p!(write("{kind}(")); + self.wrap_binder(&sig, WrapBinderMode::ForAll, |sig, p| { + write!(p, "{kind}(")?; for (i, arg) in sig.inputs()[0].tuple_fields().iter().enumerate() { if i > 0 { - p!(", "); + write!(p, ", ")?; } - p!(print(arg)); + arg.print(p)?; } - p!(")"); + write!(p, ")")?; if !sig.output().is_unit() { - p!(" -> ", print(sig.output())); + write!(p, " -> ")?; + sig.output().print(p)?; } Ok(()) @@ -2036,15 +2024,9 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { &mut self, constness: ty::BoundConstness, ) -> Result<(), PrintError> { - define_scoped_cx!(self); - match constness { - ty::BoundConstness::Const => { - p!("const "); - } - ty::BoundConstness::Maybe => { - p!("[const] "); - } + ty::BoundConstness::Const => write!(self, "const ")?, + ty::BoundConstness::Maybe => write!(self, "[const] ")?, } Ok(()) } @@ -2061,10 +2043,10 @@ pub(crate) fn pretty_print_const<'tcx>( ) -> fmt::Result { ty::tls::with(|tcx| { let literal = tcx.lift(c).unwrap(); - let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS); - cx.print_alloc_ids = true; - cx.pretty_print_const(literal, print_types)?; - fmt.write_str(&cx.into_buffer())?; + let mut p = FmtPrinter::new(tcx, Namespace::ValueNS); + p.print_alloc_ids = true; + p.pretty_print_const(literal, print_types)?; + fmt.write_str(&p.into_buffer())?; Ok(()) }) } @@ -2184,7 +2166,7 @@ impl<'t> TyCtxt<'t> { let ns = guess_def_namespace(self, def_id); debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns); - FmtPrinter::print_string(self, ns, |cx| cx.print_def_path(def_id, args)).unwrap() + FmtPrinter::print_string(self, ns, |p| p.print_def_path(def_id, args)).unwrap() } pub fn value_path_str_with_args( @@ -2196,7 +2178,7 @@ impl<'t> TyCtxt<'t> { let ns = guess_def_namespace(self, def_id); debug!("value_path_str: def_id={:?}, ns={:?}", def_id, ns); - FmtPrinter::print_string(self, ns, |cx| cx.print_value_path(def_id, args)).unwrap() + FmtPrinter::print_string(self, ns, |p| p.print_value_path(def_id, args)).unwrap() } } @@ -2358,15 +2340,14 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> { fn path_append_impl( &mut self, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, - _disambiguated_data: &DisambiguatedDefPathData, self_ty: Ty<'tcx>, trait_ref: Option>, ) -> Result<(), PrintError> { self.pretty_path_append_impl( - |cx| { - print_prefix(cx)?; - if !cx.empty_path { - write!(cx, "::")?; + |p| { + print_prefix(p)?; + if !p.empty_path { + write!(p, "::")?; } Ok(()) @@ -2420,7 +2401,7 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> { if self.in_value { write!(self, "::")?; } - self.generic_delimiters(|cx| cx.comma_sep(args.iter().copied())) + self.generic_delimiters(|p| p.comma_sep(args.iter().copied())) } else { Ok(()) } @@ -2456,7 +2437,7 @@ impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> { where T: Print<'tcx, Self> + TypeFoldable>, { - self.pretty_print_in_binder(value) + self.wrap_binder(value, WrapBinderMode::ForAll, |new_value, this| new_value.print(this)) } fn wrap_binder Result<(), PrintError>>( @@ -2468,7 +2449,12 @@ impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> { where T: TypeFoldable>, { - self.pretty_wrap_binder(value, mode, f) + let old_region_index = self.region_index; + let (new_value, _) = self.name_all_regions(value, mode)?; + f(&new_value, self)?; + self.region_index = old_region_index; + self.binder_depth -= 1; + Ok(()) } fn typed_value( @@ -2552,11 +2538,10 @@ impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> { ty: Ty<'tcx>, ) -> Result<(), PrintError> { let print = |this: &mut Self| { - define_scoped_cx!(this); if this.print_alloc_ids { - p!(write("{:?}", p)); + write!(this, "{p:?}")?; } else { - p!("&_"); + write!(this, "&_")?; } Ok(()) }; @@ -2567,17 +2552,15 @@ impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> { // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`. impl<'tcx> FmtPrinter<'_, 'tcx> { pub fn pretty_print_region(&mut self, region: ty::Region<'tcx>) -> Result<(), fmt::Error> { - define_scoped_cx!(self); - // Watch out for region highlights. let highlight = self.region_highlight_mode; if let Some(n) = highlight.region_highlighted(region) { - p!(write("'{}", n)); + write!(self, "'{n}")?; return Ok(()); } if self.should_print_verbose() { - p!(write("{:?}", region)); + write!(self, "{region:?}")?; return Ok(()); } @@ -2589,12 +2572,12 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { // `explain_region()` or `note_and_explain_region()`. match region.kind() { ty::ReEarlyParam(data) => { - p!(write("{}", data.name)); + write!(self, "{}", data.name)?; return Ok(()); } ty::ReLateParam(ty::LateParamRegion { kind, .. }) => { if let Some(name) = kind.get_name(self.tcx) { - p!(write("{}", name)); + write!(self, "{name}")?; return Ok(()); } } @@ -2603,31 +2586,31 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { bound: ty::BoundRegion { kind: br, .. }, .. }) => { if let Some(name) = br.get_name(self.tcx) { - p!(write("{}", name)); + write!(self, "{name}")?; return Ok(()); } if let Some((region, counter)) = highlight.highlight_bound_region { if br == region { - p!(write("'{}", counter)); + write!(self, "'{counter}")?; return Ok(()); } } } ty::ReVar(region_vid) if identify_regions => { - p!(write("{:?}", region_vid)); + write!(self, "{region_vid:?}")?; return Ok(()); } ty::ReVar(_) => {} ty::ReErased => {} ty::ReError(_) => {} ty::ReStatic => { - p!("'static"); + write!(self, "'static")?; return Ok(()); } } - p!("'_"); + write!(self, "'_")?; Ok(()) } @@ -2745,17 +2728,17 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { debug!("self.used_region_names: {:?}", self.used_region_names); let mut empty = true; - let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| { + let mut start_or_continue = |p: &mut Self, start: &str, cont: &str| { let w = if empty { empty = false; start } else { cont }; - let _ = write!(cx, "{w}"); + let _ = write!(p, "{w}"); }; - let do_continue = |cx: &mut Self, cont: Symbol| { - let _ = write!(cx, "{cont}"); + let do_continue = |p: &mut Self, cont: Symbol| { + let _ = write!(p, "{cont}"); }; let possible_names = ('a'..='z').rev().map(|s| Symbol::intern(&format!("'{s}"))); @@ -2855,38 +2838,6 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { Ok((new_value, map)) } - pub fn pretty_print_in_binder( - &mut self, - value: &ty::Binder<'tcx, T>, - ) -> Result<(), fmt::Error> - where - T: Print<'tcx, Self> + TypeFoldable>, - { - let old_region_index = self.region_index; - let (new_value, _) = self.name_all_regions(value, WrapBinderMode::ForAll)?; - new_value.print(self)?; - self.region_index = old_region_index; - self.binder_depth -= 1; - Ok(()) - } - - pub fn pretty_wrap_binder Result<(), fmt::Error>>( - &mut self, - value: &ty::Binder<'tcx, T>, - mode: WrapBinderMode, - f: C, - ) -> Result<(), fmt::Error> - where - T: TypeFoldable>, - { - let old_region_index = self.region_index; - let (new_value, _) = self.name_all_regions(value, mode)?; - f(&new_value, self)?; - self.region_index = old_region_index; - self.binder_depth -= 1; - Ok(()) - } - fn prepare_region_info(&mut self, value: &ty::Binder<'tcx, T>) where T: TypeFoldable>, @@ -2940,8 +2891,8 @@ impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<'tcx, T> where T: Print<'tcx, P> + TypeFoldable>, { - fn print(&self, cx: &mut P) -> Result<(), PrintError> { - cx.print_in_binder(self) + fn print(&self, p: &mut P) -> Result<(), PrintError> { + p.print_in_binder(self) } } @@ -2949,9 +2900,10 @@ impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<' where T: Print<'tcx, P>, { - fn print(&self, cx: &mut P) -> Result<(), PrintError> { - define_scoped_cx!(cx); - p!(print(self.0), ": ", print(self.1)); + fn print(&self, p: &mut P) -> Result<(), PrintError> { + self.0.print(p)?; + write!(p, ": ")?; + self.1.print(p)?; Ok(()) } } @@ -3090,11 +3042,11 @@ macro_rules! forward_display_to_print { $(#[allow(unused_lifetimes)] impl<'tcx> fmt::Display for $ty { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ty::tls::with(|tcx| { - let mut cx = FmtPrinter::new(tcx, Namespace::TypeNS); + let mut p = FmtPrinter::new(tcx, Namespace::TypeNS); tcx.lift(*self) .expect("could not lift for printing") - .print(&mut cx)?; - f.write_str(&cx.into_buffer())?; + .print(&mut p)?; + f.write_str(&p.into_buffer())?; Ok(()) }) } @@ -3103,10 +3055,9 @@ macro_rules! forward_display_to_print { } macro_rules! define_print { - (($self:ident, $cx:ident): $($ty:ty $print:block)+) => { + (($self:ident, $p:ident): $($ty:ty $print:block)+) => { $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty { - fn print(&$self, $cx: &mut P) -> Result<(), PrintError> { - define_scoped_cx!($cx); + fn print(&$self, $p: &mut P) -> Result<(), PrintError> { let _: () = $print; Ok(()) } @@ -3115,8 +3066,8 @@ macro_rules! define_print { } macro_rules! define_print_and_forward_display { - (($self:ident, $cx:ident): $($ty:ty $print:block)+) => { - define_print!(($self, $cx): $($ty $print)*); + (($self:ident, $p:ident): $($ty:ty $print:block)+) => { + define_print!(($self, $p): $($ty $print)*); forward_display_to_print!($($ty),+); }; } @@ -3129,37 +3080,38 @@ forward_display_to_print! { } define_print! { - (self, cx): + (self, p): ty::FnSig<'tcx> { - p!(write("{}", self.safety.prefix_str())); + write!(p, "{}", self.safety.prefix_str())?; if self.abi != ExternAbi::Rust { - p!(write("extern {} ", self.abi)); + write!(p, "extern {} ", self.abi)?; } - p!("fn", pretty_fn_sig(self.inputs(), self.c_variadic, self.output())); + write!(p, "fn")?; + p.pretty_fn_sig(self.inputs(), self.c_variadic, self.output())?; } ty::TraitRef<'tcx> { - p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path())) + write!(p, "<{} as {}>", self.self_ty(), self.print_only_trait_path())?; } ty::AliasTy<'tcx> { let alias_term: ty::AliasTerm<'tcx> = (*self).into(); - p!(print(alias_term)) + alias_term.print(p)?; } ty::AliasTerm<'tcx> { - match self.kind(cx.tcx()) { - ty::AliasTermKind::InherentTy | ty::AliasTermKind::InherentConst => p!(pretty_print_inherent_projection(*self)), + match self.kind(p.tcx()) { + ty::AliasTermKind::InherentTy | ty::AliasTermKind::InherentConst => p.pretty_print_inherent_projection(*self)?, ty::AliasTermKind::ProjectionTy => { - if !(cx.should_print_verbose() || with_reduced_queries()) - && cx.tcx().is_impl_trait_in_trait(self.def_id) + if !(p.should_print_verbose() || with_reduced_queries()) + && p.tcx().is_impl_trait_in_trait(self.def_id) { - p!(pretty_print_rpitit(self.def_id, self.args)) + p.pretty_print_rpitit(self.def_id, self.args)?; } else { - p!(print_def_path(self.def_id, self.args)); + p.print_def_path(self.def_id, self.args)?; } } ty::AliasTermKind::FreeTy @@ -3167,17 +3119,18 @@ define_print! { | ty::AliasTermKind::OpaqueTy | ty::AliasTermKind::UnevaluatedConst | ty::AliasTermKind::ProjectionConst => { - p!(print_def_path(self.def_id, self.args)); + p.print_def_path(self.def_id, self.args)?; } } } ty::TraitPredicate<'tcx> { - p!(print(self.trait_ref.self_ty()), ": "); + self.trait_ref.self_ty().print(p)?; + write!(p, ": ")?; if let ty::PredicatePolarity::Negative = self.polarity { - p!("!"); + write!(p, "!")?; } - p!(print(self.trait_ref.print_trait_sugared())) + self.trait_ref.print_trait_sugared().print(p)?; } ty::HostEffectPredicate<'tcx> { @@ -3185,196 +3138,223 @@ define_print! { ty::BoundConstness::Const => { "const" } ty::BoundConstness::Maybe => { "[const]" } }; - p!(print(self.trait_ref.self_ty()), ": {constness} "); - p!(print(self.trait_ref.print_trait_sugared())) + self.trait_ref.self_ty().print(p)?; + write!(p, ": {constness} ")?; + self.trait_ref.print_trait_sugared().print(p)?; } ty::TypeAndMut<'tcx> { - p!(write("{}", self.mutbl.prefix_str()), print(self.ty)) + write!(p, "{}", self.mutbl.prefix_str())?; + self.ty.print(p)?; } ty::ClauseKind<'tcx> { match *self { - ty::ClauseKind::Trait(ref data) => { - p!(print(data)) - } - ty::ClauseKind::RegionOutlives(predicate) => p!(print(predicate)), - ty::ClauseKind::TypeOutlives(predicate) => p!(print(predicate)), - ty::ClauseKind::Projection(predicate) => p!(print(predicate)), - ty::ClauseKind::HostEffect(predicate) => p!(print(predicate)), + ty::ClauseKind::Trait(ref data) => data.print(p)?, + ty::ClauseKind::RegionOutlives(predicate) => predicate.print(p)?, + ty::ClauseKind::TypeOutlives(predicate) => predicate.print(p)?, + ty::ClauseKind::Projection(predicate) => predicate.print(p)?, + ty::ClauseKind::HostEffect(predicate) => predicate.print(p)?, ty::ClauseKind::ConstArgHasType(ct, ty) => { - p!("the constant `", print(ct), "` has type `", print(ty), "`") + write!(p, "the constant `")?; + ct.print(p)?; + write!(p, "` has type `")?; + ty.print(p)?; + write!(p, "`")?; }, - ty::ClauseKind::WellFormed(term) => p!(print(term), " well-formed"), + ty::ClauseKind::WellFormed(term) => { + term.print(p)?; + write!(p, " well-formed")?; + } ty::ClauseKind::ConstEvaluatable(ct) => { - p!("the constant `", print(ct), "` can be evaluated") + write!(p, "the constant `")?; + ct.print(p)?; + write!(p, "` can be evaluated")?; + } + ty::ClauseKind::UnstableFeature(symbol) => { + write!(p, "unstable feature: ")?; + write!(p, "`{symbol}`")?; } - ty::ClauseKind::UnstableFeature(symbol) => p!("unstable feature: ", write("`{}`", symbol)), } } ty::PredicateKind<'tcx> { match *self { - ty::PredicateKind::Clause(data) => { - p!(print(data)) - } - ty::PredicateKind::Subtype(predicate) => p!(print(predicate)), - ty::PredicateKind::Coerce(predicate) => p!(print(predicate)), + ty::PredicateKind::Clause(data) => data.print(p)?, + ty::PredicateKind::Subtype(predicate) => predicate.print(p)?, + ty::PredicateKind::Coerce(predicate) => predicate.print(p)?, ty::PredicateKind::DynCompatible(trait_def_id) => { - p!("the trait `", print_def_path(trait_def_id, &[]), "` is dyn-compatible") + write!(p, "the trait `")?; + p.print_def_path(trait_def_id, &[])?; + write!(p, "` is dyn-compatible")?; } ty::PredicateKind::ConstEquate(c1, c2) => { - p!("the constant `", print(c1), "` equals `", print(c2), "`") + write!(p, "the constant `")?; + c1.print(p)?; + write!(p, "` equals `")?; + c2.print(p)?; + write!(p, "`")?; + } + ty::PredicateKind::Ambiguous => write!(p, "ambiguous")?, + ty::PredicateKind::NormalizesTo(data) => data.print(p)?, + ty::PredicateKind::AliasRelate(t1, t2, dir) => { + t1.print(p)?; + write!(p, " {dir} ")?; + t2.print(p)?; } - ty::PredicateKind::Ambiguous => p!("ambiguous"), - ty::PredicateKind::NormalizesTo(data) => p!(print(data)), - ty::PredicateKind::AliasRelate(t1, t2, dir) => p!(print(t1), write(" {} ", dir), print(t2)), } } ty::ExistentialPredicate<'tcx> { match *self { - ty::ExistentialPredicate::Trait(x) => p!(print(x)), - ty::ExistentialPredicate::Projection(x) => p!(print(x)), - ty::ExistentialPredicate::AutoTrait(def_id) => { - p!(print_def_path(def_id, &[])); - } + ty::ExistentialPredicate::Trait(x) => x.print(p)?, + ty::ExistentialPredicate::Projection(x) => x.print(p)?, + ty::ExistentialPredicate::AutoTrait(def_id) => p.print_def_path(def_id, &[])?, } } ty::ExistentialTraitRef<'tcx> { // Use a type that can't appear in defaults of type parameters. - let dummy_self = Ty::new_fresh(cx.tcx(), 0); - let trait_ref = self.with_self_ty(cx.tcx(), dummy_self); - p!(print(trait_ref.print_only_trait_path())) + let dummy_self = Ty::new_fresh(p.tcx(), 0); + let trait_ref = self.with_self_ty(p.tcx(), dummy_self); + trait_ref.print_only_trait_path().print(p)?; } ty::ExistentialProjection<'tcx> { - let name = cx.tcx().associated_item(self.def_id).name(); + let name = p.tcx().associated_item(self.def_id).name(); // The args don't contain the self ty (as it has been erased) but the corresp. // generics do as the trait always has a self ty param. We need to offset. - let args = &self.args[cx.tcx().generics_of(self.def_id).parent_count - 1..]; - p!(path_generic_args(|cx| write!(cx, "{name}"), args), " = ", print(self.term)) + let args = &self.args[p.tcx().generics_of(self.def_id).parent_count - 1..]; + p.path_generic_args(|p| write!(p, "{name}"), args)?; + write!(p, " = ")?; + self.term.print(p)?; } ty::ProjectionPredicate<'tcx> { - p!(print(self.projection_term), " == "); - cx.reset_type_limit(); - p!(print(self.term)) + self.projection_term.print(p)?; + write!(p, " == ")?; + p.reset_type_limit(); + self.term.print(p)?; } ty::SubtypePredicate<'tcx> { - p!(print(self.a), " <: "); - cx.reset_type_limit(); - p!(print(self.b)) + self.a.print(p)?; + write!(p, " <: ")?; + p.reset_type_limit(); + self.b.print(p)?; } ty::CoercePredicate<'tcx> { - p!(print(self.a), " -> "); - cx.reset_type_limit(); - p!(print(self.b)) + self.a.print(p)?; + write!(p, " -> ")?; + p.reset_type_limit(); + self.b.print(p)?; } ty::NormalizesTo<'tcx> { - p!(print(self.alias), " normalizes-to "); - cx.reset_type_limit(); - p!(print(self.term)) + self.alias.print(p)?; + write!(p, " normalizes-to ")?; + p.reset_type_limit(); + self.term.print(p)?; } } define_print_and_forward_display! { - (self, cx): + (self, p): &'tcx ty::List> { - p!("{{", comma_sep(self.iter()), "}}") + write!(p, "{{")?; + p.comma_sep(self.iter())?; + write!(p, "}}")?; } TraitRefPrintOnlyTraitPath<'tcx> { - p!(print_def_path(self.0.def_id, self.0.args)); + p.print_def_path(self.0.def_id, self.0.args)?; } TraitRefPrintSugared<'tcx> { if !with_reduced_queries() - && cx.tcx().trait_def(self.0.def_id).paren_sugar + && p.tcx().trait_def(self.0.def_id).paren_sugar && let ty::Tuple(args) = self.0.args.type_at(1).kind() { - p!(write("{}", cx.tcx().item_name(self.0.def_id)), "("); + write!(p, "{}(", p.tcx().item_name(self.0.def_id))?; for (i, arg) in args.iter().enumerate() { if i > 0 { - p!(", "); + write!(p, ", ")?; } - p!(print(arg)); + arg.print(p)?; } - p!(")"); + write!(p, ")")?; } else { - p!(print_def_path(self.0.def_id, self.0.args)); + p.print_def_path(self.0.def_id, self.0.args)?; } } TraitRefPrintOnlyTraitName<'tcx> { - p!(print_def_path(self.0.def_id, &[])); + p.print_def_path(self.0.def_id, &[])?; } TraitPredPrintModifiersAndPath<'tcx> { if let ty::PredicatePolarity::Negative = self.0.polarity { - p!("!") + write!(p, "!")?; } - p!(print(self.0.trait_ref.print_trait_sugared())); + self.0.trait_ref.print_trait_sugared().print(p)?; } TraitPredPrintWithBoundConstness<'tcx> { - p!(print(self.0.trait_ref.self_ty()), ": "); + self.0.trait_ref.self_ty().print(p)?; + write!(p, ": ")?; if let Some(constness) = self.1 { - p!(pretty_print_bound_constness(constness)); + p.pretty_print_bound_constness(constness)?; } if let ty::PredicatePolarity::Negative = self.0.polarity { - p!("!"); + write!(p, "!")?; } - p!(print(self.0.trait_ref.print_trait_sugared())) + self.0.trait_ref.print_trait_sugared().print(p)?; } PrintClosureAsImpl<'tcx> { - p!(pretty_closure_as_impl(self.closure)) + p.pretty_closure_as_impl(self.closure)?; } ty::ParamTy { - p!(write("{}", self.name)) + write!(p, "{}", self.name)?; } ty::PlaceholderType { match self.bound.kind { - ty::BoundTyKind::Anon => p!(write("{self:?}")), - ty::BoundTyKind::Param(def_id) => match cx.should_print_verbose() { - true => p!(write("{self:?}")), - false => p!(write("{}", cx.tcx().item_name(def_id))), + ty::BoundTyKind::Anon => write!(p, "{self:?}")?, + ty::BoundTyKind::Param(def_id) => match p.should_print_verbose() { + true => write!(p, "{self:?}")?, + false => write!(p, "{}", p.tcx().item_name(def_id))?, }, } } ty::ParamConst { - p!(write("{}", self.name)) + write!(p, "{}", self.name)?; } ty::Term<'tcx> { match self.kind() { - ty::TermKind::Ty(ty) => p!(print(ty)), - ty::TermKind::Const(c) => p!(print(c)), + ty::TermKind::Ty(ty) => ty.print(p)?, + ty::TermKind::Const(c) => c.print(p)?, } } ty::Predicate<'tcx> { - p!(print(self.kind())) + self.kind().print(p)?; } ty::Clause<'tcx> { - p!(print(self.kind())) + self.kind().print(p)?; } GenericArg<'tcx> { match self.kind() { - GenericArgKind::Lifetime(lt) => p!(print(lt)), - GenericArgKind::Type(ty) => p!(print(ty)), - GenericArgKind::Const(ct) => p!(print(ct)), + GenericArgKind::Lifetime(lt) => lt.print(p)?, + GenericArgKind::Type(ty) => ty.print(p)?, + GenericArgKind::Const(ct) => ct.print(p)?, } } } diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 10e499d9c758c..0e2aff6f9bdac 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -25,8 +25,8 @@ impl fmt::Debug for ty::TraitDef { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ty::tls::with(|tcx| { with_no_trimmed_paths!({ - let s = FmtPrinter::print_string(tcx, Namespace::TypeNS, |cx| { - cx.print_def_path(self.def_id, &[]) + let s = FmtPrinter::print_string(tcx, Namespace::TypeNS, |p| { + p.print_def_path(self.def_id, &[]) })?; f.write_str(&s) }) @@ -38,8 +38,8 @@ impl<'tcx> fmt::Debug for ty::AdtDef<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ty::tls::with(|tcx| { with_no_trimmed_paths!({ - let s = FmtPrinter::print_string(tcx, Namespace::TypeNS, |cx| { - cx.print_def_path(self.did(), &[]) + let s = FmtPrinter::print_string(tcx, Namespace::TypeNS, |p| { + p.print_def_path(self.did(), &[]) })?; f.write_str(&s) }) @@ -170,9 +170,9 @@ impl<'tcx> fmt::Debug for ty::Const<'tcx> { if let ConstKind::Value(cv) = self.kind() { return ty::tls::with(move |tcx| { let cv = tcx.lift(cv).unwrap(); - let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS); - cx.pretty_print_const_valtree(cv, /*print_ty*/ true)?; - f.write_str(&cx.into_buffer()) + let mut p = FmtPrinter::new(tcx, Namespace::ValueNS); + p.pretty_print_const_valtree(cv, /*print_ty*/ true)?; + f.write_str(&p.into_buffer()) }); } // Fall back to something verbose. diff --git a/compiler/rustc_symbol_mangling/src/legacy.rs b/compiler/rustc_symbol_mangling/src/legacy.rs index 12d1de463136a..aa8292c050440 100644 --- a/compiler/rustc_symbol_mangling/src/legacy.rs +++ b/compiler/rustc_symbol_mangling/src/legacy.rs @@ -58,59 +58,57 @@ pub(super) fn mangle<'tcx>( let hash = get_symbol_hash(tcx, instance, instance_ty, instantiating_crate); - let mut printer = SymbolPrinter { tcx, path: SymbolPath::new(), keep_within_component: false }; - printer - .print_def_path( - def_id, - if let ty::InstanceKind::DropGlue(_, _) - | ty::InstanceKind::AsyncDropGlueCtorShim(_, _) - | ty::InstanceKind::FutureDropPollShim(_, _, _) = instance.def - { - // Add the name of the dropped type to the symbol name - &*instance.args - } else if let ty::InstanceKind::AsyncDropGlue(_, ty) = instance.def { - let ty::Coroutine(_, cor_args) = ty.kind() else { - bug!(); - }; - let drop_ty = cor_args.first().unwrap().expect_ty(); - tcx.mk_args(&[GenericArg::from(drop_ty)]) - } else { - &[] - }, - ) - .unwrap(); + let mut p = SymbolPrinter { tcx, path: SymbolPath::new(), keep_within_component: false }; + p.print_def_path( + def_id, + if let ty::InstanceKind::DropGlue(_, _) + | ty::InstanceKind::AsyncDropGlueCtorShim(_, _) + | ty::InstanceKind::FutureDropPollShim(_, _, _) = instance.def + { + // Add the name of the dropped type to the symbol name + &*instance.args + } else if let ty::InstanceKind::AsyncDropGlue(_, ty) = instance.def { + let ty::Coroutine(_, cor_args) = ty.kind() else { + bug!(); + }; + let drop_ty = cor_args.first().unwrap().expect_ty(); + tcx.mk_args(&[GenericArg::from(drop_ty)]) + } else { + &[] + }, + ) + .unwrap(); match instance.def { ty::InstanceKind::ThreadLocalShim(..) => { - printer.write_str("{{tls-shim}}").unwrap(); + p.write_str("{{tls-shim}}").unwrap(); } ty::InstanceKind::VTableShim(..) => { - printer.write_str("{{vtable-shim}}").unwrap(); + p.write_str("{{vtable-shim}}").unwrap(); } ty::InstanceKind::ReifyShim(_, reason) => { - printer.write_str("{{reify-shim").unwrap(); + p.write_str("{{reify-shim").unwrap(); match reason { - Some(ReifyReason::FnPtr) => printer.write_str("-fnptr").unwrap(), - Some(ReifyReason::Vtable) => printer.write_str("-vtable").unwrap(), + Some(ReifyReason::FnPtr) => p.write_str("-fnptr").unwrap(), + Some(ReifyReason::Vtable) => p.write_str("-vtable").unwrap(), None => (), } - printer.write_str("}}").unwrap(); + p.write_str("}}").unwrap(); } // FIXME(async_closures): This shouldn't be needed when we fix // `Instance::ty`/`Instance::def_id`. ty::InstanceKind::ConstructCoroutineInClosureShim { receiver_by_ref, .. } => { - printer - .write_str(if receiver_by_ref { "{{by-move-shim}}" } else { "{{by-ref-shim}}" }) + p.write_str(if receiver_by_ref { "{{by-move-shim}}" } else { "{{by-ref-shim}}" }) .unwrap(); } _ => {} } if let ty::InstanceKind::FutureDropPollShim(..) = instance.def { - let _ = printer.write_str("{{drop-shim}}"); + let _ = p.write_str("{{drop-shim}}"); } - printer.path.finish(hash) + p.path.finish(hash) } fn get_symbol_hash<'tcx>( @@ -236,7 +234,7 @@ impl<'tcx> Printer<'tcx> for SymbolPrinter<'tcx> { } fn print_region(&mut self, _region: ty::Region<'_>) -> Result<(), PrintError> { - Ok(()) + unreachable!(); // because `::should_print_region` returns false } fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> { @@ -334,7 +332,6 @@ impl<'tcx> Printer<'tcx> for SymbolPrinter<'tcx> { fn path_append_impl( &mut self, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, - _disambiguated_data: &DisambiguatedDefPathData, self_ty: Ty<'tcx>, trait_ref: Option>, ) -> Result<(), PrintError> { @@ -460,6 +457,8 @@ impl<'tcx> PrettyPrinter<'tcx> for SymbolPrinter<'tcx> { fn should_print_region(&self, _region: ty::Region<'_>) -> bool { false } + + // Identical to `PrettyPrinter::comma_sep` except there is no space after each comma. fn comma_sep(&mut self, mut elems: impl Iterator) -> Result<(), PrintError> where T: Print<'tcx, Self>, diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index fe0f8e6113ef7..c2458ae814b71 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -33,7 +33,7 @@ pub(super) fn mangle<'tcx>( let args = tcx.normalize_erasing_regions(ty::TypingEnv::fully_monomorphized(), instance.args); let prefix = "_R"; - let mut cx: SymbolMangler<'_> = SymbolMangler { + let mut p: SymbolMangler<'_> = SymbolMangler { tcx, start_offset: prefix.len(), is_exportable, @@ -69,16 +69,16 @@ pub(super) fn mangle<'tcx>( bug!(); }; let drop_ty = cor_args.first().unwrap().expect_ty(); - cx.print_def_path(def_id, tcx.mk_args(&[GenericArg::from(drop_ty)])).unwrap() + p.print_def_path(def_id, tcx.mk_args(&[GenericArg::from(drop_ty)])).unwrap() } else if let Some(shim_kind) = shim_kind { - cx.path_append_ns(|cx| cx.print_def_path(def_id, args), 'S', 0, shim_kind).unwrap() + p.path_append_ns(|p| p.print_def_path(def_id, args), 'S', 0, shim_kind).unwrap() } else { - cx.print_def_path(def_id, args).unwrap() + p.print_def_path(def_id, args).unwrap() }; if let Some(instantiating_crate) = instantiating_crate { - cx.print_def_path(instantiating_crate.as_def_id(), &[]).unwrap(); + p.print_def_path(instantiating_crate.as_def_id(), &[]).unwrap(); } - std::mem::take(&mut cx.out) + std::mem::take(&mut p.out) } pub fn mangle_internal_symbol<'tcx>(tcx: TyCtxt<'tcx>, item_name: &str) -> String { @@ -88,7 +88,7 @@ pub fn mangle_internal_symbol<'tcx>(tcx: TyCtxt<'tcx>, item_name: &str) -> Strin } let prefix = "_R"; - let mut cx: SymbolMangler<'_> = SymbolMangler { + let mut p: SymbolMangler<'_> = SymbolMangler { tcx, start_offset: prefix.len(), is_exportable: false, @@ -99,10 +99,10 @@ pub fn mangle_internal_symbol<'tcx>(tcx: TyCtxt<'tcx>, item_name: &str) -> Strin out: String::from(prefix), }; - cx.path_append_ns( - |cx| { - cx.push("C"); - cx.push_disambiguator({ + p.path_append_ns( + |p| { + p.push("C"); + p.push_disambiguator({ let mut hasher = StableHasher::new(); // Incorporate the rustc version to ensure #[rustc_std_internal_symbol] functions // get a different symbol name depending on the rustc version. @@ -114,7 +114,7 @@ pub fn mangle_internal_symbol<'tcx>(tcx: TyCtxt<'tcx>, item_name: &str) -> Strin let hash: Hash64 = hasher.finish(); hash.as_u64() }); - cx.push_ident("__rustc"); + p.push_ident("__rustc"); Ok(()) }, 'v', @@ -123,7 +123,7 @@ pub fn mangle_internal_symbol<'tcx>(tcx: TyCtxt<'tcx>, item_name: &str) -> Strin ) .unwrap(); - std::mem::take(&mut cx.out) + std::mem::take(&mut p.out) } pub(super) fn mangle_typeid_for_trait_ref<'tcx>( @@ -131,7 +131,7 @@ pub(super) fn mangle_typeid_for_trait_ref<'tcx>( trait_ref: ty::ExistentialTraitRef<'tcx>, ) -> String { // FIXME(flip1995): See comment in `mangle_typeid_for_fnabi`. - let mut cx = SymbolMangler { + let mut p = SymbolMangler { tcx, start_offset: 0, is_exportable: false, @@ -141,8 +141,8 @@ pub(super) fn mangle_typeid_for_trait_ref<'tcx>( binders: vec![], out: String::new(), }; - cx.print_def_path(trait_ref.def_id, &[]).unwrap(); - std::mem::take(&mut cx.out) + p.print_def_path(trait_ref.def_id, &[]).unwrap(); + std::mem::take(&mut p.out) } struct BinderLevel { @@ -368,7 +368,7 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> { self.path_generic_args( |this| { this.path_append_ns( - |cx| cx.print_def_path(parent_def_id, &[]), + |p| p.print_def_path(parent_def_id, &[]), 'I', key.disambiguated_data.disambiguator as u64, "", @@ -425,7 +425,6 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> { ty::Bool => "b", ty::Char => "c", ty::Str => "e", - ty::Tuple(_) if ty.is_unit() => "u", ty::Int(IntTy::I8) => "a", ty::Int(IntTy::I16) => "s", ty::Int(IntTy::I32) => "l", @@ -444,12 +443,12 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> { ty::Float(FloatTy::F128) => "C4f128", ty::Never => "z", + ty::Tuple(_) if ty.is_unit() => "u", + // Should only be encountered within the identity-substituted // impl header of an item nested within an impl item. ty::Param(_) => "p", - ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => bug!(), - _ => "", }; if !basic_type.is_empty() { @@ -468,11 +467,9 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> { unreachable!() } ty::Tuple(_) if ty.is_unit() => unreachable!(), + ty::Param(_) => unreachable!(), - // Placeholders, also handled as part of basic types. - ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => { - unreachable!() - } + ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => bug!(), ty::Ref(r, ty, mutbl) => { self.push(match mutbl { @@ -542,31 +539,31 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> { ty::FnPtr(sig_tys, hdr) => { let sig = sig_tys.with(hdr); self.push("F"); - self.wrap_binder(&sig, |cx, sig| { + self.wrap_binder(&sig, |p, sig| { if sig.safety.is_unsafe() { - cx.push("U"); + p.push("U"); } match sig.abi { ExternAbi::Rust => {} - ExternAbi::C { unwind: false } => cx.push("KC"), + ExternAbi::C { unwind: false } => p.push("KC"), abi => { - cx.push("K"); + p.push("K"); let name = abi.as_str(); if name.contains('-') { - cx.push_ident(&name.replace('-', "_")); + p.push_ident(&name.replace('-', "_")); } else { - cx.push_ident(name); + p.push_ident(name); } } } for &ty in sig.inputs() { - ty.print(cx)?; + ty.print(p)?; } if sig.c_variadic { - cx.push("v"); + p.push("v"); } - cx.push("E"); - sig.output().print(cx) + p.push("E"); + sig.output().print(p) })?; } @@ -623,7 +620,7 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> { // [ [{}]] [{}] // Since any predicates after the first one shouldn't change the binders, // just put them all in the binders of the first. - self.wrap_binder(&predicates[0], |cx, _| { + self.wrap_binder(&predicates[0], |p, _| { for predicate in predicates.iter() { // It would be nice to be able to validate bound vars here, but // projections can actually include bound vars from super traits @@ -632,21 +629,21 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> { match predicate.as_ref().skip_binder() { ty::ExistentialPredicate::Trait(trait_ref) => { // Use a type that can't appear in defaults of type parameters. - let dummy_self = Ty::new_fresh(cx.tcx, 0); - let trait_ref = trait_ref.with_self_ty(cx.tcx, dummy_self); - cx.print_def_path(trait_ref.def_id, trait_ref.args)?; + let dummy_self = Ty::new_fresh(p.tcx, 0); + let trait_ref = trait_ref.with_self_ty(p.tcx, dummy_self); + p.print_def_path(trait_ref.def_id, trait_ref.args)?; } ty::ExistentialPredicate::Projection(projection) => { - let name = cx.tcx.associated_item(projection.def_id).name(); - cx.push("p"); - cx.push_ident(name.as_str()); + let name = p.tcx.associated_item(projection.def_id).name(); + p.push("p"); + p.push_ident(name.as_str()); match projection.term.kind() { - ty::TermKind::Ty(ty) => ty.print(cx), - ty::TermKind::Const(c) => c.print(cx), + ty::TermKind::Ty(ty) => ty.print(p), + ty::TermKind::Const(c) => c.print(p), }?; } ty::ExistentialPredicate::AutoTrait(def_id) => { - cx.print_def_path(*def_id, &[])?; + p.print_def_path(*def_id, &[])?; } } } @@ -849,7 +846,6 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> { fn path_append_impl( &mut self, _: impl FnOnce(&mut Self) -> Result<(), PrintError>, - _: &DisambiguatedDefPathData, _: Ty<'tcx>, _: Option>, ) -> Result<(), PrintError> { diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs index b9acadc406e9c..ed8229154a9bf 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs @@ -235,28 +235,29 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } fn print_region(&mut self, _region: ty::Region<'_>) -> Result<(), PrintError> { - Err(fmt::Error) + unreachable!(); // because `path_generic_args` ignores the `GenericArgs` } fn print_type(&mut self, _ty: Ty<'tcx>) -> Result<(), PrintError> { - Err(fmt::Error) + unreachable!(); // because `path_generic_args` ignores the `GenericArgs` } fn print_dyn_existential( &mut self, _predicates: &'tcx ty::List>, ) -> Result<(), PrintError> { - Err(fmt::Error) + unreachable!(); // because `path_generic_args` ignores the `GenericArgs` } fn print_const(&mut self, _ct: ty::Const<'tcx>) -> Result<(), PrintError> { - Err(fmt::Error) + unreachable!(); // because `path_generic_args` ignores the `GenericArgs` } fn path_crate(&mut self, cnum: CrateNum) -> Result<(), PrintError> { self.segments = vec![self.tcx.crate_name(cnum)]; Ok(()) } + fn path_qualified( &mut self, _self_ty: Ty<'tcx>, @@ -268,12 +269,12 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { fn path_append_impl( &mut self, _print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, - _disambiguated_data: &DisambiguatedDefPathData, _self_ty: Ty<'tcx>, _trait_ref: Option>, ) -> Result<(), PrintError> { Err(fmt::Error) } + fn path_append( &mut self, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, @@ -283,6 +284,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { self.segments.push(disambiguated_data.as_sym(true)); Ok(()) } + fn path_generic_args( &mut self, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, @@ -298,8 +300,8 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { // let _ = [{struct Foo; Foo}, {struct Foo; Foo}]; if did1.krate != did2.krate { let abs_path = |def_id| { - let mut printer = AbsolutePathPrinter { tcx: self.tcx, segments: vec![] }; - printer.print_def_path(def_id, &[]).map(|_| printer.segments) + let mut p = AbsolutePathPrinter { tcx: self.tcx, segments: vec![] }; + p.print_def_path(def_id, &[]).map(|_| p.segments) }; // We compare strings because DefPath can be different diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs index 022d549a9df80..966f117a1bf91 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs @@ -244,7 +244,7 @@ impl<'a, 'tcx> TypeFolder> for ClosureEraser<'a, 'tcx> { } fn fmt_printer<'a, 'tcx>(infcx: &'a InferCtxt<'tcx>, ns: Namespace) -> FmtPrinter<'a, 'tcx> { - let mut printer = FmtPrinter::new(infcx.tcx, ns); + let mut p = FmtPrinter::new(infcx.tcx, ns); let ty_getter = move |ty_vid| { if infcx.probe_ty_var(ty_vid).is_ok() { warn!("resolved ty var in error message"); @@ -270,11 +270,11 @@ fn fmt_printer<'a, 'tcx>(infcx: &'a InferCtxt<'tcx>, ns: Namespace) -> FmtPrinte None } }; - printer.ty_infer_name_resolver = Some(Box::new(ty_getter)); + p.ty_infer_name_resolver = Some(Box::new(ty_getter)); let const_getter = move |ct_vid| Some(infcx.tcx.item_name(infcx.const_var_origin(ct_vid)?.param_def_id?)); - printer.const_infer_name_resolver = Some(Box::new(const_getter)); - printer + p.const_infer_name_resolver = Some(Box::new(const_getter)); + p } fn ty_to_string<'tcx>( @@ -282,7 +282,7 @@ fn ty_to_string<'tcx>( ty: Ty<'tcx>, called_method_def_id: Option, ) -> String { - let mut printer = fmt_printer(infcx, Namespace::TypeNS); + let mut p = fmt_printer(infcx, Namespace::TypeNS); let ty = infcx.resolve_vars_if_possible(ty); // We use `fn` ptr syntax for closures, but this only works when the closure does not capture // anything. We also remove all type parameters that are fully known to the type system. @@ -292,8 +292,8 @@ fn ty_to_string<'tcx>( // We don't want the regular output for `fn`s because it includes its path in // invalid pseudo-syntax, we want the `fn`-pointer output instead. (ty::FnDef(..), _) => { - ty.fn_sig(infcx.tcx).print(&mut printer).unwrap(); - printer.into_buffer() + ty.fn_sig(infcx.tcx).print(&mut p).unwrap(); + p.into_buffer() } (_, Some(def_id)) if ty.is_ty_or_numeric_infer() @@ -303,8 +303,8 @@ fn ty_to_string<'tcx>( } _ if ty.is_ty_or_numeric_infer() => "/* Type */".to_string(), _ => { - ty.print(&mut printer).unwrap(); - printer.into_buffer() + ty.print(&mut p).unwrap(); + p.into_buffer() } } } @@ -561,21 +561,20 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { { "Vec<_>".to_string() } else { - let mut printer = fmt_printer(self, Namespace::TypeNS); - printer - .comma_sep(generic_args.iter().copied().map(|arg| { - if arg.is_suggestable(self.tcx, true) { - return arg; - } + let mut p = fmt_printer(self, Namespace::TypeNS); + p.comma_sep(generic_args.iter().copied().map(|arg| { + if arg.is_suggestable(self.tcx, true) { + return arg; + } - match arg.kind() { - GenericArgKind::Lifetime(_) => bug!("unexpected lifetime"), - GenericArgKind::Type(_) => self.next_ty_var(DUMMY_SP).into(), - GenericArgKind::Const(_) => self.next_const_var(DUMMY_SP).into(), - } - })) - .unwrap(); - printer.into_buffer() + match arg.kind() { + GenericArgKind::Lifetime(_) => bug!("unexpected lifetime"), + GenericArgKind::Type(_) => self.next_ty_var(DUMMY_SP).into(), + GenericArgKind::Const(_) => self.next_const_var(DUMMY_SP).into(), + } + })) + .unwrap(); + p.into_buffer() }; if !have_turbofish { @@ -589,9 +588,9 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { InferSourceKind::FullyQualifiedMethodCall { receiver, successor, args, def_id } => { let placeholder = Some(self.next_ty_var(DUMMY_SP)); if let Some(args) = args.make_suggestable(self.infcx.tcx, true, placeholder) { - let mut printer = fmt_printer(self, Namespace::ValueNS); - printer.print_def_path(def_id, args).unwrap(); - let def_path = printer.into_buffer(); + let mut p = fmt_printer(self, Namespace::ValueNS); + p.print_def_path(def_id, args).unwrap(); + let def_path = p.into_buffer(); // We only care about whether we have to add `&` or `&mut ` for now. // This is the case if the last adjustment is a borrow and the diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs index 64fc365c44a65..373b756dcdb71 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs @@ -47,11 +47,11 @@ where T: for<'a> Print<'tcx, FmtPrinter<'a, 'tcx>>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut printer = ty::print::FmtPrinter::new(self.tcx, self.ns); - printer.region_highlight_mode = self.highlight; + let mut p = ty::print::FmtPrinter::new(self.tcx, self.ns); + p.region_highlight_mode = self.highlight; - self.value.print(&mut printer)?; - f.write_str(&printer.into_buffer()) + self.value.print(&mut p)?; + f.write_str(&p.into_buffer()) } } diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs index 8e0620f20487b..129d0963a75a8 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs @@ -946,8 +946,8 @@ fn foo(&self) -> Self::T { String::new() } } pub fn format_generic_args(&self, args: &[ty::GenericArg<'tcx>]) -> String { - FmtPrinter::print_string(self.tcx, hir::def::Namespace::TypeNS, |cx| { - cx.path_generic_args(|_| Ok(()), args) + FmtPrinter::print_string(self.tcx, hir::def::Namespace::TypeNS, |p| { + p.path_generic_args(|_| Ok(()), args) }) .expect("could not write to `String`.") } diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/overflow.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/overflow.rs index d929ecf68bf34..4f1f5c330e5f4 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/overflow.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/overflow.rs @@ -66,10 +66,10 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { if s.len() > 50 { // We don't need to save the type to a file, we will be talking about this type already // in a separate note when we explain the obligation, so it will be available that way. - let mut cx: FmtPrinter<'_, '_> = + let mut p: FmtPrinter<'_, '_> = FmtPrinter::new_with_limit(tcx, Namespace::TypeNS, rustc_session::Limit(6)); - value.print(&mut cx).unwrap(); - cx.into_buffer() + value.print(&mut p).unwrap(); + p.into_buffer() } else { s }