Rollup merge of #144949 - nnethercote:more-Printer-cleanups, r=davidtwco

More `Printer` cleanups

A sequel to rust-lang/rust#144776.

r? ```@davidtwco```
This commit is contained in:
Guillaume Gomez
2025-08-13 18:42:59 +02:00
committed by GitHub
9 changed files with 191 additions and 160 deletions

View File

@@ -7,12 +7,12 @@ use rustc_middle::bug;
use rustc_middle::ty::print::{PrettyPrinter, PrintError, Printer}; use rustc_middle::ty::print::{PrettyPrinter, PrintError, Printer};
use rustc_middle::ty::{self, GenericArg, GenericArgKind, Ty, TyCtxt}; use rustc_middle::ty::{self, GenericArg, GenericArgKind, Ty, TyCtxt};
struct AbsolutePathPrinter<'tcx> { struct TypeNamePrinter<'tcx> {
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
path: String, path: String,
} }
impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> { impl<'tcx> Printer<'tcx> for TypeNamePrinter<'tcx> {
fn tcx(&self) -> TyCtxt<'tcx> { fn tcx(&self) -> TyCtxt<'tcx> {
self.tcx self.tcx
} }
@@ -75,26 +75,26 @@ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
self.pretty_print_dyn_existential(predicates) 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()); self.path.push_str(self.tcx.crate_name(cnum).as_str());
Ok(()) Ok(())
} }
fn path_qualified( fn print_path_with_qualified(
&mut self, &mut self,
self_ty: Ty<'tcx>, self_ty: Ty<'tcx>,
trait_ref: Option<ty::TraitRef<'tcx>>, trait_ref: Option<ty::TraitRef<'tcx>>,
) -> Result<(), PrintError> { ) -> 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, &mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
self_ty: Ty<'tcx>, self_ty: Ty<'tcx>,
trait_ref: Option<ty::TraitRef<'tcx>>, trait_ref: Option<ty::TraitRef<'tcx>>,
) -> Result<(), PrintError> { ) -> Result<(), PrintError> {
self.pretty_path_append_impl( self.pretty_print_path_with_impl(
|cx| { |cx| {
print_prefix(cx)?; print_prefix(cx)?;
@@ -107,7 +107,7 @@ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
) )
} }
fn path_append( fn print_path_with_simple(
&mut self, &mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
disambiguated_data: &DisambiguatedDefPathData, disambiguated_data: &DisambiguatedDefPathData,
@@ -119,7 +119,7 @@ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
Ok(()) Ok(())
} }
fn path_generic_args( fn print_path_with_generic_args(
&mut self, &mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
args: &[GenericArg<'tcx>], args: &[GenericArg<'tcx>],
@@ -135,7 +135,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 { fn should_print_region(&self, _region: ty::Region<'_>) -> bool {
false false
} }
@@ -159,7 +159,7 @@ 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 { fn write_str(&mut self, s: &str) -> std::fmt::Result {
self.path.push_str(s); self.path.push_str(s);
Ok(()) Ok(())
@@ -167,7 +167,7 @@ impl Write for AbsolutePathPrinter<'_> {
} }
pub fn type_name<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> String { 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.print_type(ty).unwrap();
p.path p.path
} }

View File

@@ -745,12 +745,12 @@ impl<'tcx> LateContext<'tcx> {
/// } /// }
/// ``` /// ```
pub fn get_def_path(&self, def_id: DefId) -> Vec<Symbol> { pub fn get_def_path(&self, def_id: DefId) -> Vec<Symbol> {
struct AbsolutePathPrinter<'tcx> { struct LintPathPrinter<'tcx> {
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
path: Vec<Symbol>, path: Vec<Symbol>,
} }
impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> { impl<'tcx> Printer<'tcx> for LintPathPrinter<'tcx> {
fn tcx(&self) -> TyCtxt<'tcx> { fn tcx(&self) -> TyCtxt<'tcx> {
self.tcx self.tcx
} }
@@ -774,12 +774,12 @@ impl<'tcx> LateContext<'tcx> {
unreachable!(); // because `path_generic_args` ignores the `GenericArgs` 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)]; self.path = vec![self.tcx.crate_name(cnum)];
Ok(()) Ok(())
} }
fn path_qualified( fn print_path_with_qualified(
&mut self, &mut self,
self_ty: Ty<'tcx>, self_ty: Ty<'tcx>,
trait_ref: Option<ty::TraitRef<'tcx>>, trait_ref: Option<ty::TraitRef<'tcx>>,
@@ -800,7 +800,7 @@ impl<'tcx> LateContext<'tcx> {
}) })
} }
fn path_append_impl( fn print_path_with_impl(
&mut self, &mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
self_ty: Ty<'tcx>, self_ty: Ty<'tcx>,
@@ -825,7 +825,7 @@ impl<'tcx> LateContext<'tcx> {
Ok(()) Ok(())
} }
fn path_append( fn print_path_with_simple(
&mut self, &mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
disambiguated_data: &DisambiguatedDefPathData, disambiguated_data: &DisambiguatedDefPathData,
@@ -844,7 +844,7 @@ impl<'tcx> LateContext<'tcx> {
Ok(()) Ok(())
} }
fn path_generic_args( fn print_path_with_generic_args(
&mut self, &mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
_args: &[GenericArg<'tcx>], _args: &[GenericArg<'tcx>],
@@ -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.print_def_path(def_id, &[]).unwrap();
p.path p.path
} }

View File

@@ -1932,7 +1932,7 @@ fn pretty_print_const_value_tcx<'tcx>(
let args = tcx.lift(args).unwrap(); let args = tcx.lift(args).unwrap();
let mut p = FmtPrinter::new(tcx, Namespace::ValueNS); let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
p.print_alloc_ids = true; 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())?; fmt.write_str(&p.into_buffer())?;
match variant_def.ctor_kind() { match variant_def.ctor_kind() {
@@ -1974,7 +1974,7 @@ fn pretty_print_const_value_tcx<'tcx>(
(ConstValue::ZeroSized, ty::FnDef(d, s)) => { (ConstValue::ZeroSized, ty::FnDef(d, s)) => {
let mut p = FmtPrinter::new(tcx, Namespace::ValueNS); let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
p.print_alloc_ids = true; p.print_alloc_ids = true;
p.print_value_path(*d, s)?; p.pretty_print_value_path(*d, s)?;
fmt.write_str(&p.into_buffer())?; fmt.write_str(&p.into_buffer())?;
return Ok(()); return Ok(());
} }

View File

@@ -19,18 +19,16 @@ pub trait Print<'tcx, P> {
fn print(&self, p: &mut P) -> Result<(), PrintError>; fn print(&self, p: &mut P) -> Result<(), PrintError>;
} }
/// Interface for outputting user-facing "type-system entities" /// A trait that "prints" user-facing type system entities: paths, types, lifetimes, constants,
/// (paths, types, lifetimes, constants, etc.) as a side-effect /// etc. "Printing" here means building up a representation of the entity's path, usually as a
/// (e.g. formatting, like `PrettyPrinter` implementors do) or by /// `String` (e.g. "std::io::Read") or a `Vec<Symbol>` (e.g. `[sym::std, sym::io, sym::Read]`). The
/// constructing some alternative representation (e.g. an AST), /// representation is built up by appending one or more pieces. The specific details included in
/// which the associated types allow passing through the methods. /// the built-up representation depend on the purpose of the printer. The more advanced printers
/// /// also rely on the `PrettyPrinter` sub-trait.
/// For pretty-printing/formatting in particular, see `PrettyPrinter`.
//
// FIXME(eddyb) find a better name; this is more general than "printing".
pub trait Printer<'tcx>: Sized { pub trait Printer<'tcx>: Sized {
fn tcx<'a>(&'a self) -> TyCtxt<'tcx>; 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( fn print_def_path(
&mut self, &mut self,
def_id: DefId, def_id: DefId,
@@ -39,6 +37,7 @@ pub trait Printer<'tcx>: Sized {
self.default_print_def_path(def_id, args) self.default_print_def_path(def_id, args)
} }
/// Like `print_def_path`, but for `DefPathData::Impl`.
fn print_impl_path( fn print_impl_path(
&mut self, &mut self,
impl_def_id: DefId, impl_def_id: DefId,
@@ -64,47 +63,66 @@ pub trait Printer<'tcx>: Sized {
self.default_print_impl_path(impl_def_id, self_ty, impl_trait_ref) 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>; 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>; fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError>;
/// Appends a representation of a list of `PolyExistentialPredicate`s.
fn print_dyn_existential( fn print_dyn_existential(
&mut self, &mut self,
predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>, predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
) -> Result<(), PrintError>; ) -> Result<(), PrintError>;
/// Appends a representation of a const.
fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError>; 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`,
&mut self, /// when called, appends the representation of the leading segments. The rest of the method
self_ty: Ty<'tcx>, /// appends the representation of the final segment, the details of which are in
trait_ref: Option<ty::TraitRef<'tcx>>, /// `disambiguated_data`.
) -> Result<(), PrintError>; ///
/// E.g. `std::io` + `Read` -> `std::io::Read`.
fn path_append_impl( fn print_path_with_simple(
&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(
&mut self, &mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
disambiguated_data: &DisambiguatedDefPathData, disambiguated_data: &DisambiguatedDefPathData,
) -> Result<(), PrintError>; ) -> Result<(), PrintError>;
fn path_generic_args( /// 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>;
/// 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, &mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
args: &[GenericArg<'tcx>], args: &[GenericArg<'tcx>],
) -> Result<(), PrintError>; ) -> Result<(), PrintError>;
fn should_truncate(&mut self) -> bool { /// Appends a representation of a qualified path segment, e.g. `<OsString as From<&T>>`.
false /// 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,
self_ty: Ty<'tcx>,
trait_ref: Option<ty::TraitRef<'tcx>>,
) -> Result<(), PrintError>;
// Defaults (should not be overridden): // Defaults (should not be overridden):
@@ -120,7 +138,7 @@ pub trait Printer<'tcx>: Sized {
match key.disambiguated_data.data { match key.disambiguated_data.data {
DefPathData::CrateRoot => { DefPathData::CrateRoot => {
assert!(key.parent.is_none()); 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), DefPathData::Impl => self.print_impl_path(def_id, args),
@@ -144,7 +162,7 @@ pub trait Printer<'tcx>: Sized {
)) = self.tcx().coroutine_kind(def_id) )) = self.tcx().coroutine_kind(def_id)
&& args.len() > parent_args.len() && 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), |p| p.print_def_path(def_id, parent_args),
&args[..parent_args.len() + 1][..1], &args[..parent_args.len() + 1][..1],
); );
@@ -166,7 +184,7 @@ pub trait Printer<'tcx>: Sized {
_ => { _ => {
if !generics.is_own_empty() && args.len() >= generics.count() { if !generics.is_own_empty() && args.len() >= generics.count() {
let args = generics.own_args_no_defaults(self.tcx(), args); 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), |p| p.print_def_path(def_id, parent_args),
args, args,
); );
@@ -182,7 +200,7 @@ pub trait Printer<'tcx>: Sized {
&& self.tcx().generics_of(parent_def_id).parent_count == 0; && self.tcx().generics_of(parent_def_id).parent_count == 0;
} }
self.path_append( self.print_path_with_simple(
|p: &mut Self| { |p: &mut Self| {
if trait_qualify_parent { if trait_qualify_parent {
let trait_ref = ty::TraitRef::new( let trait_ref = ty::TraitRef::new(
@@ -190,7 +208,7 @@ pub trait Printer<'tcx>: Sized {
parent_def_id, parent_def_id,
parent_args.iter().copied(), 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 { } else {
p.print_def_path(parent_def_id, parent_args) p.print_def_path(parent_def_id, parent_args)
} }
@@ -233,11 +251,15 @@ pub trait Printer<'tcx>: Sized {
// If the impl is not co-located with either self-type or // If the impl is not co-located with either self-type or
// trait-type, then fallback to a format that identifies // trait-type, then fallback to a format that identifies
// the module more clearly. // 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 { } else {
// Otherwise, try to give a good form that would be valid language // Otherwise, try to give a good form that would be valid language
// syntax. Preferably using associated item notation. // syntax. Preferably using associated item notation.
self.path_qualified(self_ty, impl_trait_ref) self.print_path_with_qualified(self_ty, impl_trait_ref)
} }
} }
} }

View File

@@ -245,7 +245,7 @@ impl<'tcx> RegionHighlightMode<'tcx> {
/// Trait for printers that pretty-print using `fmt::Write` to the printer. /// Trait for printers that pretty-print using `fmt::Write` to the printer.
pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
/// Like `print_def_path` but for value paths. /// Like `print_def_path` but for value paths.
fn print_value_path( fn pretty_print_value_path(
&mut self, &mut self,
def_id: DefId, def_id: DefId,
args: &'tcx [GenericArg<'tcx>], args: &'tcx [GenericArg<'tcx>],
@@ -253,7 +253,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
self.print_def_path(def_id, args) self.print_def_path(def_id, args)
} }
fn print_in_binder<T>(&mut self, value: &ty::Binder<'tcx, T>) -> Result<(), PrintError> fn pretty_print_in_binder<T>(&mut self, value: &ty::Binder<'tcx, T>) -> Result<(), PrintError>
where where
T: Print<'tcx, Self> + TypeFoldable<TyCtxt<'tcx>>, T: Print<'tcx, Self> + TypeFoldable<TyCtxt<'tcx>>,
{ {
@@ -333,6 +333,10 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
f: impl FnOnce(&mut Self) -> Result<(), PrintError>, f: impl FnOnce(&mut Self) -> Result<(), PrintError>,
) -> Result<(), PrintError>; ) -> Result<(), PrintError>;
fn should_truncate(&mut self) -> bool {
false
}
/// Returns `true` if the region should be printed in /// Returns `true` if the region should be printed in
/// optional positions, e.g., `&'a T` or `dyn Tr + 'b`. /// optional positions, e.g., `&'a T` or `dyn Tr + 'b`.
/// This is typically the case for all non-`'_` regions. /// This is typically the case for all non-`'_` regions.
@@ -470,7 +474,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
// path to the crate followed by the path to the item within the crate. // path to the crate followed by the path to the item within the crate.
if let Some(cnum) = def_id.as_crate_root() { if let Some(cnum) = def_id.as_crate_root() {
if cnum == LOCAL_CRATE { if cnum == LOCAL_CRATE {
self.path_crate(cnum)?; self.print_crate_name(cnum)?;
return Ok(true); return Ok(true);
} }
@@ -494,7 +498,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
// or avoid ending up with `ExternCrateSource::Extern`, // or avoid ending up with `ExternCrateSource::Extern`,
// for the injected `std`/`core`. // for the injected `std`/`core`.
if span.is_dummy() { if span.is_dummy() {
self.path_crate(cnum)?; self.print_crate_name(cnum)?;
return Ok(true); return Ok(true);
} }
@@ -508,13 +512,13 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
return Ok(true); return Ok(true);
} }
(ExternCrateSource::Path, LOCAL_CRATE) => { (ExternCrateSource::Path, LOCAL_CRATE) => {
self.path_crate(cnum)?; self.print_crate_name(cnum)?;
return Ok(true); return Ok(true);
} }
_ => {} _ => {}
}, },
None => { None => {
self.path_crate(cnum)?; self.print_crate_name(cnum)?;
return Ok(true); return Ok(true);
} }
} }
@@ -624,7 +628,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
return Ok(false); return Ok(false);
} }
callers.push(visible_parent); callers.push(visible_parent);
// HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid // HACK(eddyb) this bypasses `print_path_with_simple`'s prefix printing to avoid
// knowing ahead of time whether the entire path will succeed or not. // knowing ahead of time whether the entire path will succeed or not.
// To support printers that do not implement `PrettyPrinter`, a `Vec` or // To support printers that do not implement `PrettyPrinter`, a `Vec` or
// linked list on the stack would need to be built, before any printing. // linked list on the stack would need to be built, before any printing.
@@ -633,11 +637,14 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
true => {} true => {}
} }
callers.pop(); callers.pop();
self.path_append(|_| Ok(()), &DisambiguatedDefPathData { data, disambiguator: 0 })?; self.print_path_with_simple(
|_| Ok(()),
&DisambiguatedDefPathData { data, disambiguator: 0 },
)?;
Ok(true) Ok(true)
} }
fn pretty_path_qualified( fn pretty_print_path_with_qualified(
&mut self, &mut self,
self_ty: Ty<'tcx>, self_ty: Ty<'tcx>,
trait_ref: Option<ty::TraitRef<'tcx>>, trait_ref: Option<ty::TraitRef<'tcx>>,
@@ -672,7 +679,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
}) })
} }
fn pretty_path_append_impl( fn pretty_print_path_with_impl(
&mut self, &mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
self_ty: Ty<'tcx>, self_ty: Ty<'tcx>,
@@ -739,7 +746,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
} }
sig.print(self)?; sig.print(self)?;
write!(self, " {{")?; write!(self, " {{")?;
self.print_value_path(def_id, args)?; self.pretty_print_value_path(def_id, args)?;
write!(self, "}}")?; write!(self, "}}")?;
} }
} }
@@ -1308,10 +1315,10 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
alias_ty: ty::AliasTerm<'tcx>, alias_ty: ty::AliasTerm<'tcx>,
) -> Result<(), PrintError> { ) -> Result<(), PrintError> {
let def_key = self.tcx().def_key(alias_ty.def_id); let def_key = self.tcx().def_key(alias_ty.def_id);
self.path_generic_args( self.print_path_with_generic_args(
|p| { |p| {
p.path_append( p.print_path_with_simple(
|p| p.path_qualified(alias_ty.self_ty(), None), |p| p.print_path_with_qualified(alias_ty.self_ty(), None),
&def_key.disambiguated_data, &def_key.disambiguated_data,
) )
}, },
@@ -1386,7 +1393,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
if let ty::Tuple(tys) = principal.args.type_at(0).kind() { if let ty::Tuple(tys) = principal.args.type_at(0).kind() {
let mut projections = predicates.projection_bounds(); let mut projections = predicates.projection_bounds();
if let (Some(proj), None) = (projections.next(), projections.next()) { if let (Some(proj), None) = (projections.next(), projections.next()) {
p.pretty_fn_sig( p.pretty_print_fn_sig(
tys, tys,
false, 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"),
@@ -1396,7 +1403,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
} }
} }
// HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`, // HACK(eddyb) this duplicates `FmtPrinter`'s `print_path_with_generic_args`,
// in order to place the projections inside the `<...>`. // in order to place the projections inside the `<...>`.
if !resugared { if !resugared {
let principal_with_self = let principal_with_self =
@@ -1488,7 +1495,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
Ok(()) Ok(())
} }
fn pretty_fn_sig( fn pretty_print_fn_sig(
&mut self, &mut self,
inputs: &[Ty<'tcx>], inputs: &[Ty<'tcx>],
c_variadic: bool, c_variadic: bool,
@@ -1525,7 +1532,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, args }) => { ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, args }) => {
match self.tcx().def_kind(def) { match self.tcx().def_kind(def) {
DefKind::Const | DefKind::AssocConst => { DefKind::Const | DefKind::AssocConst => {
self.print_value_path(def, args)?; self.pretty_print_value_path(def, args)?;
} }
DefKind::AnonConst => { DefKind::AnonConst => {
if def.is_local() if def.is_local()
@@ -1534,13 +1541,13 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
{ {
write!(self, "{snip}")?; write!(self, "{snip}")?;
} else { } else {
// Do not call `print_value_path` as if a parent of this anon const is // Do not call `pretty_print_value_path` as if a parent of this anon
// an impl it will attempt to print out the impl trait ref i.e. `<T as // const is an impl it will attempt to print out the impl trait ref
// Trait>::{constant#0}`. This would cause printing to enter an // i.e. `<T as Trait>::{constant#0}`. This would cause printing to
// infinite recursion if the anon const is in the self type i.e. // enter an infinite recursion if the anon const is in the self type
// `impl<T: Default> Default for [T; 32 - 1 - 1 - 1] {` where we would // i.e. `impl<T: Default> Default for [T; 32 - 1 - 1 - 1] {` where we
// try to print // would try to print `<[T; /* print constant#0 again */] as //
// `<[T; /* print constant#0 again */] as // Default>::{constant#0}`. // Default>::{constant#0}`.
write!( write!(
self, self,
"{}::{}", "{}::{}",
@@ -1742,7 +1749,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
self.tcx().try_get_global_alloc(prov.alloc_id()) self.tcx().try_get_global_alloc(prov.alloc_id())
{ {
self.typed_value( self.typed_value(
|this| this.print_value_path(instance.def_id(), instance.args), |this| this.pretty_print_value_path(instance.def_id(), instance.args),
|this| this.print_type(ty), |this| this.print_type(ty),
" as ", " as ",
)?; )?;
@@ -1936,7 +1943,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
let variant_idx = let variant_idx =
contents.variant.expect("destructed const of adt without variant idx"); contents.variant.expect("destructed const of adt without variant idx");
let variant_def = &def.variant(variant_idx); let variant_def = &def.variant(variant_idx);
self.print_value_path(variant_def.def_id, args)?; self.pretty_print_value_path(variant_def.def_id, args)?;
match variant_def.ctor_kind() { match variant_def.ctor_kind() {
Some(CtorKind::Const) => {} Some(CtorKind::Const) => {}
Some(CtorKind::Fn) => { Some(CtorKind::Fn) => {
@@ -1972,7 +1979,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
} }
(_, ty::FnDef(def_id, args)) => { (_, ty::FnDef(def_id, args)) => {
// Never allowed today, but we still encounter them in invalid const args. // Never allowed today, but we still encounter them in invalid const args.
self.print_value_path(def_id, args)?; self.pretty_print_value_path(def_id, args)?;
return Ok(()); return Ok(());
} }
// FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
@@ -1993,7 +2000,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
Ok(()) Ok(())
} }
fn pretty_closure_as_impl( fn pretty_print_closure_as_impl(
&mut self, &mut self,
closure: ty::ClosureArgs<TyCtxt<'tcx>>, closure: ty::ClosureArgs<TyCtxt<'tcx>>,
) -> Result<(), PrintError> { ) -> Result<(), PrintError> {
@@ -2131,8 +2138,6 @@ impl<'a, 'tcx> FmtPrinter<'a, 'tcx> {
} }
} }
// HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
// (but also some things just print a `DefId` generally so maybe we need this?)
fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace { fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
match tcx.def_key(def_id).disambiguated_data.data { match tcx.def_key(def_id).disambiguated_data.data {
DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::OpaqueTy => { DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::OpaqueTy => {
@@ -2157,6 +2162,7 @@ impl<'t> TyCtxt<'t> {
self.def_path_str_with_args(def_id, &[]) self.def_path_str_with_args(def_id, &[])
} }
/// For this one we determine the appropriate namespace for the `def_id`.
pub fn def_path_str_with_args( pub fn def_path_str_with_args(
self, self,
def_id: impl IntoQueryParam<DefId>, def_id: impl IntoQueryParam<DefId>,
@@ -2169,16 +2175,17 @@ impl<'t> TyCtxt<'t> {
FmtPrinter::print_string(self, ns, |p| p.print_def_path(def_id, args)).unwrap() FmtPrinter::print_string(self, ns, |p| p.print_def_path(def_id, args)).unwrap()
} }
/// For this one we always use value namespace.
pub fn value_path_str_with_args( pub fn value_path_str_with_args(
self, self,
def_id: impl IntoQueryParam<DefId>, def_id: impl IntoQueryParam<DefId>,
args: &'t [GenericArg<'t>], args: &'t [GenericArg<'t>],
) -> String { ) -> String {
let def_id = def_id.into_query_param(); let def_id = def_id.into_query_param();
let ns = guess_def_namespace(self, def_id); let ns = Namespace::ValueNS;
debug!("value_path_str: def_id={:?}, ns={:?}", def_id, ns); debug!("value_path_str: def_id={:?}, ns={:?}", def_id, ns);
FmtPrinter::print_string(self, ns, |p| p.print_value_path(def_id, args)).unwrap() FmtPrinter::print_string(self, ns, |p| p.print_def_path(def_id, args)).unwrap()
} }
} }
@@ -2230,7 +2237,7 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> {
self.print_def_path(parent_def_id, &[])?; self.print_def_path(parent_def_id, &[])?;
// HACK(eddyb) copy of `path_append` to avoid // HACK(eddyb) copy of `print_path_with_simple` to avoid
// constructing a `DisambiguatedDefPathData`. // constructing a `DisambiguatedDefPathData`.
if !self.empty_path { if !self.empty_path {
write!(self, "::")?; write!(self, "::")?;
@@ -2295,10 +2302,6 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> {
} }
} }
fn should_truncate(&mut self) -> bool {
!self.type_length_limit.value_within_limit(self.printed_type_count)
}
fn print_dyn_existential( fn print_dyn_existential(
&mut self, &mut self,
predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>, predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
@@ -2310,7 +2313,7 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> {
self.pretty_print_const(ct, false) self.pretty_print_const(ct, false)
} }
fn path_crate(&mut self, cnum: CrateNum) -> Result<(), PrintError> { fn print_crate_name(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
self.empty_path = true; self.empty_path = true;
if cnum == LOCAL_CRATE { if cnum == LOCAL_CRATE {
if self.tcx.sess.at_least_rust_2018() { if self.tcx.sess.at_least_rust_2018() {
@@ -2327,23 +2330,23 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> {
Ok(()) Ok(())
} }
fn path_qualified( fn print_path_with_qualified(
&mut self, &mut self,
self_ty: Ty<'tcx>, self_ty: Ty<'tcx>,
trait_ref: Option<ty::TraitRef<'tcx>>, trait_ref: Option<ty::TraitRef<'tcx>>,
) -> Result<(), PrintError> { ) -> Result<(), PrintError> {
self.pretty_path_qualified(self_ty, trait_ref)?; self.pretty_print_path_with_qualified(self_ty, trait_ref)?;
self.empty_path = false; self.empty_path = false;
Ok(()) Ok(())
} }
fn path_append_impl( fn print_path_with_impl(
&mut self, &mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
self_ty: Ty<'tcx>, self_ty: Ty<'tcx>,
trait_ref: Option<ty::TraitRef<'tcx>>, trait_ref: Option<ty::TraitRef<'tcx>>,
) -> Result<(), PrintError> { ) -> Result<(), PrintError> {
self.pretty_path_append_impl( self.pretty_print_path_with_impl(
|p| { |p| {
print_prefix(p)?; print_prefix(p)?;
if !p.empty_path { if !p.empty_path {
@@ -2359,7 +2362,7 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> {
Ok(()) Ok(())
} }
fn path_append( fn print_path_with_simple(
&mut self, &mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
disambiguated_data: &DisambiguatedDefPathData, disambiguated_data: &DisambiguatedDefPathData,
@@ -2390,7 +2393,7 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> {
Ok(()) Ok(())
} }
fn path_generic_args( fn print_path_with_generic_args(
&mut self, &mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
args: &[GenericArg<'tcx>], args: &[GenericArg<'tcx>],
@@ -2421,7 +2424,7 @@ impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> {
self.0.const_infer_name_resolver.as_ref().and_then(|func| func(id)) self.0.const_infer_name_resolver.as_ref().and_then(|func| func(id))
} }
fn print_value_path( fn pretty_print_value_path(
&mut self, &mut self,
def_id: DefId, def_id: DefId,
args: &'tcx [GenericArg<'tcx>], args: &'tcx [GenericArg<'tcx>],
@@ -2433,7 +2436,7 @@ impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> {
Ok(()) Ok(())
} }
fn print_in_binder<T>(&mut self, value: &ty::Binder<'tcx, T>) -> Result<(), PrintError> fn pretty_print_in_binder<T>(&mut self, value: &ty::Binder<'tcx, T>) -> Result<(), PrintError>
where where
T: Print<'tcx, Self> + TypeFoldable<TyCtxt<'tcx>>, T: Print<'tcx, Self> + TypeFoldable<TyCtxt<'tcx>>,
{ {
@@ -2487,6 +2490,10 @@ impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> {
Ok(()) Ok(())
} }
fn should_truncate(&mut self) -> bool {
!self.type_length_limit.value_within_limit(self.printed_type_count)
}
fn should_print_region(&self, region: ty::Region<'tcx>) -> bool { fn should_print_region(&self, region: ty::Region<'tcx>) -> bool {
let highlight = self.region_highlight_mode; let highlight = self.region_highlight_mode;
if highlight.region_highlighted(region).is_some() { if highlight.region_highlighted(region).is_some() {
@@ -2892,7 +2899,7 @@ where
T: Print<'tcx, P> + TypeFoldable<TyCtxt<'tcx>>, T: Print<'tcx, P> + TypeFoldable<TyCtxt<'tcx>>,
{ {
fn print(&self, p: &mut P) -> Result<(), PrintError> { fn print(&self, p: &mut P) -> Result<(), PrintError> {
p.print_in_binder(self) p.pretty_print_in_binder(self)
} }
} }
@@ -3090,7 +3097,7 @@ define_print! {
} }
write!(p, "fn")?; write!(p, "fn")?;
p.pretty_fn_sig(self.inputs(), self.c_variadic, self.output())?; p.pretty_print_fn_sig(self.inputs(), self.c_variadic, self.output())?;
} }
ty::TraitRef<'tcx> { ty::TraitRef<'tcx> {
@@ -3225,7 +3232,7 @@ define_print! {
// The args don't contain the self ty (as it has been erased) but the corresp. // 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. // generics do as the trait always has a self ty param. We need to offset.
let args = &self.args[p.tcx().generics_of(self.def_id).parent_count - 1..]; let args = &self.args[p.tcx().generics_of(self.def_id).parent_count - 1..];
p.path_generic_args(|p| write!(p, "{name}"), args)?; p.print_path_with_generic_args(|p| write!(p, "{name}"), args)?;
write!(p, " = ")?; write!(p, " = ")?;
self.term.print(p)?; self.term.print(p)?;
} }
@@ -3314,7 +3321,7 @@ define_print_and_forward_display! {
} }
PrintClosureAsImpl<'tcx> { PrintClosureAsImpl<'tcx> {
p.pretty_closure_as_impl(self.closure)?; p.pretty_print_closure_as_impl(self.closure)?;
} }
ty::ParamTy { ty::ParamTy {

View File

@@ -58,7 +58,7 @@ pub(super) fn mangle<'tcx>(
let hash = get_symbol_hash(tcx, instance, instance_ty, instantiating_crate); let hash = get_symbol_hash(tcx, instance, instance_ty, instantiating_crate);
let mut p = SymbolPrinter { tcx, path: SymbolPath::new(), keep_within_component: false }; let mut p = LegacySymbolMangler { tcx, path: SymbolPath::new(), keep_within_component: false };
p.print_def_path( p.print_def_path(
def_id, def_id,
if let ty::InstanceKind::DropGlue(_, _) if let ty::InstanceKind::DropGlue(_, _)
@@ -213,13 +213,13 @@ impl SymbolPath {
} }
} }
struct SymbolPrinter<'tcx> { struct LegacySymbolMangler<'tcx> {
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
path: SymbolPath, path: SymbolPath,
// When `true`, `finalize_pending_component` isn't used. // When `true`, `finalize_pending_component` isn't used.
// This is needed when recursing into `path_qualified`, // This is needed when recursing into `print_path_with_qualified`,
// or `path_generic_args`, as any nested paths are // or `print_path_with_generic_args`, as any nested paths are
// logically within one component. // logically within one component.
keep_within_component: bool, keep_within_component: bool,
} }
@@ -228,7 +228,7 @@ struct SymbolPrinter<'tcx> {
// `PrettyPrinter` aka pretty printing of e.g. types in paths, // `PrettyPrinter` aka pretty printing of e.g. types in paths,
// symbol names should have their own printing machinery. // symbol names should have their own printing machinery.
impl<'tcx> Printer<'tcx> for SymbolPrinter<'tcx> { impl<'tcx> Printer<'tcx> for LegacySymbolMangler<'tcx> {
fn tcx(&self) -> TyCtxt<'tcx> { fn tcx(&self) -> TyCtxt<'tcx> {
self.tcx self.tcx
} }
@@ -305,16 +305,17 @@ impl<'tcx> Printer<'tcx> for SymbolPrinter<'tcx> {
Ok(()) Ok(())
} }
fn path_crate(&mut self, cnum: CrateNum) -> Result<(), PrintError> { fn print_crate_name(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
self.write_str(self.tcx.crate_name(cnum).as_str())?; self.write_str(self.tcx.crate_name(cnum).as_str())?;
Ok(()) Ok(())
} }
fn path_qualified(
fn print_path_with_qualified(
&mut self, &mut self,
self_ty: Ty<'tcx>, self_ty: Ty<'tcx>,
trait_ref: Option<ty::TraitRef<'tcx>>, trait_ref: Option<ty::TraitRef<'tcx>>,
) -> Result<(), PrintError> { ) -> Result<(), PrintError> {
// Similar to `pretty_path_qualified`, but for the other // Similar to `pretty_print_path_with_qualified`, but for the other
// types that are printed as paths (see `print_type` above). // types that are printed as paths (see `print_type` above).
match self_ty.kind() { match self_ty.kind() {
ty::FnDef(..) ty::FnDef(..)
@@ -327,17 +328,17 @@ impl<'tcx> Printer<'tcx> for SymbolPrinter<'tcx> {
self.print_type(self_ty) self.print_type(self_ty)
} }
_ => 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, &mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
self_ty: Ty<'tcx>, self_ty: Ty<'tcx>,
trait_ref: Option<ty::TraitRef<'tcx>>, trait_ref: Option<ty::TraitRef<'tcx>>,
) -> Result<(), PrintError> { ) -> Result<(), PrintError> {
self.pretty_path_append_impl( self.pretty_print_path_with_impl(
|cx| { |cx| {
print_prefix(cx)?; print_prefix(cx)?;
@@ -354,7 +355,8 @@ impl<'tcx> Printer<'tcx> for SymbolPrinter<'tcx> {
trait_ref, trait_ref,
) )
} }
fn path_append(
fn print_path_with_simple(
&mut self, &mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
disambiguated_data: &DisambiguatedDefPathData, disambiguated_data: &DisambiguatedDefPathData,
@@ -377,7 +379,8 @@ impl<'tcx> Printer<'tcx> for SymbolPrinter<'tcx> {
Ok(()) Ok(())
} }
fn path_generic_args(
fn print_path_with_generic_args(
&mut self, &mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
args: &[GenericArg<'tcx>], args: &[GenericArg<'tcx>],
@@ -455,7 +458,7 @@ impl<'tcx> Printer<'tcx> for SymbolPrinter<'tcx> {
} }
} }
impl<'tcx> PrettyPrinter<'tcx> for SymbolPrinter<'tcx> { impl<'tcx> PrettyPrinter<'tcx> for LegacySymbolMangler<'tcx> {
fn should_print_region(&self, _region: ty::Region<'_>) -> bool { fn should_print_region(&self, _region: ty::Region<'_>) -> bool {
false false
} }
@@ -491,7 +494,7 @@ impl<'tcx> PrettyPrinter<'tcx> for SymbolPrinter<'tcx> {
} }
} }
impl fmt::Write for SymbolPrinter<'_> { impl fmt::Write for LegacySymbolMangler<'_> {
fn write_str(&mut self, s: &str) -> fmt::Result { fn write_str(&mut self, s: &str) -> fmt::Result {
// Name sanitation. LLVM will happily accept identifiers with weird names, but // Name sanitation. LLVM will happily accept identifiers with weird names, but
// gas doesn't! // gas doesn't!

View File

@@ -33,7 +33,7 @@ pub(super) fn mangle<'tcx>(
let args = tcx.normalize_erasing_regions(ty::TypingEnv::fully_monomorphized(), instance.args); let args = tcx.normalize_erasing_regions(ty::TypingEnv::fully_monomorphized(), instance.args);
let prefix = "_R"; let prefix = "_R";
let mut p: SymbolMangler<'_> = SymbolMangler { let mut p: V0SymbolMangler<'_> = V0SymbolMangler {
tcx, tcx,
start_offset: prefix.len(), start_offset: prefix.len(),
is_exportable, is_exportable,
@@ -88,7 +88,7 @@ pub fn mangle_internal_symbol<'tcx>(tcx: TyCtxt<'tcx>, item_name: &str) -> Strin
} }
let prefix = "_R"; let prefix = "_R";
let mut p: SymbolMangler<'_> = SymbolMangler { let mut p: V0SymbolMangler<'_> = V0SymbolMangler {
tcx, tcx,
start_offset: prefix.len(), start_offset: prefix.len(),
is_exportable: false, is_exportable: false,
@@ -131,7 +131,7 @@ pub(super) fn mangle_typeid_for_trait_ref<'tcx>(
trait_ref: ty::ExistentialTraitRef<'tcx>, trait_ref: ty::ExistentialTraitRef<'tcx>,
) -> String { ) -> String {
// FIXME(flip1995): See comment in `mangle_typeid_for_fnabi`. // FIXME(flip1995): See comment in `mangle_typeid_for_fnabi`.
let mut p = SymbolMangler { let mut p = V0SymbolMangler {
tcx, tcx,
start_offset: 0, start_offset: 0,
is_exportable: false, is_exportable: false,
@@ -159,7 +159,7 @@ struct BinderLevel {
lifetime_depths: Range<u32>, lifetime_depths: Range<u32>,
} }
struct SymbolMangler<'tcx> { struct V0SymbolMangler<'tcx> {
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
binders: Vec<BinderLevel>, binders: Vec<BinderLevel>,
out: String, out: String,
@@ -173,7 +173,7 @@ struct SymbolMangler<'tcx> {
consts: FxHashMap<ty::Const<'tcx>, usize>, consts: FxHashMap<ty::Const<'tcx>, usize>,
} }
impl<'tcx> SymbolMangler<'tcx> { impl<'tcx> V0SymbolMangler<'tcx> {
fn push(&mut self, s: &str) { fn push(&mut self, s: &str) {
self.out.push_str(s); self.out.push_str(s);
} }
@@ -272,7 +272,7 @@ impl<'tcx> SymbolMangler<'tcx> {
} }
} }
impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> { impl<'tcx> Printer<'tcx> for V0SymbolMangler<'tcx> {
fn tcx(&self) -> TyCtxt<'tcx> { fn tcx(&self) -> TyCtxt<'tcx> {
self.tcx self.tcx
} }
@@ -365,7 +365,7 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> {
// Encode impl generic params if the generic parameters contain non-region parameters // Encode impl generic params if the generic parameters contain non-region parameters
// and this isn't an inherent impl. // and this isn't an inherent impl.
if impl_trait_ref.is_some() && args.iter().any(|a| a.has_non_region_param()) { if impl_trait_ref.is_some() && args.iter().any(|a| a.has_non_region_param()) {
self.path_generic_args( self.print_path_with_generic_args(
|this| { |this| {
this.path_append_ns( this.path_append_ns(
|p| p.print_def_path(parent_def_id, &[]), |p| p.print_def_path(parent_def_id, &[]),
@@ -786,7 +786,7 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> {
None => { None => {
self.push("S"); self.push("S");
for (field_def, field) in iter::zip(&variant_def.fields, fields) { for (field_def, field) in iter::zip(&variant_def.fields, fields) {
// HACK(eddyb) this mimics `path_append`, // HACK(eddyb) this mimics `print_path_with_simple`,
// instead of simply using `field_def.ident`, // instead of simply using `field_def.ident`,
// just to be able to handle disambiguators. // just to be able to handle disambiguators.
let disambiguated_field = let disambiguated_field =
@@ -819,7 +819,7 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> {
Ok(()) Ok(())
} }
fn path_crate(&mut self, cnum: CrateNum) -> Result<(), PrintError> { fn print_crate_name(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
self.push("C"); self.push("C");
if !self.is_exportable { if !self.is_exportable {
let stable_crate_id = self.tcx.def_path_hash(cnum.as_def_id()).stable_crate_id(); let stable_crate_id = self.tcx.def_path_hash(cnum.as_def_id()).stable_crate_id();
@@ -830,7 +830,7 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> {
Ok(()) Ok(())
} }
fn path_qualified( fn print_path_with_qualified(
&mut self, &mut self,
self_ty: Ty<'tcx>, self_ty: Ty<'tcx>,
trait_ref: Option<ty::TraitRef<'tcx>>, trait_ref: Option<ty::TraitRef<'tcx>>,
@@ -843,7 +843,7 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> {
self.print_def_path(trait_ref.def_id, trait_ref.args) self.print_def_path(trait_ref.def_id, trait_ref.args)
} }
fn path_append_impl( fn print_path_with_impl(
&mut self, &mut self,
_: impl FnOnce(&mut Self) -> Result<(), PrintError>, _: impl FnOnce(&mut Self) -> Result<(), PrintError>,
_: Ty<'tcx>, _: Ty<'tcx>,
@@ -853,7 +853,7 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> {
unreachable!() unreachable!()
} }
fn path_append( fn print_path_with_simple(
&mut self, &mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
disambiguated_data: &DisambiguatedDefPathData, disambiguated_data: &DisambiguatedDefPathData,
@@ -873,7 +873,7 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> {
DefPathData::SyntheticCoroutineBody => 's', DefPathData::SyntheticCoroutineBody => 's',
DefPathData::NestedStatic => 'n', DefPathData::NestedStatic => 'n',
// These should never show up as `path_append` arguments. // These should never show up as `print_path_with_simple` arguments.
DefPathData::CrateRoot DefPathData::CrateRoot
| DefPathData::Use | DefPathData::Use
| DefPathData::GlobalAsm | DefPathData::GlobalAsm
@@ -896,7 +896,7 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> {
) )
} }
fn path_generic_args( fn print_path_with_generic_args(
&mut self, &mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
args: &[GenericArg<'tcx>], args: &[GenericArg<'tcx>],

View File

@@ -224,12 +224,12 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
use ty::GenericArg; use ty::GenericArg;
use ty::print::Printer; use ty::print::Printer;
struct AbsolutePathPrinter<'tcx> { struct ConflictingPathPrinter<'tcx> {
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
segments: Vec<Symbol>, segments: Vec<Symbol>,
} }
impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> { impl<'tcx> Printer<'tcx> for ConflictingPathPrinter<'tcx> {
fn tcx<'a>(&'a self) -> TyCtxt<'tcx> { fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
self.tcx self.tcx
} }
@@ -253,12 +253,12 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
unreachable!(); // because `path_generic_args` ignores the `GenericArgs` 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.segments = vec![self.tcx.crate_name(cnum)]; self.segments = vec![self.tcx.crate_name(cnum)];
Ok(()) Ok(())
} }
fn path_qualified( fn print_path_with_qualified(
&mut self, &mut self,
_self_ty: Ty<'tcx>, _self_ty: Ty<'tcx>,
_trait_ref: Option<ty::TraitRef<'tcx>>, _trait_ref: Option<ty::TraitRef<'tcx>>,
@@ -266,7 +266,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
Err(fmt::Error) Err(fmt::Error)
} }
fn path_append_impl( fn print_path_with_impl(
&mut self, &mut self,
_print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, _print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
_self_ty: Ty<'tcx>, _self_ty: Ty<'tcx>,
@@ -275,7 +275,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
Err(fmt::Error) Err(fmt::Error)
} }
fn path_append( fn print_path_with_simple(
&mut self, &mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
disambiguated_data: &DisambiguatedDefPathData, disambiguated_data: &DisambiguatedDefPathData,
@@ -285,7 +285,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
Ok(()) Ok(())
} }
fn path_generic_args( fn print_path_with_generic_args(
&mut self, &mut self,
print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
_args: &[GenericArg<'tcx>], _args: &[GenericArg<'tcx>],
@@ -300,19 +300,18 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
// let _ = [{struct Foo; Foo}, {struct Foo; Foo}]; // let _ = [{struct Foo; Foo}, {struct Foo; Foo}];
if did1.krate != did2.krate { if did1.krate != did2.krate {
let abs_path = |def_id| { let abs_path = |def_id| {
let mut p = AbsolutePathPrinter { tcx: self.tcx, segments: vec![] }; let mut p = ConflictingPathPrinter { tcx: self.tcx, segments: vec![] };
p.print_def_path(def_id, &[]).map(|_| p.segments) p.print_def_path(def_id, &[]).map(|_| p.segments)
}; };
// We compare strings because DefPath can be different // We compare strings because DefPath can be different for imported and
// for imported and non-imported crates // non-imported crates.
let expected_str = self.tcx.def_path_str(did1); let expected_str = self.tcx.def_path_str(did1);
let found_str = self.tcx.def_path_str(did2); let found_str = self.tcx.def_path_str(did2);
let Ok(expected_abs) = abs_path(did1) else { return false }; let Ok(expected_abs) = abs_path(did1) else { return false };
let Ok(found_abs) = abs_path(did2) else { return false }; let Ok(found_abs) = abs_path(did2) else { return false };
let same_path = || -> Result<_, PrintError> { let same_path = expected_str == found_str || expected_abs == found_abs;
Ok(expected_str == found_str || expected_abs == found_abs) if same_path {
};
// We want to use as unique a type path as possible. If both types are "locally // We want to use as unique a type path as possible. If both types are "locally
// known" by the same name, we use the "absolute path" which uses the original // known" by the same name, we use the "absolute path" which uses the original
// crate name instead. // crate name instead.
@@ -321,7 +320,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
} else { } else {
(expected_str.clone(), found_str.clone()) (expected_str.clone(), found_str.clone())
}; };
if same_path().unwrap_or(false) {
// We've displayed "expected `a::b`, found `a::b`". We add context to // We've displayed "expected `a::b`, found `a::b`". We add context to
// differentiate the different cases where that might happen. // differentiate the different cases where that might happen.
let expected_crate_name = self.tcx.crate_name(did1.krate); let expected_crate_name = self.tcx.crate_name(did1.krate);

View File

@@ -946,7 +946,7 @@ fn foo(&self) -> Self::T { String::new() }
pub fn format_generic_args(&self, args: &[ty::GenericArg<'tcx>]) -> String { pub fn format_generic_args(&self, args: &[ty::GenericArg<'tcx>]) -> String {
FmtPrinter::print_string(self.tcx, hir::def::Namespace::TypeNS, |p| { FmtPrinter::print_string(self.tcx, hir::def::Namespace::TypeNS, |p| {
p.path_generic_args(|_| Ok(()), args) p.print_path_with_generic_args(|_| Ok(()), args)
}) })
.expect("could not write to `String`.") .expect("could not write to `String`.")
} }