Skip to content

More Printer cleanups #144949

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 7 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
24 changes: 12 additions & 12 deletions compiler/rustc_const_eval/src/util/type_name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ use rustc_middle::bug;
use rustc_middle::ty::print::{PrettyPrinter, PrintError, Printer};
use rustc_middle::ty::{self, GenericArg, GenericArgKind, Ty, TyCtxt};

struct AbsolutePathPrinter<'tcx> {
struct TypeNamePrinter<'tcx> {
tcx: TyCtxt<'tcx>,
path: String,
}

impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
impl<'tcx> Printer<'tcx> for TypeNamePrinter<'tcx> {
fn tcx(&self) -> TyCtxt<'tcx> {
self.tcx
}
Expand Down Expand Up @@ -73,26 +73,26 @@ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
self.pretty_print_dyn_existential(predicates)
}

fn path_crate(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
fn print_crate_name(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
self.path.push_str(self.tcx.crate_name(cnum).as_str());
Ok(())
}

fn path_qualified(
fn print_path_with_qualified(
&mut self,
self_ty: Ty<'tcx>,
trait_ref: Option<ty::TraitRef<'tcx>>,
) -> Result<(), PrintError> {
self.pretty_path_qualified(self_ty, trait_ref)
self.pretty_print_path_with_qualified(self_ty, trait_ref)
}

fn path_append_impl(
fn print_path_with_impl(
&mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
self_ty: Ty<'tcx>,
trait_ref: Option<ty::TraitRef<'tcx>>,
) -> Result<(), PrintError> {
self.pretty_path_append_impl(
self.pretty_print_path_with_impl(
|cx| {
print_prefix(cx)?;

Expand All @@ -105,7 +105,7 @@ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
)
}

fn path_append(
fn print_path_with_simple(
&mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
disambiguated_data: &DisambiguatedDefPathData,
Expand All @@ -117,7 +117,7 @@ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
Ok(())
}

fn path_generic_args(
fn print_path_with_generic_args(
&mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
args: &[GenericArg<'tcx>],
Expand All @@ -133,7 +133,7 @@ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
}
}

impl<'tcx> PrettyPrinter<'tcx> for AbsolutePathPrinter<'tcx> {
impl<'tcx> PrettyPrinter<'tcx> for TypeNamePrinter<'tcx> {
fn should_print_region(&self, _region: ty::Region<'_>) -> bool {
false
}
Expand All @@ -157,15 +157,15 @@ impl<'tcx> PrettyPrinter<'tcx> for AbsolutePathPrinter<'tcx> {
}
}

impl Write for AbsolutePathPrinter<'_> {
impl Write for TypeNamePrinter<'_> {
fn write_str(&mut self, s: &str) -> std::fmt::Result {
self.path.push_str(s);
Ok(())
}
}

pub fn type_name<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> String {
let mut p = AbsolutePathPrinter { tcx, path: String::new() };
let mut p = TypeNamePrinter { tcx, path: String::new() };
p.print_type(ty).unwrap();
p.path
}
16 changes: 8 additions & 8 deletions compiler/rustc_lint/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -745,12 +745,12 @@ impl<'tcx> LateContext<'tcx> {
/// }
/// ```
pub fn get_def_path(&self, def_id: DefId) -> Vec<Symbol> {
struct AbsolutePathPrinter<'tcx> {
struct LintPathPrinter<'tcx> {
tcx: TyCtxt<'tcx>,
path: Vec<Symbol>,
}

impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
impl<'tcx> Printer<'tcx> for LintPathPrinter<'tcx> {
fn tcx(&self) -> TyCtxt<'tcx> {
self.tcx
}
Expand All @@ -774,12 +774,12 @@ impl<'tcx> LateContext<'tcx> {
unreachable!(); // because `path_generic_args` ignores the `GenericArgs`
}

fn path_crate(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
fn print_crate_name(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
self.path = vec![self.tcx.crate_name(cnum)];
Ok(())
}

fn path_qualified(
fn print_path_with_qualified(
&mut self,
self_ty: Ty<'tcx>,
trait_ref: Option<ty::TraitRef<'tcx>>,
Expand All @@ -800,7 +800,7 @@ impl<'tcx> LateContext<'tcx> {
})
}

fn path_append_impl(
fn print_path_with_impl(
&mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
self_ty: Ty<'tcx>,
Expand All @@ -825,7 +825,7 @@ impl<'tcx> LateContext<'tcx> {
Ok(())
}

fn path_append(
fn print_path_with_simple(
&mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
disambiguated_data: &DisambiguatedDefPathData,
Expand All @@ -844,7 +844,7 @@ impl<'tcx> LateContext<'tcx> {
Ok(())
}

fn path_generic_args(
fn print_path_with_generic_args(
&mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
_args: &[GenericArg<'tcx>],
Expand All @@ -853,7 +853,7 @@ impl<'tcx> LateContext<'tcx> {
}
}

let mut p = AbsolutePathPrinter { tcx: self.tcx, path: vec![] };
let mut p = LintPathPrinter { tcx: self.tcx, path: vec![] };
p.print_def_path(def_id, &[]).unwrap();
p.path
}
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_middle/src/mir/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1969,7 +1969,7 @@ fn pretty_print_const_value_tcx<'tcx>(
let args = tcx.lift(args).unwrap();
let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
p.print_alloc_ids = true;
p.print_value_path(variant_def.def_id, args)?;
p.pretty_print_value_path(variant_def.def_id, args)?;
fmt.write_str(&p.into_buffer())?;

match variant_def.ctor_kind() {
Expand Down Expand Up @@ -2011,7 +2011,7 @@ fn pretty_print_const_value_tcx<'tcx>(
(ConstValue::ZeroSized, ty::FnDef(d, s)) => {
let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
p.print_alloc_ids = true;
p.print_value_path(*d, s)?;
p.pretty_print_value_path(*d, s)?;
fmt.write_str(&p.into_buffer())?;
return Ok(());
}
Expand Down
82 changes: 52 additions & 30 deletions compiler/rustc_middle/src/ty/print/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,16 @@ pub trait Print<'tcx, P> {
fn print(&self, p: &mut P) -> Result<(), PrintError>;
}

/// Interface for outputting user-facing "type-system entities"
/// (paths, types, lifetimes, constants, etc.) as a side-effect
/// (e.g. formatting, like `PrettyPrinter` implementors do) or by
/// constructing some alternative representation (e.g. an AST),
/// which the associated types allow passing through the methods.
///
/// For pretty-printing/formatting in particular, see `PrettyPrinter`.
//
// FIXME(eddyb) find a better name; this is more general than "printing".
/// A trait that "prints" user-facing type system entities: paths, types, lifetimes, constants,
/// etc. "Printing" here means building up a representation of the entity's path, usually as a
/// `String` (e.g. "std::io::Read") or a `Vec<Symbol>` (e.g. `[sym::std, sym::io, sym::Read]`). The
/// representation is built up by appending one or more pieces. The specific details included in
/// the built-up representation depend on the purpose of the printer. The more advanced printers
/// also rely on the `PrettyPrinter` sub-trait.
pub trait Printer<'tcx>: Sized {
fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;

/// Appends a representation of an entity with a normal path, e.g. "std::io::Read".
fn print_def_path(
&mut self,
def_id: DefId,
Expand All @@ -41,6 +39,7 @@ pub trait Printer<'tcx>: Sized {
self.default_print_def_path(def_id, args)
}

/// Like `print_def_path`, but for `DefPathData::Impl`.
fn print_impl_path(
&mut self,
impl_def_id: DefId,
Expand All @@ -66,48 +65,67 @@ pub trait Printer<'tcx>: Sized {
self.default_print_impl_path(impl_def_id, self_ty, impl_trait_ref)
}

/// Appends a representation of a region.
fn print_region(&mut self, region: ty::Region<'tcx>) -> Result<(), PrintError>;

/// Appends a representation of a type.
fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError>;

/// Appends a representation of a list of `PolyExistentialPredicate`s.
fn print_dyn_existential(
&mut self,
predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
) -> Result<(), PrintError>;

/// Appends a representation of a const.
fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError>;

fn path_crate(&mut self, cnum: CrateNum) -> Result<(), PrintError>;
/// Appends a representation of a crate name, e.g. `std`, or even ``.
fn print_crate_name(&mut self, cnum: CrateNum) -> Result<(), PrintError>;

fn path_qualified(
/// Appends a representation of a (full or partial) simple path, in two parts. `print_prefix`,
/// when called, appends the representation of the leading segments. The rest of the method
/// appends the representation of the final segment, the details of which are in
/// `disambiguated_data`.
///
/// E.g. `std::io` + `Read` -> `std::io::Read`.
fn print_path_with_simple(
&mut self,
self_ty: Ty<'tcx>,
trait_ref: Option<ty::TraitRef<'tcx>>,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
disambiguated_data: &DisambiguatedDefPathData,
) -> Result<(), PrintError>;

fn path_append_impl(
/// Similar to `print_path_with_simple`, but the final segment is an `impl` segment.
///
/// E.g. `slice` + `<impl [T]>` -> `slice::<impl [T]>`, which may then be further appended to,
/// giving a longer path representation such as `slice::<impl [T]>::to_vec_in::ConvertVec`.
fn print_path_with_impl(
&mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
self_ty: Ty<'tcx>,
trait_ref: Option<ty::TraitRef<'tcx>>,
) -> Result<(), PrintError>;

fn path_append(
/// Appends a representation of a path ending in generic args, in two parts. `print_prefix`,
/// when called, appends the leading segments. The rest of the method appends the
/// representation of the generic args. (Some printers choose to skip appending the generic
/// args.)
///
/// E.g. `ImplementsTraitForUsize` + `<usize>` -> `ImplementsTraitForUsize<usize>`.
fn print_path_with_generic_args(
&mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
disambiguated_data: &DisambiguatedDefPathData,
args: &[GenericArg<'tcx>],
) -> Result<(), PrintError>;

fn path_generic_args(
/// Appends a representation of a qualified path segment, e.g. `<OsString as From<&T>>`.
/// If `trait_ref` is `None`, it may fall back to simpler forms, e.g. `<Vec<T>>` or just `Foo`.
fn print_path_with_qualified(
&mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
args: &[GenericArg<'tcx>],
self_ty: Ty<'tcx>,
trait_ref: Option<ty::TraitRef<'tcx>>,
) -> Result<(), PrintError>;

fn should_truncate(&mut self) -> bool {
false
}

// Defaults (should not be overridden):

#[instrument(skip(self), level = "debug")]
Expand All @@ -122,7 +140,7 @@ pub trait Printer<'tcx>: Sized {
match key.disambiguated_data.data {
DefPathData::CrateRoot => {
assert!(key.parent.is_none());
self.path_crate(def_id.krate)
self.print_crate_name(def_id.krate)
}

DefPathData::Impl => self.print_impl_path(def_id, args),
Expand All @@ -146,7 +164,7 @@ pub trait Printer<'tcx>: Sized {
)) = self.tcx().coroutine_kind(def_id)
&& args.len() > parent_args.len()
{
return self.path_generic_args(
return self.print_path_with_generic_args(
|p| p.print_def_path(def_id, parent_args),
&args[..parent_args.len() + 1][..1],
);
Expand All @@ -168,7 +186,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(
return self.print_path_with_generic_args(
|p| p.print_def_path(def_id, parent_args),
args,
);
Expand All @@ -184,15 +202,15 @@ pub trait Printer<'tcx>: Sized {
&& self.tcx().generics_of(parent_def_id).parent_count == 0;
}

self.path_append(
self.print_path_with_simple(
|p: &mut Self| {
if trait_qualify_parent {
let trait_ref = ty::TraitRef::new(
p.tcx(),
parent_def_id,
parent_args.iter().copied(),
);
p.path_qualified(trait_ref.self_ty(), Some(trait_ref))
p.print_path_with_qualified(trait_ref.self_ty(), Some(trait_ref))
} else {
p.print_def_path(parent_def_id, parent_args)
}
Expand Down Expand Up @@ -235,11 +253,15 @@ 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(|p| p.print_def_path(parent_def_id, &[]), self_ty, impl_trait_ref)
self.print_path_with_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.
self.path_qualified(self_ty, impl_trait_ref)
self.print_path_with_qualified(self_ty, impl_trait_ref)
}
}
}
Expand Down
Loading
Loading