1 use crate::mir::interpret::{AllocRange, GlobalAlloc, Pointer, Provenance, Scalar};
2 use crate::ty::subst::{GenericArg, GenericArgKind, Subst};
4 self, ConstInt, DefIdTree, ParamConst, ScalarInt, Term, Ty, TyCtxt, TypeFoldable,
5 TypeSuperFoldable, TypeSuperVisitable, TypeVisitable,
7 use rustc_apfloat::ieee::{Double, Single};
8 use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
9 use rustc_data_structures::sso::SsoHashSet;
11 use rustc_hir::def::{self, CtorKind, DefKind, Namespace};
12 use rustc_hir::def_id::{DefId, DefIdSet, CRATE_DEF_ID, LOCAL_CRATE};
13 use rustc_hir::definitions::{DefPathData, DefPathDataName, DisambiguatedDefPathData};
14 use rustc_session::config::TrimmedDefPaths;
15 use rustc_session::cstore::{ExternCrate, ExternCrateSource};
16 use rustc_span::symbol::{kw, Ident, Symbol};
17 use rustc_target::abi::Size;
18 use rustc_target::spec::abi::Abi;
22 use std::collections::BTreeMap;
23 use std::convert::TryFrom;
24 use std::fmt::{self, Write as _};
26 use std::ops::{ControlFlow, Deref, DerefMut};
28 // `pretty` is a separate module only for organization.
33 write!(scoped_cx!(), $lit)?
35 (@write($($data:expr),+)) => {
36 write!(scoped_cx!(), $($data),+)?
38 (@print($x:expr)) => {
39 scoped_cx!() = $x.print(scoped_cx!())?
41 (@$method:ident($($arg:expr),*)) => {
42 scoped_cx!() = scoped_cx!().$method($($arg),*)?
44 ($($elem:tt $(($($args:tt)*))?),+) => {{
45 $(p!(@ $elem $(($($args)*))?);)+
48 macro_rules! define_scoped_cx {
50 #[allow(unused_macros)]
51 macro_rules! scoped_cx {
60 static FORCE_IMPL_FILENAME_LINE: Cell<bool> = const { Cell::new(false) };
61 static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = const { Cell::new(false) };
62 static NO_TRIMMED_PATH: Cell<bool> = const { Cell::new(false) };
63 static NO_QUERIES: Cell<bool> = const { Cell::new(false) };
64 static NO_VISIBLE_PATH: Cell<bool> = const { Cell::new(false) };
67 macro_rules! define_helper {
68 ($($(#[$a:meta])* fn $name:ident($helper:ident, $tl:ident);)+) => {
71 pub struct $helper(bool);
74 pub fn new() -> $helper {
75 $helper($tl.with(|c| c.replace(true)))
80 pub macro $name($e:expr) {
82 let _guard = $helper::new();
87 impl Drop for $helper {
89 $tl.with(|c| c.set(self.0))
97 /// Avoids running any queries during any prints that occur
98 /// during the closure. This may alter the appearance of some
99 /// types (e.g. forcing verbose printing for opaque types).
100 /// This method is used during some queries (e.g. `explicit_item_bounds`
101 /// for opaque types), to ensure that any debug printing that
102 /// occurs during the query computation does not end up recursively
103 /// calling the same query.
104 fn with_no_queries(NoQueriesGuard, NO_QUERIES);
105 /// Force us to name impls with just the filename/line number. We
106 /// normally try to use types. But at some points, notably while printing
107 /// cycle errors, this can result in extra or suboptimal error output,
108 /// so this variable disables that check.
109 fn with_forced_impl_filename_line(ForcedImplGuard, FORCE_IMPL_FILENAME_LINE);
110 /// Adds the `crate::` prefix to paths where appropriate.
111 fn with_crate_prefix(CratePrefixGuard, SHOULD_PREFIX_WITH_CRATE);
112 /// Prevent path trimming if it is turned on. Path trimming affects `Display` impl
113 /// of various rustc types, for example `std::vec::Vec` would be trimmed to `Vec`,
114 /// if no other `Vec` is found.
115 fn with_no_trimmed_paths(NoTrimmedGuard, NO_TRIMMED_PATH);
116 /// Prevent selection of visible paths. `Display` impl of DefId will prefer
117 /// visible (public) reexports of types as paths.
118 fn with_no_visible_paths(NoVisibleGuard, NO_VISIBLE_PATH);
121 /// The "region highlights" are used to control region printing during
122 /// specific error messages. When a "region highlight" is enabled, it
123 /// gives an alternate way to print specific regions. For now, we
124 /// always print those regions using a number, so something like "`'0`".
126 /// Regions not selected by the region highlight mode are presently
128 #[derive(Copy, Clone)]
129 pub struct RegionHighlightMode<'tcx> {
132 /// If enabled, when we see the selected region, use "`'N`"
133 /// instead of the ordinary behavior.
134 highlight_regions: [Option<(ty::Region<'tcx>, usize)>; 3],
136 /// If enabled, when printing a "free region" that originated from
137 /// the given `ty::BoundRegionKind`, print it as "`'1`". Free regions that would ordinarily
138 /// have names print as normal.
140 /// This is used when you have a signature like `fn foo(x: &u32,
141 /// y: &'a u32)` and we want to give a name to the region of the
143 highlight_bound_region: Option<(ty::BoundRegionKind, usize)>,
146 impl<'tcx> RegionHighlightMode<'tcx> {
147 pub fn new(tcx: TyCtxt<'tcx>) -> Self {
150 highlight_regions: Default::default(),
151 highlight_bound_region: Default::default(),
155 /// If `region` and `number` are both `Some`, invokes
156 /// `highlighting_region`.
157 pub fn maybe_highlighting_region(
159 region: Option<ty::Region<'tcx>>,
160 number: Option<usize>,
162 if let Some(k) = region {
163 if let Some(n) = number {
164 self.highlighting_region(k, n);
169 /// Highlights the region inference variable `vid` as `'N`.
170 pub fn highlighting_region(&mut self, region: ty::Region<'tcx>, number: usize) {
171 let num_slots = self.highlight_regions.len();
172 let first_avail_slot =
173 self.highlight_regions.iter_mut().find(|s| s.is_none()).unwrap_or_else(|| {
174 bug!("can only highlight {} placeholders at a time", num_slots,)
176 *first_avail_slot = Some((region, number));
179 /// Convenience wrapper for `highlighting_region`.
180 pub fn highlighting_region_vid(&mut self, vid: ty::RegionVid, number: usize) {
181 self.highlighting_region(self.tcx.mk_region(ty::ReVar(vid)), number)
184 /// Returns `Some(n)` with the number to use for the given region, if any.
185 fn region_highlighted(&self, region: ty::Region<'tcx>) -> Option<usize> {
186 self.highlight_regions.iter().find_map(|h| match h {
187 Some((r, n)) if *r == region => Some(*n),
192 /// Highlight the given bound region.
193 /// We can only highlight one bound region at a time. See
194 /// the field `highlight_bound_region` for more detailed notes.
195 pub fn highlighting_bound_region(&mut self, br: ty::BoundRegionKind, number: usize) {
196 assert!(self.highlight_bound_region.is_none());
197 self.highlight_bound_region = Some((br, number));
201 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
202 pub trait PrettyPrinter<'tcx>:
209 DynExistential = Self,
213 /// Like `print_def_path` but for value paths.
217 substs: &'tcx [GenericArg<'tcx>],
218 ) -> Result<Self::Path, Self::Error> {
219 self.print_def_path(def_id, substs)
222 fn in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, Self::Error>
224 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
226 value.as_ref().skip_binder().print(self)
229 fn wrap_binder<T, F: FnOnce(&T, Self) -> Result<Self, fmt::Error>>(
231 value: &ty::Binder<'tcx, T>,
233 ) -> Result<Self, Self::Error>
235 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
237 f(value.as_ref().skip_binder(), self)
240 /// Prints comma-separated elements.
241 fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
243 T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
245 if let Some(first) = elems.next() {
246 self = first.print(self)?;
248 self.write_str(", ")?;
249 self = elem.print(self)?;
255 /// Prints `{f: t}` or `{f as t}` depending on the `cast` argument
258 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
259 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
261 ) -> Result<Self::Const, Self::Error> {
262 self.write_str("{")?;
264 self.write_str(conversion)?;
266 self.write_str("}")?;
270 /// Prints `<...>` around what `f` prints.
271 fn generic_delimiters(
273 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
274 ) -> Result<Self, Self::Error>;
276 /// Returns `true` if the region should be printed in
277 /// optional positions, e.g., `&'a T` or `dyn Tr + 'b`.
278 /// This is typically the case for all non-`'_` regions.
279 fn should_print_region(&self, region: ty::Region<'tcx>) -> bool;
281 // Defaults (should not be overridden):
283 /// If possible, this returns a global path resolving to `def_id` that is visible
284 /// from at least one local module, and returns `true`. If the crate defining `def_id` is
285 /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
286 fn try_print_visible_def_path(self, def_id: DefId) -> Result<(Self, bool), Self::Error> {
287 if NO_VISIBLE_PATH.with(|flag| flag.get()) {
288 return Ok((self, false));
291 let mut callers = Vec::new();
292 self.try_print_visible_def_path_recur(def_id, &mut callers)
295 /// Try to see if this path can be trimmed to a unique symbol name.
296 fn try_print_trimmed_def_path(
299 ) -> Result<(Self::Path, bool), Self::Error> {
300 if !self.tcx().sess.opts.unstable_opts.trim_diagnostic_paths
301 || matches!(self.tcx().sess.opts.trimmed_def_paths, TrimmedDefPaths::Never)
302 || NO_TRIMMED_PATH.with(|flag| flag.get())
303 || SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get())
305 return Ok((self, false));
308 match self.tcx().trimmed_def_paths(()).get(&def_id) {
309 None => Ok((self, false)),
311 self.write_str(symbol.as_str())?;
317 /// Does the work of `try_print_visible_def_path`, building the
318 /// full definition path recursively before attempting to
319 /// post-process it into the valid and visible version that
320 /// accounts for re-exports.
322 /// This method should only be called by itself or
323 /// `try_print_visible_def_path`.
325 /// `callers` is a chain of visible_parent's leading to `def_id`,
326 /// to support cycle detection during recursion.
328 /// This method returns false if we can't print the visible path, so
329 /// `print_def_path` can fall back on the item's real definition path.
330 fn try_print_visible_def_path_recur(
333 callers: &mut Vec<DefId>,
334 ) -> Result<(Self, bool), Self::Error> {
335 define_scoped_cx!(self);
337 debug!("try_print_visible_def_path: def_id={:?}", def_id);
339 // If `def_id` is a direct or injected extern crate, return the
340 // path to the crate followed by the path to the item within the crate.
341 if let Some(cnum) = def_id.as_crate_root() {
342 if cnum == LOCAL_CRATE {
343 return Ok((self.path_crate(cnum)?, true));
346 // In local mode, when we encounter a crate other than
347 // LOCAL_CRATE, execution proceeds in one of two ways:
349 // 1. For a direct dependency, where user added an
350 // `extern crate` manually, we put the `extern
351 // crate` as the parent. So you wind up with
352 // something relative to the current crate.
353 // 2. For an extern inferred from a path or an indirect crate,
354 // where there is no explicit `extern crate`, we just prepend
356 match self.tcx().extern_crate(def_id) {
357 Some(&ExternCrate { src, dependency_of, span, .. }) => match (src, dependency_of) {
358 (ExternCrateSource::Extern(def_id), LOCAL_CRATE) => {
359 // NOTE(eddyb) the only reason `span` might be dummy,
360 // that we're aware of, is that it's the `std`/`core`
361 // `extern crate` injected by default.
362 // FIXME(eddyb) find something better to key this on,
363 // or avoid ending up with `ExternCrateSource::Extern`,
364 // for the injected `std`/`core`.
366 return Ok((self.path_crate(cnum)?, true));
369 // Disable `try_print_trimmed_def_path` behavior within
370 // the `print_def_path` call, to avoid infinite recursion
371 // in cases where the `extern crate foo` has non-trivial
372 // parents, e.g. it's nested in `impl foo::Trait for Bar`
373 // (see also issues #55779 and #87932).
374 self = with_no_visible_paths!(self.print_def_path(def_id, &[])?);
376 return Ok((self, true));
378 (ExternCrateSource::Path, LOCAL_CRATE) => {
379 return Ok((self.path_crate(cnum)?, true));
384 return Ok((self.path_crate(cnum)?, true));
389 if def_id.is_local() {
390 return Ok((self, false));
393 let visible_parent_map = self.tcx().visible_parent_map(());
395 let mut cur_def_key = self.tcx().def_key(def_id);
396 debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
398 // For a constructor, we want the name of its parent rather than <unnamed>.
399 if let DefPathData::Ctor = cur_def_key.disambiguated_data.data {
404 .expect("`DefPathData::Ctor` / `VariantData` missing a parent"),
407 cur_def_key = self.tcx().def_key(parent);
410 let Some(visible_parent) = visible_parent_map.get(&def_id).cloned() else {
411 return Ok((self, false));
414 let actual_parent = self.tcx().opt_parent(def_id);
416 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
417 visible_parent, actual_parent,
420 let mut data = cur_def_key.disambiguated_data.data;
422 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
423 data, visible_parent, actual_parent,
427 // In order to output a path that could actually be imported (valid and visible),
428 // we need to handle re-exports correctly.
430 // For example, take `std::os::unix::process::CommandExt`, this trait is actually
431 // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
433 // `std::os::unix` reexports the contents of `std::sys::unix::ext`. `std::sys` is
434 // private so the "true" path to `CommandExt` isn't accessible.
436 // In this case, the `visible_parent_map` will look something like this:
438 // (child) -> (parent)
439 // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
440 // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
441 // `std::sys::unix::ext` -> `std::os`
443 // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
446 // When printing the path to `CommandExt` and looking at the `cur_def_key` that
447 // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
448 // to the parent - resulting in a mangled path like
449 // `std::os::ext::process::CommandExt`.
451 // Instead, we must detect that there was a re-export and instead print `unix`
452 // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
453 // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
454 // the visible parent (`std::os`). If these do not match, then we iterate over
455 // the children of the visible parent (as was done when computing
456 // `visible_parent_map`), looking for the specific child we currently have and then
457 // have access to the re-exported name.
458 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
459 // Item might be re-exported several times, but filter for the one
460 // that's public and whose identifier isn't `_`.
463 .module_children(visible_parent)
465 .filter(|child| child.res.opt_def_id() == Some(def_id))
466 .find(|child| child.vis.is_public() && child.ident.name != kw::Underscore)
467 .map(|child| child.ident.name);
469 if let Some(new_name) = reexport {
472 // There is no name that is public and isn't `_`, so bail.
473 return Ok((self, false));
476 // Re-exported `extern crate` (#43189).
477 DefPathData::CrateRoot => {
478 data = DefPathData::TypeNs(self.tcx().crate_name(def_id.krate));
482 debug!("try_print_visible_def_path: data={:?}", data);
484 if callers.contains(&visible_parent) {
485 return Ok((self, false));
487 callers.push(visible_parent);
488 // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
489 // knowing ahead of time whether the entire path will succeed or not.
490 // To support printers that do not implement `PrettyPrinter`, a `Vec` or
491 // linked list on the stack would need to be built, before any printing.
492 match self.try_print_visible_def_path_recur(visible_parent, callers)? {
493 (cx, false) => return Ok((cx, false)),
494 (cx, true) => self = cx,
498 Ok((self.path_append(Ok, &DisambiguatedDefPathData { data, disambiguator: 0 })?, true))
501 fn pretty_path_qualified(
504 trait_ref: Option<ty::TraitRef<'tcx>>,
505 ) -> Result<Self::Path, Self::Error> {
506 if trait_ref.is_none() {
507 // Inherent impls. Try to print `Foo::bar` for an inherent
508 // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
509 // anything other than a simple path.
510 match self_ty.kind() {
519 return self_ty.print(self);
526 self.generic_delimiters(|mut cx| {
527 define_scoped_cx!(cx);
530 if let Some(trait_ref) = trait_ref {
531 p!(" as ", print(trait_ref.print_only_trait_path()));
537 fn pretty_path_append_impl(
539 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
541 trait_ref: Option<ty::TraitRef<'tcx>>,
542 ) -> Result<Self::Path, Self::Error> {
543 self = print_prefix(self)?;
545 self.generic_delimiters(|mut cx| {
546 define_scoped_cx!(cx);
549 if let Some(trait_ref) = trait_ref {
550 p!(print(trait_ref.print_only_trait_path()), " for ");
558 fn pretty_print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
559 define_scoped_cx!(self);
562 ty::Bool => p!("bool"),
563 ty::Char => p!("char"),
564 ty::Int(t) => p!(write("{}", t.name_str())),
565 ty::Uint(t) => p!(write("{}", t.name_str())),
566 ty::Float(t) => p!(write("{}", t.name_str())),
567 ty::RawPtr(ref tm) => {
571 hir::Mutability::Mut => "mut",
572 hir::Mutability::Not => "const",
577 ty::Ref(r, ty, mutbl) => {
579 if self.should_print_region(r) {
582 p!(print(ty::TypeAndMut { ty, mutbl }))
584 ty::Never => p!("!"),
585 ty::Tuple(ref tys) => {
586 p!("(", comma_sep(tys.iter()));
592 ty::FnDef(def_id, substs) => {
593 let sig = self.tcx().bound_fn_sig(def_id).subst(self.tcx(), substs);
594 p!(print(sig), " {{", print_value_path(def_id, substs), "}}");
596 ty::FnPtr(ref bare_fn) => p!(print(bare_fn)),
597 ty::Infer(infer_ty) => {
598 let verbose = self.tcx().sess.verbose();
599 if let ty::TyVar(ty_vid) = infer_ty {
600 if let Some(name) = self.ty_infer_name(ty_vid) {
601 p!(write("{}", name))
604 p!(write("{:?}", infer_ty))
606 p!(write("{}", infer_ty))
610 if verbose { p!(write("{:?}", infer_ty)) } else { p!(write("{}", infer_ty)) }
613 ty::Error(_) => p!("[type error]"),
614 ty::Param(ref param_ty) => p!(print(param_ty)),
615 ty::Bound(debruijn, bound_ty) => match bound_ty.kind {
616 ty::BoundTyKind::Anon => self.pretty_print_bound_var(debruijn, bound_ty.var)?,
617 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
619 ty::Adt(def, substs) => {
620 p!(print_def_path(def.did(), substs));
622 ty::Dynamic(data, r) => {
623 let print_r = self.should_print_region(r);
627 p!("dyn ", print(data));
629 p!(" + ", print(r), ")");
632 ty::Foreign(def_id) => {
633 p!(print_def_path(def_id, &[]));
635 ty::Projection(ref data) => p!(print(data)),
636 ty::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
637 ty::Opaque(def_id, substs) => {
638 // FIXME(eddyb) print this with `print_def_path`.
639 // We use verbose printing in 'NO_QUERIES' mode, to
640 // avoid needing to call `predicates_of`. This should
641 // only affect certain debug messages (e.g. messages printed
642 // from `rustc_middle::ty` during the computation of `tcx.predicates_of`),
643 // and should have no effect on any compiler output.
644 if self.tcx().sess.verbose() || NO_QUERIES.with(|q| q.get()) {
645 p!(write("Opaque({:?}, {:?})", def_id, substs));
649 let parent = self.tcx().parent(def_id);
650 match self.tcx().def_kind(parent) {
651 DefKind::TyAlias | DefKind::AssocTy => {
652 if let ty::Opaque(d, _) = *self.tcx().type_of(parent).kind() {
654 // If the type alias directly starts with the `impl` of the
655 // opaque type we're printing, then skip the `::{opaque#1}`.
656 p!(print_def_path(parent, substs));
660 // Complex opaque type, e.g. `type Foo = (i32, impl Debug);`
661 p!(print_def_path(def_id, substs));
664 _ => return self.pretty_print_opaque_impl_type(def_id, substs),
667 ty::Str => p!("str"),
668 ty::Generator(did, substs, movability) => {
671 hir::Movability::Movable => {}
672 hir::Movability::Static => p!("static "),
675 if !self.tcx().sess.verbose() {
677 // FIXME(eddyb) should use `def_span`.
678 if let Some(did) = did.as_local() {
679 let span = self.tcx().def_span(did);
682 // This may end up in stderr diagnostics but it may also be emitted
683 // into MIR. Hence we use the remapped path if available
684 self.tcx().sess.source_map().span_to_embeddable_string(span)
687 p!(write("@"), print_def_path(did, substs));
690 p!(print_def_path(did, substs));
692 if !substs.as_generator().is_valid() {
695 self = self.comma_sep(substs.as_generator().upvar_tys())?;
699 if substs.as_generator().is_valid() {
700 p!(" ", print(substs.as_generator().witness()));
706 ty::GeneratorWitness(types) => {
707 p!(in_binder(&types));
709 ty::Closure(did, substs) => {
711 if !self.tcx().sess.verbose() {
712 p!(write("closure"));
713 // FIXME(eddyb) should use `def_span`.
714 if let Some(did) = did.as_local() {
715 if self.tcx().sess.opts.unstable_opts.span_free_formats {
716 p!("@", print_def_path(did.to_def_id(), substs));
718 let span = self.tcx().def_span(did);
721 // This may end up in stderr diagnostics but it may also be emitted
722 // into MIR. Hence we use the remapped path if available
723 self.tcx().sess.source_map().span_to_embeddable_string(span)
727 p!(write("@"), print_def_path(did, substs));
730 p!(print_def_path(did, substs));
731 if !substs.as_closure().is_valid() {
732 p!(" closure_substs=(unavailable)");
733 p!(write(" substs={:?}", substs));
735 p!(" closure_kind_ty=", print(substs.as_closure().kind_ty()));
737 " closure_sig_as_fn_ptr_ty=",
738 print(substs.as_closure().sig_as_fn_ptr_ty())
741 self = self.comma_sep(substs.as_closure().upvar_tys())?;
747 ty::Array(ty, sz) => {
748 p!("[", print(ty), "; ");
749 if self.tcx().sess.verbose() {
750 p!(write("{:?}", sz));
751 } else if let ty::ConstKind::Unevaluated(..) = sz.kind() {
752 // Do not try to evaluate unevaluated constants. If we are const evaluating an
753 // array length anon const, rustc will (with debug assertions) print the
754 // constant's path. Which will end up here again.
756 } else if let Some(n) = sz.kind().try_to_bits(self.tcx().data_layout.pointer_size) {
758 } else if let ty::ConstKind::Param(param) = sz.kind() {
765 ty::Slice(ty) => p!("[", print(ty), "]"),
771 fn pretty_print_opaque_impl_type(
774 substs: &'tcx ty::List<ty::GenericArg<'tcx>>,
775 ) -> Result<Self::Type, Self::Error> {
776 let tcx = self.tcx();
778 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
779 // by looking up the projections associated with the def_id.
780 let bounds = tcx.bound_explicit_item_bounds(def_id);
782 let mut traits = FxIndexMap::default();
783 let mut fn_traits = FxIndexMap::default();
784 let mut is_sized = false;
786 for predicate in bounds.transpose_iter().map(|e| e.map_bound(|(p, _)| *p)) {
787 let predicate = predicate.subst(tcx, substs);
788 let bound_predicate = predicate.kind();
790 match bound_predicate.skip_binder() {
791 ty::PredicateKind::Trait(pred) => {
792 let trait_ref = bound_predicate.rebind(pred.trait_ref);
794 // Don't print + Sized, but rather + ?Sized if absent.
795 if Some(trait_ref.def_id()) == tcx.lang_items().sized_trait() {
800 self.insert_trait_and_projection(trait_ref, None, &mut traits, &mut fn_traits);
802 ty::PredicateKind::Projection(pred) => {
803 let proj_ref = bound_predicate.rebind(pred);
804 let trait_ref = proj_ref.required_poly_trait_ref(tcx);
806 // Projection type entry -- the def-id for naming, and the ty.
807 let proj_ty = (proj_ref.projection_def_id(), proj_ref.term());
809 self.insert_trait_and_projection(
820 write!(self, "impl ")?;
822 let mut first = true;
823 // Insert parenthesis around (Fn(A, B) -> C) if the opaque ty has more than one other trait
824 let paren_needed = fn_traits.len() > 1 || traits.len() > 0 || !is_sized;
826 for (fn_once_trait_ref, entry) in fn_traits {
827 write!(self, "{}", if first { "" } else { " + " })?;
828 write!(self, "{}", if paren_needed { "(" } else { "" })?;
830 self = self.wrap_binder(&fn_once_trait_ref, |trait_ref, mut cx| {
831 define_scoped_cx!(cx);
832 // Get the (single) generic ty (the args) of this FnOnce trait ref.
833 let generics = tcx.generics_of(trait_ref.def_id);
834 let args = generics.own_substs_no_defaults(tcx, trait_ref.substs);
836 match (entry.return_ty, args[0].expect_ty()) {
837 // We can only print `impl Fn() -> ()` if we have a tuple of args and we recorded
839 (Some(return_ty), arg_tys) if matches!(arg_tys.kind(), ty::Tuple(_)) => {
840 let name = if entry.fn_trait_ref.is_some() {
842 } else if entry.fn_mut_trait_ref.is_some() {
848 p!(write("{}(", name));
850 for (idx, ty) in arg_tys.tuple_fields().iter().enumerate() {
858 if let Term::Ty(ty) = return_ty.skip_binder() {
860 p!(" -> ", print(return_ty));
863 p!(write("{}", if paren_needed { ")" } else { "" }));
867 // If we got here, we can't print as a `impl Fn(A, B) -> C`. Just record the
868 // trait_refs we collected in the OpaqueFnEntry as normal trait refs.
870 if entry.has_fn_once {
871 traits.entry(fn_once_trait_ref).or_default().extend(
872 // Group the return ty with its def id, if we had one.
875 .map(|ty| (tcx.lang_items().fn_once_output().unwrap(), ty)),
878 if let Some(trait_ref) = entry.fn_mut_trait_ref {
879 traits.entry(trait_ref).or_default();
881 if let Some(trait_ref) = entry.fn_trait_ref {
882 traits.entry(trait_ref).or_default();
891 // Print the rest of the trait types (that aren't Fn* family of traits)
892 for (trait_ref, assoc_items) in traits {
893 write!(self, "{}", if first { "" } else { " + " })?;
895 self = self.wrap_binder(&trait_ref, |trait_ref, mut cx| {
896 define_scoped_cx!(cx);
897 p!(print(trait_ref.print_only_trait_name()));
899 let generics = tcx.generics_of(trait_ref.def_id);
900 let args = generics.own_substs_no_defaults(tcx, trait_ref.substs);
902 if !args.is_empty() || !assoc_items.is_empty() {
903 let mut first = true;
915 for (assoc_item_def_id, term) in assoc_items {
916 // Skip printing `<[generator@] as Generator<_>>::Return` from async blocks,
917 // unless we can find out what generator return type it comes from.
918 let term = if let Some(ty) = term.skip_binder().ty()
919 && let ty::Projection(ty::ProjectionTy { item_def_id, substs }) = ty.kind()
920 && Some(*item_def_id) == tcx.lang_items().generator_return()
922 if let ty::Generator(_, substs, _) = substs.type_at(0).kind() {
923 let return_ty = substs.as_generator().return_ty();
924 if !return_ty.is_ty_infer() {
943 p!(write("{} = ", tcx.associated_item(assoc_item_def_id).name));
966 write!(self, "{}?Sized", if first { "" } else { " + " })?;
968 write!(self, "Sized")?;
974 /// Insert the trait ref and optionally a projection type associated with it into either the
975 /// traits map or fn_traits map, depending on if the trait is in the Fn* family of traits.
976 fn insert_trait_and_projection(
978 trait_ref: ty::PolyTraitRef<'tcx>,
979 proj_ty: Option<(DefId, ty::Binder<'tcx, Term<'tcx>>)>,
980 traits: &mut FxIndexMap<
981 ty::PolyTraitRef<'tcx>,
982 FxIndexMap<DefId, ty::Binder<'tcx, Term<'tcx>>>,
984 fn_traits: &mut FxIndexMap<ty::PolyTraitRef<'tcx>, OpaqueFnEntry<'tcx>>,
986 let trait_def_id = trait_ref.def_id();
988 // If our trait_ref is FnOnce or any of its children, project it onto the parent FnOnce
989 // super-trait ref and record it there.
990 if let Some(fn_once_trait) = self.tcx().lang_items().fn_once_trait() {
991 // If we have a FnOnce, then insert it into
992 if trait_def_id == fn_once_trait {
993 let entry = fn_traits.entry(trait_ref).or_default();
994 // Optionally insert the return_ty as well.
995 if let Some((_, ty)) = proj_ty {
996 entry.return_ty = Some(ty);
998 entry.has_fn_once = true;
1000 } else if Some(trait_def_id) == self.tcx().lang_items().fn_mut_trait() {
1001 let super_trait_ref = crate::traits::util::supertraits(self.tcx(), trait_ref)
1002 .find(|super_trait_ref| super_trait_ref.def_id() == fn_once_trait)
1005 fn_traits.entry(super_trait_ref).or_default().fn_mut_trait_ref = Some(trait_ref);
1007 } else if Some(trait_def_id) == self.tcx().lang_items().fn_trait() {
1008 let super_trait_ref = crate::traits::util::supertraits(self.tcx(), trait_ref)
1009 .find(|super_trait_ref| super_trait_ref.def_id() == fn_once_trait)
1012 fn_traits.entry(super_trait_ref).or_default().fn_trait_ref = Some(trait_ref);
1017 // Otherwise, just group our traits and projection types.
1018 traits.entry(trait_ref).or_default().extend(proj_ty);
1021 fn pretty_print_bound_var(
1023 debruijn: ty::DebruijnIndex,
1025 ) -> Result<(), Self::Error> {
1026 if debruijn == ty::INNERMOST {
1027 write!(self, "^{}", var.index())
1029 write!(self, "^{}_{}", debruijn.index(), var.index())
1033 fn ty_infer_name(&self, _: ty::TyVid) -> Option<Symbol> {
1037 fn const_infer_name(&self, _: ty::ConstVid<'tcx>) -> Option<Symbol> {
1041 fn pretty_print_dyn_existential(
1043 predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
1044 ) -> Result<Self::DynExistential, Self::Error> {
1045 // Generate the main trait ref, including associated types.
1046 let mut first = true;
1048 if let Some(principal) = predicates.principal() {
1049 self = self.wrap_binder(&principal, |principal, mut cx| {
1050 define_scoped_cx!(cx);
1051 p!(print_def_path(principal.def_id, &[]));
1053 let mut resugared = false;
1055 // Special-case `Fn(...) -> ...` and re-sugar it.
1056 let fn_trait_kind = cx.tcx().fn_trait_kind_from_lang_item(principal.def_id);
1057 if !cx.tcx().sess.verbose() && fn_trait_kind.is_some() {
1058 if let ty::Tuple(tys) = principal.substs.type_at(0).kind() {
1059 let mut projections = predicates.projection_bounds();
1060 if let (Some(proj), None) = (projections.next(), projections.next()) {
1064 proj.skip_binder().term.ty().expect("Return type was a const")
1071 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
1072 // in order to place the projections inside the `<...>`.
1074 // Use a type that can't appear in defaults of type parameters.
1075 let dummy_cx = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1076 let principal = principal.with_self_ty(cx.tcx(), dummy_cx);
1080 .generics_of(principal.def_id)
1081 .own_substs_no_defaults(cx.tcx(), principal.substs);
1083 // Don't print `'_` if there's no unerased regions.
1084 let print_regions = args.iter().any(|arg| match arg.unpack() {
1085 GenericArgKind::Lifetime(r) => !r.is_erased(),
1088 let mut args = args.iter().cloned().filter(|arg| match arg.unpack() {
1089 GenericArgKind::Lifetime(_) => print_regions,
1092 let mut projections = predicates.projection_bounds();
1094 let arg0 = args.next();
1095 let projection0 = projections.next();
1096 if arg0.is_some() || projection0.is_some() {
1097 let args = arg0.into_iter().chain(args);
1098 let projections = projection0.into_iter().chain(projections);
1100 p!(generic_delimiters(|mut cx| {
1101 cx = cx.comma_sep(args)?;
1102 if arg0.is_some() && projection0.is_some() {
1105 cx.comma_sep(projections)
1115 define_scoped_cx!(self);
1118 // FIXME(eddyb) avoid printing twice (needed to ensure
1119 // that the auto traits are sorted *and* printed via cx).
1120 let mut auto_traits: Vec<_> = predicates.auto_traits().collect();
1122 // The auto traits come ordered by `DefPathHash`. While
1123 // `DefPathHash` is *stable* in the sense that it depends on
1124 // neither the host nor the phase of the moon, it depends
1125 // "pseudorandomly" on the compiler version and the target.
1127 // To avoid causing instabilities in compiletest
1128 // output, sort the auto-traits alphabetically.
1129 auto_traits.sort_by_cached_key(|did| self.tcx().def_path_str(*did));
1131 for def_id in auto_traits {
1137 p!(print_def_path(def_id, &[]));
1145 inputs: &[Ty<'tcx>],
1148 ) -> Result<Self, Self::Error> {
1149 define_scoped_cx!(self);
1151 p!("(", comma_sep(inputs.iter().copied()));
1153 if !inputs.is_empty() {
1159 if !output.is_unit() {
1160 p!(" -> ", print(output));
1166 fn pretty_print_const(
1168 ct: ty::Const<'tcx>,
1170 ) -> Result<Self::Const, Self::Error> {
1171 define_scoped_cx!(self);
1173 if self.tcx().sess.verbose() {
1174 p!(write("Const({:?}: {:?})", ct.kind(), ct.ty()));
1178 macro_rules! print_underscore {
1181 self = self.typed_value(
1186 |this| this.print_type(ct.ty()),
1196 ty::ConstKind::Unevaluated(ty::Unevaluated {
1199 promoted: Some(promoted),
1201 p!(print_value_path(def.did, substs));
1202 p!(write("::{:?}", promoted));
1204 ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted: None }) => {
1205 match self.tcx().def_kind(def.did) {
1206 DefKind::Static(..) | DefKind::Const | DefKind::AssocConst => {
1207 p!(print_value_path(def.did, substs))
1211 let span = self.tcx().def_span(def.did);
1212 if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span) {
1213 p!(write("{}", snip))
1223 ty::ConstKind::Infer(infer_ct) => {
1225 ty::InferConst::Var(ct_vid)
1226 if let Some(name) = self.const_infer_name(ct_vid) =>
1227 p!(write("{}", name)),
1228 _ => print_underscore!(),
1231 ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)),
1232 ty::ConstKind::Value(value) => {
1233 return self.pretty_print_const_valtree(value, ct.ty(), print_ty);
1236 ty::ConstKind::Bound(debruijn, bound_var) => {
1237 self.pretty_print_bound_var(debruijn, bound_var)?
1239 ty::ConstKind::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
1240 ty::ConstKind::Error(_) => p!("[const error]"),
1245 fn pretty_print_const_scalar(
1250 ) -> Result<Self::Const, Self::Error> {
1252 Scalar::Ptr(ptr, _size) => self.pretty_print_const_scalar_ptr(ptr, ty, print_ty),
1253 Scalar::Int(int) => self.pretty_print_const_scalar_int(int, ty, print_ty),
1257 fn pretty_print_const_scalar_ptr(
1262 ) -> Result<Self::Const, Self::Error> {
1263 define_scoped_cx!(self);
1265 let (alloc_id, offset) = ptr.into_parts();
1267 // Byte strings (&[u8; N])
1268 ty::Ref(_, inner, _) => {
1269 if let ty::Array(elem, len) = inner.kind() {
1270 if let ty::Uint(ty::UintTy::U8) = elem.kind() {
1271 if let ty::ConstKind::Value(ty::ValTree::Leaf(int)) = len.kind() {
1272 match self.tcx().get_global_alloc(alloc_id) {
1273 Some(GlobalAlloc::Memory(alloc)) => {
1274 let len = int.assert_bits(self.tcx().data_layout.pointer_size);
1276 AllocRange { start: offset, size: Size::from_bytes(len) };
1277 if let Ok(byte_str) =
1278 alloc.inner().get_bytes(&self.tcx(), range)
1280 p!(pretty_print_byte_str(byte_str))
1282 p!("<too short allocation>")
1285 // FIXME: for statics and functions, we could in principle print more detail.
1286 Some(GlobalAlloc::Static(def_id)) => {
1287 p!(write("<static({:?})>", def_id))
1289 Some(GlobalAlloc::Function(_)) => p!("<function>"),
1290 None => p!("<dangling pointer>"),
1298 // FIXME: We should probably have a helper method to share code with the "Byte strings"
1299 // printing above (which also has to handle pointers to all sorts of things).
1300 if let Some(GlobalAlloc::Function(instance)) = self.tcx().get_global_alloc(alloc_id)
1302 self = self.typed_value(
1303 |this| this.print_value_path(instance.def_id(), instance.substs),
1304 |this| this.print_type(ty),
1312 // Any pointer values not covered by a branch above
1313 self = self.pretty_print_const_pointer(ptr, ty, print_ty)?;
1317 fn pretty_print_const_scalar_int(
1322 ) -> Result<Self::Const, Self::Error> {
1323 define_scoped_cx!(self);
1327 ty::Bool if int == ScalarInt::FALSE => p!("false"),
1328 ty::Bool if int == ScalarInt::TRUE => p!("true"),
1330 ty::Float(ty::FloatTy::F32) => {
1331 p!(write("{}f32", Single::try_from(int).unwrap()))
1333 ty::Float(ty::FloatTy::F64) => {
1334 p!(write("{}f64", Double::try_from(int).unwrap()))
1337 ty::Uint(_) | ty::Int(_) => {
1339 ConstInt::new(int, matches!(ty.kind(), ty::Int(_)), ty.is_ptr_sized_integral());
1340 if print_ty { p!(write("{:#?}", int)) } else { p!(write("{:?}", int)) }
1343 ty::Char if char::try_from(int).is_ok() => {
1344 p!(write("{:?}", char::try_from(int).unwrap()))
1347 ty::Ref(..) | ty::RawPtr(_) | ty::FnPtr(_) => {
1348 let data = int.assert_bits(self.tcx().data_layout.pointer_size);
1349 self = self.typed_value(
1351 write!(this, "0x{:x}", data)?;
1354 |this| this.print_type(ty),
1358 // Nontrivial types with scalar bit representation
1360 let print = |mut this: Self| {
1361 if int.size() == Size::ZERO {
1362 write!(this, "transmute(())")?;
1364 write!(this, "transmute(0x{:x})", int)?;
1368 self = if print_ty {
1369 self.typed_value(print, |this| this.print_type(ty), ": ")?
1378 /// This is overridden for MIR printing because we only want to hide alloc ids from users, not
1379 /// from MIR where it is actually useful.
1380 fn pretty_print_const_pointer<Tag: Provenance>(
1385 ) -> Result<Self::Const, Self::Error> {
1389 this.write_str("&_")?;
1392 |this| this.print_type(ty),
1396 self.write_str("&_")?;
1401 fn pretty_print_byte_str(mut self, byte_str: &'tcx [u8]) -> Result<Self::Const, Self::Error> {
1402 define_scoped_cx!(self);
1404 for &c in byte_str {
1405 for e in std::ascii::escape_default(c) {
1406 self.write_char(e as char)?;
1413 fn pretty_print_const_valtree(
1415 valtree: ty::ValTree<'tcx>,
1418 ) -> Result<Self::Const, Self::Error> {
1419 define_scoped_cx!(self);
1421 if self.tcx().sess.verbose() {
1422 p!(write("ValTree({:?}: ", valtree), print(ty), ")");
1426 let u8_type = self.tcx().types.u8;
1427 match (valtree, ty.kind()) {
1428 (ty::ValTree::Branch(_), ty::Ref(_, inner_ty, _)) => match inner_ty.kind() {
1429 ty::Slice(t) if *t == u8_type => {
1430 let bytes = valtree.try_to_raw_bytes(self.tcx(), ty).unwrap_or_else(|| {
1432 "expected to convert valtree {:?} to raw bytes for type {:?}",
1437 return self.pretty_print_byte_str(bytes);
1440 let bytes = valtree.try_to_raw_bytes(self.tcx(), ty).unwrap_or_else(|| {
1441 bug!("expected to convert valtree to raw bytes for type {:?}", ty)
1443 p!(write("{:?}", String::from_utf8_lossy(bytes)));
1448 p!(pretty_print_const_valtree(valtree, *inner_ty, print_ty));
1452 (ty::ValTree::Branch(_), ty::Array(t, _)) if *t == u8_type => {
1453 let bytes = valtree.try_to_raw_bytes(self.tcx(), *t).unwrap_or_else(|| {
1454 bug!("expected to convert valtree to raw bytes for type {:?}", t)
1457 p!(pretty_print_byte_str(bytes));
1460 // Aggregates, printed as array/tuple/struct/variant construction syntax.
1461 (ty::ValTree::Branch(_), ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) => {
1463 self.tcx().destructure_const(ty::Const::from_value(self.tcx(), valtree, ty));
1464 let fields = contents.fields.iter().copied();
1467 p!("[", comma_sep(fields), "]");
1470 p!("(", comma_sep(fields));
1471 if contents.fields.len() == 1 {
1476 ty::Adt(def, _) if def.variants().is_empty() => {
1477 self = self.typed_value(
1479 write!(this, "unreachable()")?;
1482 |this| this.print_type(ty),
1486 ty::Adt(def, substs) => {
1488 contents.variant.expect("destructed const of adt without variant idx");
1489 let variant_def = &def.variant(variant_idx);
1490 p!(print_value_path(variant_def.def_id, substs));
1491 match variant_def.ctor_kind {
1492 CtorKind::Const => {}
1494 p!("(", comma_sep(fields), ")");
1496 CtorKind::Fictive => {
1498 let mut first = true;
1499 for (field_def, field) in iter::zip(&variant_def.fields, fields) {
1503 p!(write("{}: ", field_def.name), print(field));
1510 _ => unreachable!(),
1514 (ty::ValTree::Leaf(leaf), _) => {
1515 return self.pretty_print_const_scalar_int(leaf, ty, print_ty);
1517 // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
1518 // their fields instead of just dumping the memory.
1523 if valtree == ty::ValTree::zst() {
1526 p!(write("{:?}", valtree));
1529 p!(": ", print(ty));
1535 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
1536 pub struct FmtPrinter<'a, 'tcx>(Box<FmtPrinterData<'a, 'tcx>>);
1538 pub struct FmtPrinterData<'a, 'tcx> {
1544 pub print_alloc_ids: bool,
1546 used_region_names: FxHashSet<Symbol>,
1547 region_index: usize,
1548 binder_depth: usize,
1549 printed_type_count: usize,
1551 pub region_highlight_mode: RegionHighlightMode<'tcx>,
1553 pub ty_infer_name_resolver: Option<Box<dyn Fn(ty::TyVid) -> Option<Symbol> + 'a>>,
1554 pub const_infer_name_resolver: Option<Box<dyn Fn(ty::ConstVid<'tcx>) -> Option<Symbol> + 'a>>,
1557 impl<'a, 'tcx> Deref for FmtPrinter<'a, 'tcx> {
1558 type Target = FmtPrinterData<'a, 'tcx>;
1559 fn deref(&self) -> &Self::Target {
1564 impl DerefMut for FmtPrinter<'_, '_> {
1565 fn deref_mut(&mut self) -> &mut Self::Target {
1570 impl<'a, 'tcx> FmtPrinter<'a, 'tcx> {
1571 pub fn new(tcx: TyCtxt<'tcx>, ns: Namespace) -> Self {
1572 FmtPrinter(Box::new(FmtPrinterData {
1574 // Estimated reasonable capacity to allocate upfront based on a few
1576 fmt: String::with_capacity(64),
1578 in_value: ns == Namespace::ValueNS,
1579 print_alloc_ids: false,
1580 used_region_names: Default::default(),
1583 printed_type_count: 0,
1584 region_highlight_mode: RegionHighlightMode::new(tcx),
1585 ty_infer_name_resolver: None,
1586 const_infer_name_resolver: None,
1590 pub fn into_buffer(self) -> String {
1595 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1596 // (but also some things just print a `DefId` generally so maybe we need this?)
1597 fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
1598 match tcx.def_key(def_id).disambiguated_data.data {
1599 DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::ImplTrait => {
1603 DefPathData::ValueNs(..)
1604 | DefPathData::AnonConst
1605 | DefPathData::ClosureExpr
1606 | DefPathData::Ctor => Namespace::ValueNS,
1608 DefPathData::MacroNs(..) => Namespace::MacroNS,
1610 _ => Namespace::TypeNS,
1614 impl<'t> TyCtxt<'t> {
1615 /// Returns a string identifying this `DefId`. This string is
1616 /// suitable for user output.
1617 pub fn def_path_str(self, def_id: DefId) -> String {
1618 self.def_path_str_with_substs(def_id, &[])
1621 pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1622 let ns = guess_def_namespace(self, def_id);
1623 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1624 FmtPrinter::new(self, ns).print_def_path(def_id, substs).unwrap().into_buffer()
1628 impl fmt::Write for FmtPrinter<'_, '_> {
1629 fn write_str(&mut self, s: &str) -> fmt::Result {
1630 self.fmt.push_str(s);
1635 impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> {
1636 type Error = fmt::Error;
1641 type DynExistential = Self;
1644 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
1651 substs: &'tcx [GenericArg<'tcx>],
1652 ) -> Result<Self::Path, Self::Error> {
1653 define_scoped_cx!(self);
1655 if substs.is_empty() {
1656 match self.try_print_trimmed_def_path(def_id)? {
1657 (cx, true) => return Ok(cx),
1658 (cx, false) => self = cx,
1661 match self.try_print_visible_def_path(def_id)? {
1662 (cx, true) => return Ok(cx),
1663 (cx, false) => self = cx,
1667 let key = self.tcx.def_key(def_id);
1668 if let DefPathData::Impl = key.disambiguated_data.data {
1669 // Always use types for non-local impls, where types are always
1670 // available, and filename/line-number is mostly uninteresting.
1671 let use_types = !def_id.is_local() || {
1672 // Otherwise, use filename/line-number if forced.
1673 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1678 // If no type info is available, fall back to
1679 // pretty printing some span information. This should
1680 // only occur very early in the compiler pipeline.
1681 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1682 let span = self.tcx.def_span(def_id);
1684 self = self.print_def_path(parent_def_id, &[])?;
1686 // HACK(eddyb) copy of `path_append` to avoid
1687 // constructing a `DisambiguatedDefPathData`.
1688 if !self.empty_path {
1689 write!(self, "::")?;
1694 // This may end up in stderr diagnostics but it may also be emitted
1695 // into MIR. Hence we use the remapped path if available
1696 self.tcx.sess.source_map().span_to_embeddable_string(span)
1698 self.empty_path = false;
1704 self.default_print_def_path(def_id, substs)
1707 fn print_region(self, region: ty::Region<'tcx>) -> Result<Self::Region, Self::Error> {
1708 self.pretty_print_region(region)
1711 fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1712 let type_length_limit = self.tcx.type_length_limit();
1713 if type_length_limit.value_within_limit(self.printed_type_count) {
1714 self.printed_type_count += 1;
1715 self.pretty_print_type(ty)
1717 write!(self, "...")?;
1722 fn print_dyn_existential(
1724 predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
1725 ) -> Result<Self::DynExistential, Self::Error> {
1726 self.pretty_print_dyn_existential(predicates)
1729 fn print_const(self, ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1730 self.pretty_print_const(ct, false)
1733 fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1734 self.empty_path = true;
1735 if cnum == LOCAL_CRATE {
1736 if self.tcx.sess.rust_2018() {
1737 // We add the `crate::` keyword on Rust 2018, only when desired.
1738 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1739 write!(self, "{}", kw::Crate)?;
1740 self.empty_path = false;
1744 write!(self, "{}", self.tcx.crate_name(cnum))?;
1745 self.empty_path = false;
1753 trait_ref: Option<ty::TraitRef<'tcx>>,
1754 ) -> Result<Self::Path, Self::Error> {
1755 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1756 self.empty_path = false;
1760 fn path_append_impl(
1762 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1763 _disambiguated_data: &DisambiguatedDefPathData,
1765 trait_ref: Option<ty::TraitRef<'tcx>>,
1766 ) -> Result<Self::Path, Self::Error> {
1767 self = self.pretty_path_append_impl(
1769 cx = print_prefix(cx)?;
1779 self.empty_path = false;
1785 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1786 disambiguated_data: &DisambiguatedDefPathData,
1787 ) -> Result<Self::Path, Self::Error> {
1788 self = print_prefix(self)?;
1790 // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
1791 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
1795 let name = disambiguated_data.data.name();
1796 if !self.empty_path {
1797 write!(self, "::")?;
1800 if let DefPathDataName::Named(name) = name {
1801 if Ident::with_dummy_span(name).is_raw_guess() {
1802 write!(self, "r#")?;
1806 let verbose = self.tcx.sess.verbose();
1807 disambiguated_data.fmt_maybe_verbose(&mut self, verbose)?;
1809 self.empty_path = false;
1814 fn path_generic_args(
1816 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1817 args: &[GenericArg<'tcx>],
1818 ) -> Result<Self::Path, Self::Error> {
1819 self = print_prefix(self)?;
1821 // Don't print `'_` if there's no unerased regions.
1822 let print_regions = self.tcx.sess.verbose()
1823 || args.iter().any(|arg| match arg.unpack() {
1824 GenericArgKind::Lifetime(r) => !r.is_erased(),
1827 let args = args.iter().cloned().filter(|arg| match arg.unpack() {
1828 GenericArgKind::Lifetime(_) => print_regions,
1832 if args.clone().next().is_some() {
1834 write!(self, "::")?;
1836 self.generic_delimiters(|cx| cx.comma_sep(args))
1843 impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> {
1844 fn ty_infer_name(&self, id: ty::TyVid) -> Option<Symbol> {
1845 self.0.ty_infer_name_resolver.as_ref().and_then(|func| func(id))
1848 fn const_infer_name(&self, id: ty::ConstVid<'tcx>) -> Option<Symbol> {
1849 self.0.const_infer_name_resolver.as_ref().and_then(|func| func(id))
1852 fn print_value_path(
1855 substs: &'tcx [GenericArg<'tcx>],
1856 ) -> Result<Self::Path, Self::Error> {
1857 let was_in_value = std::mem::replace(&mut self.in_value, true);
1858 self = self.print_def_path(def_id, substs)?;
1859 self.in_value = was_in_value;
1864 fn in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, Self::Error>
1866 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1868 self.pretty_in_binder(value)
1871 fn wrap_binder<T, C: FnOnce(&T, Self) -> Result<Self, Self::Error>>(
1873 value: &ty::Binder<'tcx, T>,
1875 ) -> Result<Self, Self::Error>
1877 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1879 self.pretty_wrap_binder(value, f)
1884 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1885 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
1887 ) -> Result<Self::Const, Self::Error> {
1888 self.write_str("{")?;
1890 self.write_str(conversion)?;
1891 let was_in_value = std::mem::replace(&mut self.in_value, false);
1893 self.in_value = was_in_value;
1894 self.write_str("}")?;
1898 fn generic_delimiters(
1900 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1901 ) -> Result<Self, Self::Error> {
1904 let was_in_value = std::mem::replace(&mut self.in_value, false);
1905 let mut inner = f(self)?;
1906 inner.in_value = was_in_value;
1908 write!(inner, ">")?;
1912 fn should_print_region(&self, region: ty::Region<'tcx>) -> bool {
1913 let highlight = self.region_highlight_mode;
1914 if highlight.region_highlighted(region).is_some() {
1918 if self.tcx.sess.verbose() {
1922 let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
1925 ty::ReEarlyBound(ref data) => {
1926 data.name != kw::Empty && data.name != kw::UnderscoreLifetime
1929 ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
1930 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1931 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1932 if let ty::BrNamed(_, name) = br {
1933 if name != kw::Empty && name != kw::UnderscoreLifetime {
1938 if let Some((region, _)) = highlight.highlight_bound_region {
1947 ty::ReVar(_) if identify_regions => true,
1949 ty::ReVar(_) | ty::ReErased => false,
1951 ty::ReStatic | ty::ReEmpty(_) => true,
1955 fn pretty_print_const_pointer<Tag: Provenance>(
1960 ) -> Result<Self::Const, Self::Error> {
1961 let print = |mut this: Self| {
1962 define_scoped_cx!(this);
1963 if this.print_alloc_ids {
1964 p!(write("{:?}", p));
1971 self.typed_value(print, |this| this.print_type(ty), ": ")
1978 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1979 impl<'tcx> FmtPrinter<'_, 'tcx> {
1980 pub fn pretty_print_region(mut self, region: ty::Region<'tcx>) -> Result<Self, fmt::Error> {
1981 define_scoped_cx!(self);
1983 // Watch out for region highlights.
1984 let highlight = self.region_highlight_mode;
1985 if let Some(n) = highlight.region_highlighted(region) {
1986 p!(write("'{}", n));
1990 if self.tcx.sess.verbose() {
1991 p!(write("{:?}", region));
1995 let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
1997 // These printouts are concise. They do not contain all the information
1998 // the user might want to diagnose an error, but there is basically no way
1999 // to fit that into a short string. Hence the recommendation to use
2000 // `explain_region()` or `note_and_explain_region()`.
2002 ty::ReEarlyBound(ref data) => {
2003 if data.name != kw::Empty {
2004 p!(write("{}", data.name));
2008 ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
2009 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
2010 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
2011 if let ty::BrNamed(_, name) = br {
2012 if name != kw::Empty && name != kw::UnderscoreLifetime {
2013 p!(write("{}", name));
2018 if let Some((region, counter)) = highlight.highlight_bound_region {
2020 p!(write("'{}", counter));
2025 ty::ReVar(region_vid) if identify_regions => {
2026 p!(write("{:?}", region_vid));
2035 ty::ReEmpty(ty::UniverseIndex::ROOT) => {
2039 ty::ReEmpty(ui) => {
2040 p!(write("'<empty:{:?}>", ui));
2051 /// Folds through bound vars and placeholders, naming them
2052 struct RegionFolder<'a, 'tcx> {
2054 current_index: ty::DebruijnIndex,
2055 region_map: BTreeMap<ty::BoundRegion, ty::Region<'tcx>>,
2056 name: &'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a),
2059 impl<'a, 'tcx> ty::TypeFolder<'tcx> for RegionFolder<'a, 'tcx> {
2060 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
2064 fn fold_binder<T: TypeFoldable<'tcx>>(
2066 t: ty::Binder<'tcx, T>,
2067 ) -> ty::Binder<'tcx, T> {
2068 self.current_index.shift_in(1);
2069 let t = t.super_fold_with(self);
2070 self.current_index.shift_out(1);
2074 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
2076 _ if t.has_vars_bound_at_or_above(self.current_index) || t.has_placeholders() => {
2077 return t.super_fold_with(self);
2084 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
2085 let name = &mut self.name;
2086 let region = match *r {
2087 ty::ReLateBound(_, br) => *self.region_map.entry(br).or_insert_with(|| name(br)),
2088 ty::RePlaceholder(ty::PlaceholderRegion { name: kind, .. }) => {
2089 // If this is an anonymous placeholder, don't rename. Otherwise, in some
2090 // async fns, we get a `for<'r> Send` bound
2092 ty::BrAnon(_) | ty::BrEnv => r,
2094 // Index doesn't matter, since this is just for naming and these never get bound
2095 let br = ty::BoundRegion { var: ty::BoundVar::from_u32(0), kind };
2096 *self.region_map.entry(br).or_insert_with(|| name(br))
2102 if let ty::ReLateBound(debruijn1, br) = *region {
2103 assert_eq!(debruijn1, ty::INNERMOST);
2104 self.tcx.mk_region(ty::ReLateBound(self.current_index, br))
2111 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
2112 // `region_index` and `used_region_names`.
2113 impl<'tcx> FmtPrinter<'_, 'tcx> {
2114 pub fn name_all_regions<T>(
2116 value: &ty::Binder<'tcx, T>,
2117 ) -> Result<(Self, T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>), fmt::Error>
2119 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2121 fn name_by_region_index(index: usize) -> Symbol {
2123 0 => Symbol::intern("'r"),
2124 1 => Symbol::intern("'s"),
2125 i => Symbol::intern(&format!("'t{}", i - 2)),
2129 // Replace any anonymous late-bound regions with named
2130 // variants, using new unique identifiers, so that we can
2131 // clearly differentiate between named and unnamed regions in
2132 // the output. We'll probably want to tweak this over time to
2133 // decide just how much information to give.
2134 if self.binder_depth == 0 {
2135 self.prepare_late_bound_region_info(value);
2138 let mut empty = true;
2139 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
2146 let _ = write!(cx, "{}", w);
2148 let do_continue = |cx: &mut Self, cont: Symbol| {
2149 let _ = write!(cx, "{}", cont);
2152 define_scoped_cx!(self);
2154 let mut region_index = self.region_index;
2155 let mut next_name = |this: &Self| loop {
2156 let name = name_by_region_index(region_index);
2158 if !this.used_region_names.contains(&name) {
2163 // If we want to print verbosely, then print *all* binders, even if they
2164 // aren't named. Eventually, we might just want this as the default, but
2165 // this is not *quite* right and changes the ordering of some output
2167 let (new_value, map) = if self.tcx().sess.verbose() {
2168 let regions: Vec<_> = value
2172 let ty::BoundVariableKind::Region(var) = var else {
2173 // This doesn't really matter because it doesn't get used,
2174 // it's just an empty value
2175 return ty::BrAnon(0);
2178 ty::BrAnon(_) | ty::BrEnv => {
2179 start_or_continue(&mut self, "for<", ", ");
2180 let name = next_name(&self);
2181 do_continue(&mut self, name);
2182 ty::BrNamed(CRATE_DEF_ID.to_def_id(), name)
2184 ty::BrNamed(def_id, kw::UnderscoreLifetime) => {
2185 start_or_continue(&mut self, "for<", ", ");
2186 let name = next_name(&self);
2187 do_continue(&mut self, name);
2188 ty::BrNamed(def_id, name)
2190 ty::BrNamed(def_id, name) => {
2191 start_or_continue(&mut self, "for<", ", ");
2192 do_continue(&mut self, name);
2193 ty::BrNamed(def_id, name)
2198 start_or_continue(&mut self, "", "> ");
2200 self.tcx.replace_late_bound_regions(value.clone(), |br| {
2201 let kind = regions[br.var.as_usize()];
2202 self.tcx.mk_region(ty::ReLateBound(
2204 ty::BoundRegion { var: br.var, kind },
2209 let mut name = |br: ty::BoundRegion| {
2210 start_or_continue(&mut self, "for<", ", ");
2211 let kind = match br.kind {
2212 ty::BrAnon(_) | ty::BrEnv => {
2213 let name = next_name(&self);
2214 do_continue(&mut self, name);
2215 ty::BrNamed(CRATE_DEF_ID.to_def_id(), name)
2217 ty::BrNamed(def_id, kw::UnderscoreLifetime) => {
2218 let name = next_name(&self);
2219 do_continue(&mut self, name);
2220 ty::BrNamed(def_id, name)
2222 ty::BrNamed(_, name) => {
2223 do_continue(&mut self, name);
2227 tcx.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BoundRegion { var: br.var, kind }))
2229 let mut folder = RegionFolder {
2231 current_index: ty::INNERMOST,
2233 region_map: BTreeMap::new(),
2235 let new_value = value.clone().skip_binder().fold_with(&mut folder);
2236 let region_map = folder.region_map;
2237 start_or_continue(&mut self, "", "> ");
2238 (new_value, region_map)
2241 self.binder_depth += 1;
2242 self.region_index = region_index;
2243 Ok((self, new_value, map))
2246 pub fn pretty_in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, fmt::Error>
2248 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2250 let old_region_index = self.region_index;
2251 let (new, new_value, _) = self.name_all_regions(value)?;
2252 let mut inner = new_value.print(new)?;
2253 inner.region_index = old_region_index;
2254 inner.binder_depth -= 1;
2258 pub fn pretty_wrap_binder<T, C: FnOnce(&T, Self) -> Result<Self, fmt::Error>>(
2260 value: &ty::Binder<'tcx, T>,
2262 ) -> Result<Self, fmt::Error>
2264 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2266 let old_region_index = self.region_index;
2267 let (new, new_value, _) = self.name_all_regions(value)?;
2268 let mut inner = f(&new_value, new)?;
2269 inner.region_index = old_region_index;
2270 inner.binder_depth -= 1;
2274 fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<'tcx, T>)
2276 T: TypeVisitable<'tcx>,
2278 struct LateBoundRegionNameCollector<'a, 'tcx> {
2279 used_region_names: &'a mut FxHashSet<Symbol>,
2280 type_collector: SsoHashSet<Ty<'tcx>>,
2283 impl<'tcx> ty::visit::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_, 'tcx> {
2286 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
2287 trace!("address: {:p}", r.0.0);
2288 if let ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name), .. }) = *r {
2289 self.used_region_names.insert(name);
2290 } else if let ty::RePlaceholder(ty::PlaceholderRegion {
2291 name: ty::BrNamed(_, name),
2295 self.used_region_names.insert(name);
2297 r.super_visit_with(self)
2300 // We collect types in order to prevent really large types from compiling for
2301 // a really long time. See issue #83150 for why this is necessary.
2302 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
2303 let not_previously_inserted = self.type_collector.insert(ty);
2304 if not_previously_inserted {
2305 ty.super_visit_with(self)
2307 ControlFlow::CONTINUE
2312 self.used_region_names.clear();
2313 let mut collector = LateBoundRegionNameCollector {
2314 used_region_names: &mut self.used_region_names,
2315 type_collector: SsoHashSet::new(),
2317 value.visit_with(&mut collector);
2318 self.region_index = 0;
2322 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<'tcx, T>
2324 T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
2327 type Error = P::Error;
2329 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
2334 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
2336 T: Print<'tcx, P, Output = P, Error = P::Error>,
2337 U: Print<'tcx, P, Output = P, Error = P::Error>,
2340 type Error = P::Error;
2341 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
2342 define_scoped_cx!(cx);
2343 p!(print(self.0), ": ", print(self.1));
2348 macro_rules! forward_display_to_print {
2350 // Some of the $ty arguments may not actually use 'tcx
2351 $(#[allow(unused_lifetimes)] impl<'tcx> fmt::Display for $ty {
2352 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2353 ty::tls::with(|tcx| {
2354 let cx = tcx.lift(*self)
2355 .expect("could not lift for printing")
2356 .print(FmtPrinter::new(tcx, Namespace::TypeNS))?;
2357 f.write_str(&cx.into_buffer())?;
2365 macro_rules! define_print_and_forward_display {
2366 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
2367 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
2369 type Error = fmt::Error;
2370 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
2371 #[allow(unused_mut)]
2373 define_scoped_cx!($cx);
2375 #[allow(unreachable_code)]
2380 forward_display_to_print!($($ty),+);
2384 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2385 /// the trait path. That is, it will print `Trait<U>` instead of
2386 /// `<T as Trait<U>>`.
2387 #[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
2388 pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
2390 impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
2391 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2392 fmt::Display::fmt(self, f)
2396 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2397 /// the trait name. That is, it will print `Trait` instead of
2398 /// `<T as Trait<U>>`.
2399 #[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
2400 pub struct TraitRefPrintOnlyTraitName<'tcx>(ty::TraitRef<'tcx>);
2402 impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitName<'tcx> {
2403 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2404 fmt::Display::fmt(self, f)
2408 impl<'tcx> ty::TraitRef<'tcx> {
2409 pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
2410 TraitRefPrintOnlyTraitPath(self)
2413 pub fn print_only_trait_name(self) -> TraitRefPrintOnlyTraitName<'tcx> {
2414 TraitRefPrintOnlyTraitName(self)
2418 impl<'tcx> ty::Binder<'tcx, ty::TraitRef<'tcx>> {
2419 pub fn print_only_trait_path(self) -> ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>> {
2420 self.map_bound(|tr| tr.print_only_trait_path())
2424 #[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
2425 pub struct TraitPredPrintModifiersAndPath<'tcx>(ty::TraitPredicate<'tcx>);
2427 impl<'tcx> fmt::Debug for TraitPredPrintModifiersAndPath<'tcx> {
2428 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2429 fmt::Display::fmt(self, f)
2433 impl<'tcx> ty::TraitPredicate<'tcx> {
2434 pub fn print_modifiers_and_trait_path(self) -> TraitPredPrintModifiersAndPath<'tcx> {
2435 TraitPredPrintModifiersAndPath(self)
2439 impl<'tcx> ty::PolyTraitPredicate<'tcx> {
2440 pub fn print_modifiers_and_trait_path(
2442 ) -> ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>> {
2443 self.map_bound(TraitPredPrintModifiersAndPath)
2447 forward_display_to_print! {
2450 &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
2453 // HACK(eddyb) these are exhaustive instead of generic,
2454 // because `for<'tcx>` isn't possible yet.
2455 ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>,
2456 ty::Binder<'tcx, ty::TraitRef<'tcx>>,
2457 ty::Binder<'tcx, ty::ExistentialTraitRef<'tcx>>,
2458 ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>>,
2459 ty::Binder<'tcx, TraitRefPrintOnlyTraitName<'tcx>>,
2460 ty::Binder<'tcx, ty::FnSig<'tcx>>,
2461 ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2462 ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>>,
2463 ty::Binder<'tcx, ty::SubtypePredicate<'tcx>>,
2464 ty::Binder<'tcx, ty::ProjectionPredicate<'tcx>>,
2465 ty::Binder<'tcx, ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
2466 ty::Binder<'tcx, ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
2468 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
2469 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
2472 define_print_and_forward_display! {
2475 &'tcx ty::List<Ty<'tcx>> {
2476 p!("{{", comma_sep(self.iter()), "}}")
2479 ty::TypeAndMut<'tcx> {
2480 p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
2483 ty::ExistentialTraitRef<'tcx> {
2484 // Use a type that can't appear in defaults of type parameters.
2485 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
2486 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
2487 p!(print(trait_ref.print_only_trait_path()))
2490 ty::ExistentialProjection<'tcx> {
2491 let name = cx.tcx().associated_item(self.item_def_id).name;
2492 p!(write("{} = ", name), print(self.term))
2495 ty::ExistentialPredicate<'tcx> {
2497 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
2498 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
2499 ty::ExistentialPredicate::AutoTrait(def_id) => {
2500 p!(print_def_path(def_id, &[]));
2506 p!(write("{}", self.unsafety.prefix_str()));
2508 if self.abi != Abi::Rust {
2509 p!(write("extern {} ", self.abi));
2512 p!("fn", pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
2515 ty::TraitRef<'tcx> {
2516 p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
2519 TraitRefPrintOnlyTraitPath<'tcx> {
2520 p!(print_def_path(self.0.def_id, self.0.substs));
2523 TraitRefPrintOnlyTraitName<'tcx> {
2524 p!(print_def_path(self.0.def_id, &[]));
2527 TraitPredPrintModifiersAndPath<'tcx> {
2528 if let ty::BoundConstness::ConstIfConst = self.0.constness {
2532 if let ty::ImplPolarity::Negative = self.0.polarity {
2536 p!(print(self.0.trait_ref.print_only_trait_path()));
2540 p!(write("{}", self.name))
2544 p!(write("{}", self.name))
2547 ty::SubtypePredicate<'tcx> {
2548 p!(print(self.a), " <: ", print(self.b))
2551 ty::CoercePredicate<'tcx> {
2552 p!(print(self.a), " -> ", print(self.b))
2555 ty::TraitPredicate<'tcx> {
2556 p!(print(self.trait_ref.self_ty()), ": ");
2557 if let ty::BoundConstness::ConstIfConst = self.constness {
2560 p!(print(self.trait_ref.print_only_trait_path()))
2563 ty::ProjectionPredicate<'tcx> {
2564 p!(print(self.projection_ty), " == ", print(self.term))
2569 ty::Term::Ty(ty) => p!(print(ty)),
2570 ty::Term::Const(c) => p!(print(c)),
2574 ty::ProjectionTy<'tcx> {
2575 p!(print_def_path(self.item_def_id, self.substs));
2580 ty::ClosureKind::Fn => p!("Fn"),
2581 ty::ClosureKind::FnMut => p!("FnMut"),
2582 ty::ClosureKind::FnOnce => p!("FnOnce"),
2586 ty::Predicate<'tcx> {
2587 let binder = self.kind();
2591 ty::PredicateKind<'tcx> {
2593 ty::PredicateKind::Trait(ref data) => {
2596 ty::PredicateKind::Subtype(predicate) => p!(print(predicate)),
2597 ty::PredicateKind::Coerce(predicate) => p!(print(predicate)),
2598 ty::PredicateKind::RegionOutlives(predicate) => p!(print(predicate)),
2599 ty::PredicateKind::TypeOutlives(predicate) => p!(print(predicate)),
2600 ty::PredicateKind::Projection(predicate) => p!(print(predicate)),
2601 ty::PredicateKind::WellFormed(arg) => p!(print(arg), " well-formed"),
2602 ty::PredicateKind::ObjectSafe(trait_def_id) => {
2603 p!("the trait `", print_def_path(trait_def_id, &[]), "` is object-safe")
2605 ty::PredicateKind::ClosureKind(closure_def_id, _closure_substs, kind) => {
2607 print_value_path(closure_def_id, &[]),
2608 write("` implements the trait `{}`", kind))
2610 ty::PredicateKind::ConstEvaluatable(uv) => {
2611 p!("the constant `", print_value_path(uv.def.did, uv.substs), "` can be evaluated")
2613 ty::PredicateKind::ConstEquate(c1, c2) => {
2614 p!("the constant `", print(c1), "` equals `", print(c2), "`")
2616 ty::PredicateKind::TypeWellFormedFromEnv(ty) => {
2617 p!("the type `", print(ty), "` is found in the environment")
2623 match self.unpack() {
2624 GenericArgKind::Lifetime(lt) => p!(print(lt)),
2625 GenericArgKind::Type(ty) => p!(print(ty)),
2626 GenericArgKind::Const(ct) => p!(print(ct)),
2631 fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
2632 // Iterate all local crate items no matter where they are defined.
2633 let hir = tcx.hir();
2634 for id in hir.items() {
2635 if matches!(tcx.def_kind(id.def_id), DefKind::Use) {
2639 let item = hir.item(id);
2640 if item.ident.name == kw::Empty {
2644 let def_id = item.def_id.to_def_id();
2645 let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
2646 collect_fn(&item.ident, ns, def_id);
2649 // Now take care of extern crate items.
2650 let queue = &mut Vec::new();
2651 let mut seen_defs: DefIdSet = Default::default();
2653 for &cnum in tcx.crates(()).iter() {
2654 let def_id = cnum.as_def_id();
2656 // Ignore crates that are not direct dependencies.
2657 match tcx.extern_crate(def_id) {
2659 Some(extern_crate) => {
2660 if !extern_crate.is_direct() {
2669 // Iterate external crate defs but be mindful about visibility
2670 while let Some(def) = queue.pop() {
2671 for child in tcx.module_children(def).iter() {
2672 if !child.vis.is_public() {
2677 def::Res::Def(DefKind::AssocTy, _) => {}
2678 def::Res::Def(DefKind::TyAlias, _) => {}
2679 def::Res::Def(defkind, def_id) => {
2680 if let Some(ns) = defkind.ns() {
2681 collect_fn(&child.ident, ns, def_id);
2684 if matches!(defkind, DefKind::Mod | DefKind::Enum | DefKind::Trait)
2685 && seen_defs.insert(def_id)
2696 /// The purpose of this function is to collect public symbols names that are unique across all
2697 /// crates in the build. Later, when printing about types we can use those names instead of the
2698 /// full exported path to them.
2700 /// So essentially, if a symbol name can only be imported from one place for a type, and as
2701 /// long as it was not glob-imported anywhere in the current crate, we can trim its printed
2702 /// path and print only the name.
2704 /// This has wide implications on error messages with types, for example, shortening
2705 /// `std::vec::Vec` to just `Vec`, as long as there is no other `Vec` importable anywhere.
2707 /// The implementation uses similar import discovery logic to that of 'use' suggestions.
2708 fn trimmed_def_paths(tcx: TyCtxt<'_>, (): ()) -> FxHashMap<DefId, Symbol> {
2709 let mut map: FxHashMap<DefId, Symbol> = FxHashMap::default();
2711 if let TrimmedDefPaths::GoodPath = tcx.sess.opts.trimmed_def_paths {
2712 // For good paths causing this bug, the `rustc_middle::ty::print::with_no_trimmed_paths`
2713 // wrapper can be used to suppress this query, in exchange for full paths being formatted.
2714 tcx.sess.delay_good_path_bug("trimmed_def_paths constructed");
2717 let unique_symbols_rev: &mut FxHashMap<(Namespace, Symbol), Option<DefId>> =
2718 &mut FxHashMap::default();
2720 for symbol_set in tcx.resolutions(()).glob_map.values() {
2721 for symbol in symbol_set {
2722 unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
2723 unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
2724 unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
2728 for_each_def(tcx, |ident, ns, def_id| {
2729 use std::collections::hash_map::Entry::{Occupied, Vacant};
2731 match unique_symbols_rev.entry((ns, ident.name)) {
2732 Occupied(mut v) => match v.get() {
2735 if *existing != def_id {
2741 v.insert(Some(def_id));
2746 for ((_, symbol), opt_def_id) in unique_symbols_rev.drain() {
2747 use std::collections::hash_map::Entry::{Occupied, Vacant};
2749 if let Some(def_id) = opt_def_id {
2750 match map.entry(def_id) {
2751 Occupied(mut v) => {
2752 // A single DefId can be known under multiple names (e.g.,
2753 // with a `pub use ... as ...;`). We need to ensure that the
2754 // name placed in this map is chosen deterministically, so
2755 // if we find multiple names (`symbol`) resolving to the
2756 // same `def_id`, we prefer the lexicographically smallest
2759 // Any stable ordering would be fine here though.
2760 if *v.get() != symbol {
2761 if v.get().as_str() > symbol.as_str() {
2776 pub fn provide(providers: &mut ty::query::Providers) {
2777 *providers = ty::query::Providers { trimmed_def_paths, ..*providers };
2781 pub struct OpaqueFnEntry<'tcx> {
2782 // The trait ref is already stored as a key, so just track if we have it as a real predicate
2784 fn_mut_trait_ref: Option<ty::PolyTraitRef<'tcx>>,
2785 fn_trait_ref: Option<ty::PolyTraitRef<'tcx>>,
2786 return_ty: Option<ty::Binder<'tcx, Term<'tcx>>>,