Skip to content

Printer cleanups #144776

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions compiler/rustc_borrowck/src/diagnostics/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -624,36 +624,36 @@ 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() {
ty::ReBound(_, ty::BoundRegion { kind: br, .. })
| 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
} else {
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
Expand Down
13 changes: 7 additions & 6 deletions compiler/rustc_const_eval/src/interpret/operand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,27 +188,28 @@ pub struct ImmTy<'tcx, Prov: Provenance = CtfeProvenance> {
impl<Prov: Provenance> 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<Prov>,
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)
}
}
}
ty::tls::with(|tcx| {
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(());
}
Expand Down
24 changes: 5 additions & 19 deletions compiler/rustc_const_eval/src/util/type_name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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> {
Expand All @@ -18,7 +18,7 @@ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
}

fn print_region(&mut self, _region: ty::Region<'_>) -> Result<(), PrintError> {
Ok(())
unreachable!(); // because `<Self As PrettyPrinter>::should_print_region` returns false
}

fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> {
Expand Down Expand Up @@ -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<ty::TraitRef<'tcx>>,
) -> Result<(), PrintError> {
Expand Down Expand Up @@ -138,19 +137,6 @@ impl<'tcx> PrettyPrinter<'tcx> for AbsolutePathPrinter<'tcx> {
fn should_print_region(&self, _region: ty::Region<'_>) -> bool {
false
}
fn comma_sep<T>(&mut self, mut elems: impl Iterator<Item = T>) -> 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,
Expand Down Expand Up @@ -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
}
23 changes: 11 additions & 12 deletions compiler/rustc_lint/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ty::PolyExistentialPredicate<'tcx>>,
) -> 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> {
Expand All @@ -784,10 +784,10 @@ impl<'tcx> LateContext<'tcx> {
self_ty: Ty<'tcx>,
trait_ref: Option<ty::TraitRef<'tcx>>,
) -> 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:
Expand All @@ -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<ty::TraitRef<'tcx>>,
) -> Result<(), PrintError> {
Expand Down Expand Up @@ -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`.
Expand Down
34 changes: 17 additions & 17 deletions compiler/rustc_middle/src/mir/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down Expand Up @@ -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_ {
Expand Down Expand Up @@ -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) => {}
Expand Down Expand Up @@ -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
Expand Down
24 changes: 12 additions & 12 deletions compiler/rustc_middle/src/ty/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,13 +213,13 @@ impl<'tcx> Ty<'tcx> {
}

impl<'tcx> TyCtxt<'tcx> {
pub fn string_with_limit<T>(self, p: T, length_limit: usize) -> String
pub fn string_with_limit<T>(self, t: T, length_limit: usize) -> String
where
T: Copy + for<'a, 'b> Lift<TyCtxt<'b>, 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 {
Expand All @@ -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;
Expand All @@ -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<T>(self, p: T, path: &mut Option<PathBuf>) -> String
pub fn short_string<T>(self, t: T, path: &mut Option<PathBuf>) -> String
where
T: Copy + Hash + for<'a, 'b> Lift<TyCtxt<'b>, 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`");

Expand All @@ -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"))
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_middle/src/ty/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})?;

Expand Down
Loading
Loading