Skip to content

Commit a1e41a0

Browse files
Rollup merge of #144776 - nnethercote:Printer-cleanups, r=cjgillot
`Printer` cleanups The trait `Printer` is implemented by six types, and the sub-trait `PrettyPrinter` is implemented by three of those types. The traits and the impls are complex and a bit of a mess. This PR starts to clean them up. r? ``@davidtwco``
2 parents 4cb0ebd + cc62d55 commit a1e41a0

File tree

17 files changed

+649
-693
lines changed

17 files changed

+649
-693
lines changed

compiler/rustc_borrowck/src/diagnostics/mod.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -613,7 +613,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
613613
/// Return the name of the provided `Ty` (that must be a reference) with a synthesized lifetime
614614
/// name where required.
615615
pub(super) fn get_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {
616-
let mut printer = ty::print::FmtPrinter::new(self.infcx.tcx, Namespace::TypeNS);
616+
let mut p = ty::print::FmtPrinter::new(self.infcx.tcx, Namespace::TypeNS);
617617

618618
// We need to add synthesized lifetimes where appropriate. We do
619619
// this by hooking into the pretty printer and telling it to label the
@@ -624,36 +624,36 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
624624
| ty::RePlaceholder(ty::PlaceholderRegion {
625625
bound: ty::BoundRegion { kind: br, .. },
626626
..
627-
}) => printer.region_highlight_mode.highlighting_bound_region(br, counter),
627+
}) => p.region_highlight_mode.highlighting_bound_region(br, counter),
628628
_ => {}
629629
}
630630
}
631631

632-
ty.print(&mut printer).unwrap();
633-
printer.into_buffer()
632+
ty.print(&mut p).unwrap();
633+
p.into_buffer()
634634
}
635635

636636
/// Returns the name of the provided `Ty` (that must be a reference)'s region with a
637637
/// synthesized lifetime name where required.
638638
pub(super) fn get_region_name_for_ty(&self, ty: Ty<'tcx>, counter: usize) -> String {
639-
let mut printer = ty::print::FmtPrinter::new(self.infcx.tcx, Namespace::TypeNS);
639+
let mut p = ty::print::FmtPrinter::new(self.infcx.tcx, Namespace::TypeNS);
640640

641641
let region = if let ty::Ref(region, ..) = ty.kind() {
642642
match region.kind() {
643643
ty::ReBound(_, ty::BoundRegion { kind: br, .. })
644644
| ty::RePlaceholder(ty::PlaceholderRegion {
645645
bound: ty::BoundRegion { kind: br, .. },
646646
..
647-
}) => printer.region_highlight_mode.highlighting_bound_region(br, counter),
647+
}) => p.region_highlight_mode.highlighting_bound_region(br, counter),
648648
_ => {}
649649
}
650650
region
651651
} else {
652652
bug!("ty for annotation of borrow region is not a reference");
653653
};
654654

655-
region.print(&mut printer).unwrap();
656-
printer.into_buffer()
655+
region.print(&mut p).unwrap();
656+
p.into_buffer()
657657
}
658658

659659
/// Add a note to region errors and borrow explanations when higher-ranked regions in predicates

