Skip to content

Commit b0fbca9

Browse files
committed
rustc: integrate LocalPathPrinter's behavior into FmtPrinter.
1 parent 9f8aaa0 commit b0fbca9

File tree

2 files changed

+63
-39
lines changed

2 files changed

+63
-39
lines changed

src/librustc/ty/print.rs

Lines changed: 49 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use rustc_data_structures::fx::FxHashSet;
1111
use syntax::symbol::InternedString;
1212

1313
use std::cell::Cell;
14-
use std::fmt;
14+
use std::fmt::{self, Write as _};
1515
use std::ops::Deref;
1616

1717
thread_local! {
@@ -145,6 +145,7 @@ pub trait Print<'tcx, P> {
145145
pub trait Printer: Sized {
146146
type Path;
147147

148+
#[must_use]
148149
fn print_def_path(
149150
self: &mut PrintCx<'_, '_, 'tcx, Self>,
150151
def_id: DefId,
@@ -153,6 +154,7 @@ pub trait Printer: Sized {
153154
) -> Self::Path {
154155
self.default_print_def_path(def_id, substs, ns)
155156
}
157+
#[must_use]
156158
fn print_impl_path(
157159
self: &mut PrintCx<'_, '_, 'tcx, Self>,
158160
impl_def_id: DefId,
@@ -162,15 +164,26 @@ pub trait Printer: Sized {
162164
self.default_print_impl_path(impl_def_id, substs, ns)
163165
}
164166

167+
#[must_use]
165168
fn path_crate(self: &mut PrintCx<'_, '_, '_, Self>, cnum: CrateNum) -> Self::Path;
169+
#[must_use]
166170
fn path_impl(self: &mut PrintCx<'_, '_, '_, Self>, text: &str) -> Self::Path;
171+
#[must_use]
167172
fn path_append(
168173
self: &mut PrintCx<'_, '_, '_, Self>,
169174
path: Self::Path,
170175
text: &str,
171176
) -> Self::Path;
172177
}
173178

179+
#[must_use]
180+
pub struct PrettyPath {
181+
pub empty: bool,
182+
}
183+
184+
/// Trait for printers that pretty-print using `fmt::Write` to the printer.
185+
pub trait PrettyPrinter: Printer<Path = Result<PrettyPath, fmt::Error>> + fmt::Write {}
186+
174187
impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
175188
// HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
176189
// (but also some things just print a `DefId` generally so maybe we need this?)
@@ -202,7 +215,10 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
202215
if FORCE_ABSOLUTE.with(|force| force.get()) {
203216
PrintCx::new(self, AbsolutePathPrinter).print_def_path(def_id, substs, ns)
204217
} else {
205-
PrintCx::new(self, LocalPathPrinter).print_def_path(def_id, substs, ns)
218+
let mut s = String::new();
219+
let _ = PrintCx::new(self, FmtPrinter { fmt: &mut s })
220+
.print_def_path(def_id, substs, ns);
221+
s
206222
}
207223
}
208224

@@ -442,10 +458,7 @@ pub struct FmtPrinter<F: fmt::Write> {
442458
pub fmt: F,
443459
}
444460

445-
// FIXME(eddyb) integrate into `FmtPrinter`.
446-
struct LocalPathPrinter;
447-
448-
impl LocalPathPrinter {
461+
impl<F: fmt::Write> FmtPrinter<F> {
449462
/// If possible, this returns a global path resolving to `def_id` that is visible
450463
/// from at least one local module and returns true. If the crate defining `def_id` is
451464
/// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
@@ -582,8 +595,14 @@ impl LocalPathPrinter {
582595
}
583596
}
584597

585-
impl Printer for LocalPathPrinter {
586-
type Path = String;
598+
impl<F: fmt::Write> fmt::Write for FmtPrinter<F> {
599+
fn write_str(&mut self, s: &str) -> fmt::Result {
600+
self.fmt.write_str(s)
601+
}
602+
}
603+
604+
impl<F: fmt::Write> Printer for FmtPrinter<F> {
605+
type Path = Result<PrettyPath, fmt::Error>;
587606

588607
fn print_def_path(
589608
self: &mut PrintCx<'_, '_, 'tcx, Self>,
@@ -612,7 +631,6 @@ impl Printer for LocalPathPrinter {
612631
// If no type info is available, fall back to
613632
// pretty printing some span information. This should
614633
// only occur very early in the compiler pipeline.
615-
// FIXME(eddyb) this should just be using `tcx.def_span(impl_def_id)`
616634
let parent_def_id = self.tcx.parent(impl_def_id).unwrap();
617635
let path = self.print_def_path(parent_def_id, None, ns);
618636
let span = self.tcx.def_span(impl_def_id);
@@ -627,26 +645,39 @@ impl Printer for LocalPathPrinter {
627645
if self.tcx.sess.rust_2018() {
628646
// We add the `crate::` keyword on Rust 2018, only when desired.
629647
if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
630-
return keywords::Crate.name().to_string();
648+
write!(self.printer, "{}", keywords::Crate.name())?;
649+
return Ok(PrettyPath { empty: false });
631650
}
632651
}
633-
String::new()
652+
Ok(PrettyPath { empty: true })
634653
} else {
635-
self.tcx.crate_name(cnum).to_string()
654+
write!(self.printer, "{}", self.tcx.crate_name(cnum))?;
655+
Ok(PrettyPath { empty: false })
636656
}
637657
}
638658
fn path_impl(self: &mut PrintCx<'_, '_, '_, Self>, text: &str) -> Self::Path {
639-
text.to_string()
659+
write!(self.printer, "{}", text)?;
660+
Ok(PrettyPath { empty: false })
640661
}
641662
fn path_append(
642663
self: &mut PrintCx<'_, '_, '_, Self>,
643-
mut path: Self::Path,
664+
path: Self::Path,
644665
text: &str,
645666
) -> Self::Path {
646-
if !path.is_empty() {
647-
path.push_str("::");
667+
let path = path?;
668+
669+
// FIXME(eddyb) this shouldn't happen, but is currently
670+
// the case for `extern { ... }` "foreign modules".
671+
if text.is_empty() {
672+
return Ok(path);
648673
}
649-
path.push_str(text);
650-
path
674+
675+
if !path.empty {
676+
write!(self.printer, "::")?;
677+
}
678+
write!(self.printer, "{}", text)?;
679+
Ok(PrettyPath { empty: false })
651680
}
652681
}
682+
683+
impl<F: fmt::Write> PrettyPrinter for FmtPrinter<F> {}

src/librustc/util/ppaux.rs

Lines changed: 14 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,11 @@ use crate::ty::{Param, Bound, RawPtr, Ref, Never, Tuple};
1010
use crate::ty::{Closure, Generator, GeneratorWitness, Foreign, Projection, Opaque};
1111
use crate::ty::{Placeholder, UnnormalizedProjection, Dynamic, Int, Uint, Infer};
1212
use crate::ty::{self, ParamConst, Ty, TypeFoldable};
13-
use crate::ty::print::{FmtPrinter, PrintCx, Print};
13+
use crate::ty::print::{FmtPrinter, PrettyPrinter, PrintCx, Print};
1414
use crate::mir::interpret::ConstValue;
1515

1616
use std::cell::Cell;
17-
use std::fmt;
17+
use std::fmt::{self, Write as _};
1818
use std::iter;
1919
use std::usize;
2020

@@ -193,18 +193,18 @@ macro_rules! gen_display_debug {
193193
}
194194
macro_rules! gen_print_impl {
195195
( ($($x:tt)+) $target:ty, ($self:ident, $cx:ident) $disp:block $dbg:block ) => {
196-
impl<$($x)+, F: fmt::Write> Print<'tcx, FmtPrinter<F>> for $target {
196+
impl<$($x)+, P: PrettyPrinter> Print<'tcx, P> for $target {
197197
type Output = fmt::Result;
198-
fn print(&$self, $cx: &mut PrintCx<'_, '_, 'tcx, FmtPrinter<F>>) -> fmt::Result {
198+
fn print(&$self, $cx: &mut PrintCx<'_, '_, 'tcx, P>) -> fmt::Result {
199199
if $cx.is_debug $dbg
200200
else $disp
201201
}
202202
}
203203
};
204204
( () $target:ty, ($self:ident, $cx:ident) $disp:block $dbg:block ) => {
205-
impl<F: fmt::Write> Print<'tcx, FmtPrinter<F>> for $target {
205+
impl<P: PrettyPrinter> Print<'tcx, P> for $target {
206206
type Output = fmt::Result;
207-
fn print(&$self, $cx: &mut PrintCx<'_, '_, 'tcx, FmtPrinter<F>>) -> fmt::Result {
207+
fn print(&$self, $cx: &mut PrintCx<'_, '_, 'tcx, P>) -> fmt::Result {
208208
if $cx.is_debug $dbg
209209
else $disp
210210
}
@@ -235,7 +235,7 @@ macro_rules! define_print {
235235
( $generic:tt $target:ty,
236236
($self:ident, $cx:ident) { display $disp:block } ) => {
237237
gen_print_impl! { $generic $target, ($self, $cx) yes $disp no {
238-
write!($cx.printer.fmt, "{:?}", $self)
238+
write!($cx.printer, "{:?}", $self)
239239
} }
240240
};
241241
}
@@ -246,7 +246,7 @@ macro_rules! define_print_multi {
246246
}
247247
macro_rules! print_inner {
248248
( $cx:expr, write ($($data:expr),+) ) => {
249-
write!($cx.printer.fmt, $($data),+)
249+
write!($cx.printer, $($data),+)
250250
};
251251
( $cx:expr, $kind:ident ($data:expr) ) => {
252252
$data.$kind($cx)
@@ -258,7 +258,7 @@ macro_rules! print {
258258
};
259259
}
260260

261-
impl<F: fmt::Write> PrintCx<'a, 'gcx, 'tcx, FmtPrinter<F>> {
261+
impl<P: PrettyPrinter> PrintCx<'a, 'gcx, 'tcx, P> {
262262
fn fn_sig(
263263
&mut self,
264264
inputs: &[Ty<'tcx>],
@@ -409,7 +409,7 @@ impl<F: fmt::Write> PrintCx<'a, 'gcx, 'tcx, FmtPrinter<F>> {
409409
}
410410

411411
fn in_binder<T>(&mut self, value: &ty::Binder<T>) -> fmt::Result
412-
where T: Print<'tcx, FmtPrinter<F>, Output = fmt::Result> + TypeFoldable<'tcx>
412+
where T: Print<'tcx, P, Output = fmt::Result> + TypeFoldable<'tcx>
413413
{
414414
fn name_by_region_index(index: usize) -> InternedString {
415415
match index {
@@ -494,13 +494,6 @@ pub fn parameterized<F: fmt::Write>(
494494
})
495495
}
496496

497-
impl<'a, 'tcx, P, T: Print<'tcx, P>> Print<'tcx, P> for &'a T {
498-
type Output = T::Output;
499-
fn print(&self, cx: &mut PrintCx<'_, '_, 'tcx, P>) -> Self::Output {
500-
(*self).print(cx)
501-
}
502-
}
503-
504497
define_print! {
505498
('tcx) &'tcx ty::List<ty::ExistentialPredicate<'tcx>>, (self, cx) {
506499
display {
@@ -581,15 +574,15 @@ impl fmt::Debug for ty::GenericParamDef {
581574

582575
impl fmt::Debug for ty::TraitDef {
583576
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
584-
PrintCx::with(FmtPrinter { fmt: f }, |cx| {
577+
PrintCx::with(FmtPrinter { fmt: f }, |mut cx| {
585578
print!(cx, write("{}", cx.tcx.def_path_str(self.def_id)))
586579
})
587580
}
588581
}
589582

590583
impl fmt::Debug for ty::AdtDef {
591584
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
592-
PrintCx::with(FmtPrinter { fmt: f }, |cx| {
585+
PrintCx::with(FmtPrinter { fmt: f }, |mut cx| {
593586
print!(cx, write("{}", cx.tcx.def_path_str(self.did)))
594587
})
595588
}
@@ -605,7 +598,7 @@ impl<'tcx> fmt::Debug for ty::ClosureUpvar<'tcx> {
605598

606599
impl fmt::Debug for ty::UpvarId {
607600
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
608-
PrintCx::with(FmtPrinter { fmt: f }, |cx| {
601+
PrintCx::with(FmtPrinter { fmt: f }, |mut cx| {
609602
print!(cx, write("UpvarId({:?};`{}`;{:?})",
610603
self.var_path.hir_id,
611604
cx.tcx.hir().name_by_hir_id(self.var_path.hir_id),
@@ -928,7 +921,7 @@ define_print! {
928921
define_print! {
929922
() ty::Variance, (self, cx) {
930923
debug {
931-
cx.printer.fmt.write_str(match *self {
924+
cx.printer.write_str(match *self {
932925
ty::Covariant => "+",
933926
ty::Contravariant => "-",
934927
ty::Invariant => "o",

0 commit comments

Comments
 (0)