compiler/rustc_const_eval/src/interpret/operand.rs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -188,27 +188,28 @@ pub struct ImmTy<'tcx, Prov: Provenance = CtfeProvenance> {
188188
impl<Prov: Provenance> std::fmt::Display for ImmTy<'_, Prov> {
189189
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
190190
/// Helper function for printing a scalar to a FmtPrinter
191-
fn p<'a, 'tcx, Prov: Provenance>(
192-
cx: &mut FmtPrinter<'a, 'tcx>,
191+
fn print_scalar<'a, 'tcx, Prov: Provenance>(
192+
p: &mut FmtPrinter<'a, 'tcx>,
193193
s: Scalar<Prov>,
194194
ty: Ty<'tcx>,
195195
) -> Result<(), std::fmt::Error> {
196196
match s {
197-
Scalar::Int(int) => cx.pretty_print_const_scalar_int(int, ty, true),
197+
Scalar::Int(int) => p.pretty_print_const_scalar_int(int, ty, true),
198198
Scalar::Ptr(ptr, _sz) => {
199199
// Just print the ptr value. `pretty_print_const_scalar_ptr` would also try to
200200
// print what is points to, which would fail since it has no access to the local
201201
// memory.
202-
cx.pretty_print_const_pointer(ptr, ty)
202+
p.pretty_print_const_pointer(ptr, ty)
203203
}
204204
}
205205
}
206206
ty::tls::with(|tcx| {
207207
match self.imm {
208208
Immediate::Scalar(s) => {
209209
if let Some(ty) = tcx.lift(self.layout.ty) {
210-
let s =
211-
FmtPrinter::print_string(tcx, Namespace::ValueNS, |cx| p(cx, s, ty))?;
210+
let s = FmtPrinter::print_string(tcx, Namespace::ValueNS, |p| {
211+
print_scalar(p, s, ty)
212+
})?;
212213
f.write_str(&s)?;
213214
return Ok(());
214215
}

compiler/rustc_const_eval/src/util/type_name.rs

Lines changed: 5 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use rustc_data_structures::intern::Interned;
44
use rustc_hir::def_id::CrateNum;
55
use rustc_hir::definitions::DisambiguatedDefPathData;
66
use rustc_middle::bug;
7-
use rustc_middle::ty::print::{PrettyPrinter, Print, PrintError, Printer};
7+
use rustc_middle::ty::print::{PrettyPrinter, PrintError, Printer};
88
use rustc_middle::ty::{self, GenericArg, GenericArgKind, Ty, TyCtxt};
99

1010
struct AbsolutePathPrinter<'tcx> {
@@ -18,7 +18,7 @@ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
1818
}
1919

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

2424
fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError> {
@@ -89,7 +89,6 @@ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
8989
fn path_append_impl(
9090
&mut self,
9191
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
92-
_disambiguated_data: &DisambiguatedDefPathData,
9392
self_ty: Ty<'tcx>,
9493
trait_ref: Option<ty::TraitRef<'tcx>>,
9594
) -> Result<(), PrintError> {
@@ -138,19 +137,6 @@ impl<'tcx> PrettyPrinter<'tcx> for AbsolutePathPrinter<'tcx> {
138137
fn should_print_region(&self, _region: ty::Region<'_>) -> bool {
139138
false
140139
}
141-
fn comma_sep<T>(&mut self, mut elems: impl Iterator<Item = T>) -> Result<(), PrintError>
142-
where
143-
T: Print<'tcx, Self>,
144-
{
145-
if let Some(first) = elems.next() {
146-
first.print(self)?;
147-
for elem in elems {
148-
self.path.push_str(", ");
149-
elem.print(self)?;
150-
}
151-
}
152-
Ok(())
153-
}
154140

155141
fn generic_delimiters(
156142
&mut self,
@@ -179,7 +165,7 @@ impl Write for AbsolutePathPrinter<'_> {
179165
}
180166

181167
pub fn type_name<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> String {
182-
let mut printer = AbsolutePathPrinter { tcx, path: String::new() };
183-
printer.print_type(ty).unwrap();
184-
printer.path
168+
let mut p = AbsolutePathPrinter { tcx, path: String::new() };
169+
p.print_type(ty).unwrap();
170+
p.path
185171
}

compiler/rustc_lint/src/context.rs

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -756,22 +756,22 @@ impl<'tcx> LateContext<'tcx> {
756756
}
757757

758758
fn print_region(&mut self, _region: ty::Region<'_>) -> Result<(), PrintError> {
759-
Ok(())
759+
unreachable!(); // because `path_generic_args` ignores the `GenericArgs`
760760
}
761761

762762
fn print_type(&mut self, _ty: Ty<'tcx>) -> Result<(), PrintError> {
763-
Ok(())
763+
unreachable!(); // because `path_generic_args` ignores the `GenericArgs`
764764
}
765765

766766
fn print_dyn_existential(
767767
&mut self,
768768
_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
769769
) -> Result<(), PrintError> {
770-
Ok(())
770+
unreachable!(); // because `path_generic_args` ignores the `GenericArgs`
771771
}
772772

773773
fn print_const(&mut self, _ct: ty::Const<'tcx>) -> Result<(), PrintError> {
774-
Ok(())
774+
unreachable!(); // because `path_generic_args` ignores the `GenericArgs`
775775
}
776776

777777
fn path_crate(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
@@ -784,10 +784,10 @@ impl<'tcx> LateContext<'tcx> {
784784
self_ty: Ty<'tcx>,
785785
trait_ref: Option<ty::TraitRef<'tcx>>,
786786
) -> Result<(), PrintError> {
787-
if trait_ref.is_none() {
788-
if let ty::Adt(def, args) = self_ty.kind() {
789-
return self.print_def_path(def.did(), args);
790-
}
787+
if trait_ref.is_none()
788+
&& let ty::Adt(def, args) = self_ty.kind()
789+
{
790+
return self.print_def_path(def.did(), args);
791791
}
792792

793793
// This shouldn't ever be needed, but just in case:
@@ -803,7 +803,6 @@ impl<'tcx> LateContext<'tcx> {
803803
fn path_append_impl(
804804
&mut self,
805805
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
806-
_disambiguated_data: &DisambiguatedDefPathData,
807806
self_ty: Ty<'tcx>,
808807
trait_ref: Option<ty::TraitRef<'tcx>>,
809808
) -> Result<(), PrintError> {
@@ -854,9 +853,9 @@ impl<'tcx> LateContext<'tcx> {
854853
}
855854
}
856855

857-
let mut printer = AbsolutePathPrinter { tcx: self.tcx, path: vec![] };
858-
printer.print_def_path(def_id, &[]).unwrap();
859-
printer.path
856+
let mut p = AbsolutePathPrinter { tcx: self.tcx, path: vec![] };
857+
p.print_def_path(def_id, &[]).unwrap();
858+
p.path
860859
}
861860

862861
/// Returns the associated type `name` for `self_ty` as an implementation of `trait_id`.

compiler/rustc_middle/src/mir/pretty.rs

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1197,8 +1197,8 @@ impl<'tcx> Debug for Rvalue<'tcx> {
11971197
ty::tls::with(|tcx| {
11981198
let variant_def = &tcx.adt_def(adt_did).variant(variant);
11991199
let args = tcx.lift(args).expect("could not lift for printing");
1200-
let name = FmtPrinter::print_string(tcx, Namespace::ValueNS, |cx| {
1201-
cx.print_def_path(variant_def.def_id, args)
1200+
let name = FmtPrinter::print_string(tcx, Namespace::ValueNS, |p| {
1201+
p.print_def_path(variant_def.def_id, args)
12021202
})?;
12031203

12041204
match variant_def.ctor_kind() {
@@ -1473,9 +1473,9 @@ impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> {
14731473
};
14741474

14751475
let fmt_valtree = |cv: &ty::Value<'tcx>| {
1476-
let mut cx = FmtPrinter::new(self.tcx, Namespace::ValueNS);
1477-
cx.pretty_print_const_valtree(*cv, /*print_ty*/ true).unwrap();
1478-
cx.into_buffer()
1476+
let mut p = FmtPrinter::new(self.tcx, Namespace::ValueNS);
1477+
p.pretty_print_const_valtree(*cv, /*print_ty*/ true).unwrap();
1478+
p.into_buffer()
14791479
};
14801480

14811481
let val = match const_ {
@@ -1967,10 +1967,10 @@ fn pretty_print_const_value_tcx<'tcx>(
19671967
.expect("destructed mir constant of adt without variant idx");
19681968
let variant_def = &def.variant(variant_idx);
19691969
let args = tcx.lift(args).unwrap();
1970-
let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
1971-
cx.print_alloc_ids = true;
1972-
cx.print_value_path(variant_def.def_id, args)?;
1973-
fmt.write_str(&cx.into_buffer())?;
1970+
let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
1971+
p.print_alloc_ids = true;
1972+
p.print_value_path(variant_def.def_id, args)?;
1973+
fmt.write_str(&p.into_buffer())?;
19741974

19751975
match variant_def.ctor_kind() {
19761976
Some(CtorKind::Const) => {}
@@ -2001,18 +2001,18 @@ fn pretty_print_const_value_tcx<'tcx>(
20012001
}
20022002
}
20032003
(ConstValue::Scalar(scalar), _) => {
2004-
let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
2005-
cx.print_alloc_ids = true;
2004+
let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
2005+
p.print_alloc_ids = true;
20062006
let ty = tcx.lift(ty).unwrap();
2007-
cx.pretty_print_const_scalar(scalar, ty)?;
2008-
fmt.write_str(&cx.into_buffer())?;
2007+
p.pretty_print_const_scalar(scalar, ty)?;
2008+
fmt.write_str(&p.into_buffer())?;
20092009
return Ok(());
20102010
}
20112011
(ConstValue::ZeroSized, ty::FnDef(d, s)) => {
2012-
let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
2013-
cx.print_alloc_ids = true;
2014-
cx.print_value_path(*d, s)?;
2015-
fmt.write_str(&cx.into_buffer())?;
2012+
let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
2013+
p.print_alloc_ids = true;
2014+
p.print_value_path(*d, s)?;
2015+
fmt.write_str(&p.into_buffer())?;
20162016
return Ok(());
20172017
}
20182018
// FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading

compiler/rustc_middle/src/ty/error.rs

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -213,13 +213,13 @@ impl<'tcx> Ty<'tcx> {
213213
}
214214

215215
impl<'tcx> TyCtxt<'tcx> {
216-
pub fn string_with_limit<T>(self, p: T, length_limit: usize) -> String
216+
pub fn string_with_limit<T>(self, t: T, length_limit: usize) -> String
217217
where
218218
T: Copy + for<'a, 'b> Lift<TyCtxt<'b>, Lifted: Print<'b, FmtPrinter<'a, 'b>>>,
219219
{
220220
let mut type_limit = 50;
221-
let regular = FmtPrinter::print_string(self, hir::def::Namespace::TypeNS, |cx| {
222-
self.lift(p).expect("could not lift for printing").print(cx)
221+
let regular = FmtPrinter::print_string(self, hir::def::Namespace::TypeNS, |p| {
222+
self.lift(t).expect("could not lift for printing").print(p)
223223
})
224224
.expect("could not write to `String`");
225225
if regular.len() <= length_limit {
@@ -229,16 +229,16 @@ impl<'tcx> TyCtxt<'tcx> {
229229
loop {
230230
// Look for the longest properly trimmed path that still fits in length_limit.
231231
short = with_forced_trimmed_paths!({
232-
let mut cx = FmtPrinter::new_with_limit(
232+
let mut p = FmtPrinter::new_with_limit(
233233
self,
234234
hir::def::Namespace::TypeNS,
235235
rustc_session::Limit(type_limit),
236236
);
237-
self.lift(p)
237+
self.lift(t)
238238
.expect("could not lift for printing")
239-
.print(&mut cx)
239+
.print(&mut p)
240240
.expect("could not print type");
241-
cx.into_buffer()
241+
p.into_buffer()
242242
});
243243
if short.len() <= length_limit || type_limit == 0 {
244244
break;
@@ -252,12 +252,12 @@ impl<'tcx> TyCtxt<'tcx> {
252252
/// `tcx.short_string(ty, diag.long_ty_path())`. The diagnostic itself is the one that keeps
253253
/// the existence of a "long type" anywhere in the diagnostic, so the note telling the user
254254
/// where we wrote the file to is only printed once.
255-
pub fn short_string<T>(self, p: T, path: &mut Option<PathBuf>) -> String
255+
pub fn short_string<T>(self, t: T, path: &mut Option<PathBuf>) -> String
256256
where
257257
T: Copy + Hash + for<'a, 'b> Lift<TyCtxt<'b>, Lifted: Print<'b, FmtPrinter<'a, 'b>>>,
258258
{
259-
let regular = FmtPrinter::print_string(self, hir::def::Namespace::TypeNS, |cx| {
260-
self.lift(p).expect("could not lift for printing").print(cx)
259+
let regular = FmtPrinter::print_string(self, hir::def::Namespace::TypeNS, |p| {
260+
self.lift(t).expect("could not lift for printing").print(p)
261261
})
262262
.expect("could not write to `String`");
263263

@@ -270,13 +270,13 @@ impl<'tcx> TyCtxt<'tcx> {
270270
if regular.len() <= width * 2 / 3 {
271271
return regular;
272272
}
273-
let short = self.string_with_limit(p, length_limit);
273+
let short = self.string_with_limit(t, length_limit);
274274
if regular == short {
275275
return regular;
276276
}
277277
// Ensure we create an unique file for the type passed in when we create a file.
278278
let mut s = DefaultHasher::new();
279-
p.hash(&mut s);
279+
t.hash(&mut s);
280280
let hash = s.finish();
281281
*path = Some(path.take().unwrap_or_else(|| {
282282
self.output_filenames(()).temp_path_for_diagnostic(&format!("long-type-{hash}.txt"))

compiler/rustc_middle/src/ty/instance.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -397,13 +397,13 @@ pub fn fmt_instance(
397397
ty::tls::with(|tcx| {
398398
let args = tcx.lift(instance.args).expect("could not lift for printing");
399399

400-
let mut cx = if let Some(type_length) = type_length {
400+
let mut p = if let Some(type_length) = type_length {
401401
FmtPrinter::new_with_limit(tcx, Namespace::ValueNS, type_length)
402402
} else {
403403
FmtPrinter::new(tcx, Namespace::ValueNS)
404404
};
405-
cx.print_def_path(instance.def_id(), args)?;
406-
let s = cx.into_buffer();
405+
p.print_def_path(instance.def_id(), args)?;
406+
let s = p.into_buffer();
407407
f.write_str(&s)
408408
})?;
409409

0 commit comments

Comments
 (0)