1 use crate::mir::interpret::{AllocRange, GlobalAlloc, Pointer, Provenance, Scalar};
3 self, ConstInt, DefIdTree, ParamConst, ScalarInt, Term, TermKind, Ty, TyCtxt, TypeFoldable,
4 TypeSuperFoldable, TypeSuperVisitable, TypeVisitable,
6 use crate::ty::{GenericArg, GenericArgKind};
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::{DefKey, DefPathData, DefPathDataName, DisambiguatedDefPathData};
14 use rustc_hir::LangItem;
15 use rustc_session::config::TrimmedDefPaths;
16 use rustc_session::cstore::{ExternCrate, ExternCrateSource};
17 use rustc_session::Limit;
18 use rustc_span::symbol::{kw, Ident, Symbol};
19 use rustc_span::FileNameDisplayPreference;
20 use rustc_target::abi::Size;
21 use rustc_target::spec::abi::Abi;
22 use smallvec::SmallVec;
26 use std::collections::BTreeMap;
27 use std::fmt::{self, Write as _};
29 use std::ops::{ControlFlow, Deref, DerefMut};
31 // `pretty` is a separate module only for organization.
36 write!(scoped_cx!(), $lit)?
38 (@write($($data:expr),+)) => {
39 write!(scoped_cx!(), $($data),+)?
41 (@print($x:expr)) => {
42 scoped_cx!() = $x.print(scoped_cx!())?
44 (@$method:ident($($arg:expr),*)) => {
45 scoped_cx!() = scoped_cx!().$method($($arg),*)?
47 ($($elem:tt $(($($args:tt)*))?),+) => {{
48 $(p!(@ $elem $(($($args)*))?);)+
51 macro_rules! define_scoped_cx {
53 #[allow(unused_macros)]
54 macro_rules! scoped_cx {
63 static FORCE_IMPL_FILENAME_LINE: Cell<bool> = const { Cell::new(false) };
64 static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = const { Cell::new(false) };
65 static NO_TRIMMED_PATH: Cell<bool> = const { Cell::new(false) };
66 static FORCE_TRIMMED_PATH: Cell<bool> = const { Cell::new(false) };
67 static NO_QUERIES: Cell<bool> = const { Cell::new(false) };
68 static NO_VISIBLE_PATH: Cell<bool> = const { Cell::new(false) };
71 macro_rules! define_helper {
72 ($($(#[$a:meta])* fn $name:ident($helper:ident, $tl:ident);)+) => {
75 pub struct $helper(bool);
78 pub fn new() -> $helper {
79 $helper($tl.with(|c| c.replace(true)))
84 pub macro $name($e:expr) {
86 let _guard = $helper::new();
91 impl Drop for $helper {
93 $tl.with(|c| c.set(self.0))
101 /// Avoids running any queries during any prints that occur
102 /// during the closure. This may alter the appearance of some
103 /// types (e.g. forcing verbose printing for opaque types).
104 /// This method is used during some queries (e.g. `explicit_item_bounds`
105 /// for opaque types), to ensure that any debug printing that
106 /// occurs during the query computation does not end up recursively
107 /// calling the same query.
108 fn with_no_queries(NoQueriesGuard, NO_QUERIES);
109 /// Force us to name impls with just the filename/line number. We
110 /// normally try to use types. But at some points, notably while printing
111 /// cycle errors, this can result in extra or suboptimal error output,
112 /// so this variable disables that check.
113 fn with_forced_impl_filename_line(ForcedImplGuard, FORCE_IMPL_FILENAME_LINE);
114 /// Adds the `crate::` prefix to paths where appropriate.
115 fn with_crate_prefix(CratePrefixGuard, SHOULD_PREFIX_WITH_CRATE);
116 /// Prevent path trimming if it is turned on. Path trimming affects `Display` impl
117 /// of various rustc types, for example `std::vec::Vec` would be trimmed to `Vec`,
118 /// if no other `Vec` is found.
119 fn with_no_trimmed_paths(NoTrimmedGuard, NO_TRIMMED_PATH);
120 fn with_forced_trimmed_paths(ForceTrimmedGuard, FORCE_TRIMMED_PATH);
121 /// Prevent selection of visible paths. `Display` impl of DefId will prefer
122 /// visible (public) reexports of types as paths.
123 fn with_no_visible_paths(NoVisibleGuard, NO_VISIBLE_PATH);
126 /// The "region highlights" are used to control region printing during
127 /// specific error messages. When a "region highlight" is enabled, it
128 /// gives an alternate way to print specific regions. For now, we
129 /// always print those regions using a number, so something like "`'0`".
131 /// Regions not selected by the region highlight mode are presently
133 #[derive(Copy, Clone)]
134 pub struct RegionHighlightMode<'tcx> {
137 /// If enabled, when we see the selected region, use "`'N`"
138 /// instead of the ordinary behavior.
139 highlight_regions: [Option<(ty::Region<'tcx>, usize)>; 3],
141 /// If enabled, when printing a "free region" that originated from
142 /// the given `ty::BoundRegionKind`, print it as "`'1`". Free regions that would ordinarily
143 /// have names print as normal.
145 /// This is used when you have a signature like `fn foo(x: &u32,
146 /// y: &'a u32)` and we want to give a name to the region of the
148 highlight_bound_region: Option<(ty::BoundRegionKind, usize)>,
151 impl<'tcx> RegionHighlightMode<'tcx> {
152 pub fn new(tcx: TyCtxt<'tcx>) -> Self {
155 highlight_regions: Default::default(),
156 highlight_bound_region: Default::default(),
160 /// If `region` and `number` are both `Some`, invokes
161 /// `highlighting_region`.
162 pub fn maybe_highlighting_region(
164 region: Option<ty::Region<'tcx>>,
165 number: Option<usize>,
167 if let Some(k) = region {
168 if let Some(n) = number {
169 self.highlighting_region(k, n);
174 /// Highlights the region inference variable `vid` as `'N`.
175 pub fn highlighting_region(&mut self, region: ty::Region<'tcx>, number: usize) {
176 let num_slots = self.highlight_regions.len();
177 let first_avail_slot =
178 self.highlight_regions.iter_mut().find(|s| s.is_none()).unwrap_or_else(|| {
179 bug!("can only highlight {} placeholders at a time", num_slots,)
181 *first_avail_slot = Some((region, number));
184 /// Convenience wrapper for `highlighting_region`.
185 pub fn highlighting_region_vid(&mut self, vid: ty::RegionVid, number: usize) {
186 self.highlighting_region(self.tcx.mk_region(ty::ReVar(vid)), number)
189 /// Returns `Some(n)` with the number to use for the given region, if any.
190 fn region_highlighted(&self, region: ty::Region<'tcx>) -> Option<usize> {
191 self.highlight_regions.iter().find_map(|h| match h {
192 Some((r, n)) if *r == region => Some(*n),
197 /// Highlight the given bound region.
198 /// We can only highlight one bound region at a time. See
199 /// the field `highlight_bound_region` for more detailed notes.
200 pub fn highlighting_bound_region(&mut self, br: ty::BoundRegionKind, number: usize) {
201 assert!(self.highlight_bound_region.is_none());
202 self.highlight_bound_region = Some((br, number));
206 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
207 pub trait PrettyPrinter<'tcx>:
214 DynExistential = Self,
218 /// Like `print_def_path` but for value paths.
222 substs: &'tcx [GenericArg<'tcx>],
223 ) -> Result<Self::Path, Self::Error> {
224 self.print_def_path(def_id, substs)
227 fn in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, Self::Error>
229 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
231 value.as_ref().skip_binder().print(self)
234 fn wrap_binder<T, F: FnOnce(&T, Self) -> Result<Self, fmt::Error>>(
236 value: &ty::Binder<'tcx, T>,
238 ) -> Result<Self, Self::Error>
240 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
242 f(value.as_ref().skip_binder(), self)
245 /// Prints comma-separated elements.
246 fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
248 T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
250 if let Some(first) = elems.next() {
251 self = first.print(self)?;
253 self.write_str(", ")?;
254 self = elem.print(self)?;
260 /// Prints `{f: t}` or `{f as t}` depending on the `cast` argument
263 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
264 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
266 ) -> Result<Self::Const, Self::Error> {
267 self.write_str("{")?;
269 self.write_str(conversion)?;
271 self.write_str("}")?;
275 /// Prints `<...>` around what `f` prints.
276 fn generic_delimiters(
278 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
279 ) -> Result<Self, Self::Error>;
281 /// Returns `true` if the region should be printed in
282 /// optional positions, e.g., `&'a T` or `dyn Tr + 'b`.
283 /// This is typically the case for all non-`'_` regions.
284 fn should_print_region(&self, region: ty::Region<'tcx>) -> bool;
286 fn reset_type_limit(&mut self) {}
288 // Defaults (should not be overridden):
290 /// If possible, this returns a global path resolving to `def_id` that is visible
291 /// from at least one local module, and returns `true`. If the crate defining `def_id` is
292 /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
293 fn try_print_visible_def_path(self, def_id: DefId) -> Result<(Self, bool), Self::Error> {
294 if NO_VISIBLE_PATH.with(|flag| flag.get()) {
295 return Ok((self, false));
298 let mut callers = Vec::new();
299 self.try_print_visible_def_path_recur(def_id, &mut callers)
302 // Given a `DefId`, produce a short name. For types and traits, it prints *only* its name,
303 // For associated items on traits it prints out the trait's name and the associated item's name.
304 // For enum variants, if they have an unique name, then we only print the name, otherwise we
305 // print the enum name and the variant name. Otherwise, we do not print anything and let the
306 // caller use the `print_def_path` fallback.
307 fn force_print_trimmed_def_path(
310 ) -> Result<(Self::Path, bool), Self::Error> {
311 let key = self.tcx().def_key(def_id);
312 let visible_parent_map = self.tcx().visible_parent_map(());
313 let kind = self.tcx().def_kind(def_id);
315 let get_local_name = |this: &Self, name, def_id, key: DefKey| {
316 if let Some(visible_parent) = visible_parent_map.get(&def_id)
317 && let actual_parent = this.tcx().opt_parent(def_id)
318 && let DefPathData::TypeNs(_) = key.disambiguated_data.data
319 && Some(*visible_parent) != actual_parent
323 .module_children(visible_parent)
325 .filter(|child| child.res.opt_def_id() == Some(def_id))
326 .find(|child| child.vis.is_public() && child.ident.name != kw::Underscore)
327 .map(|child| child.ident.name)
333 if let DefKind::Variant = kind
334 && let Some(symbol) = self.tcx().trimmed_def_paths(()).get(&def_id)
336 // If `Assoc` is unique, we don't want to talk about `Trait::Assoc`.
337 self.write_str(get_local_name(&self, *symbol, def_id, key).as_str())?;
338 return Ok((self, true));
340 if let Some(symbol) = key.get_opt_name() {
341 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = kind
342 && let Some(parent) = self.tcx().opt_parent(def_id)
343 && let parent_key = self.tcx().def_key(parent)
344 && let Some(symbol) = parent_key.get_opt_name()
347 self.write_str(get_local_name(&self, symbol, parent, parent_key).as_str())?;
348 self.write_str("::")?;
349 } else if let DefKind::Variant = kind
350 && let Some(parent) = self.tcx().opt_parent(def_id)
351 && let parent_key = self.tcx().def_key(parent)
352 && let Some(symbol) = parent_key.get_opt_name()
356 // For associated items and variants, we want the "full" path, namely, include
357 // the parent type in the path. For example, `Iterator::Item`.
358 self.write_str(get_local_name(&self, symbol, parent, parent_key).as_str())?;
359 self.write_str("::")?;
360 } else if let DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::Trait
361 | DefKind::TyAlias | DefKind::Fn | DefKind::Const | DefKind::Static(_) = kind
364 // If not covered above, like for example items out of `impl` blocks, fallback.
365 return Ok((self, false));
367 self.write_str(get_local_name(&self, symbol, def_id, key).as_str())?;
368 return Ok((self, true));
373 /// Try to see if this path can be trimmed to a unique symbol name.
374 fn try_print_trimmed_def_path(
377 ) -> Result<(Self::Path, bool), Self::Error> {
378 if FORCE_TRIMMED_PATH.with(|flag| flag.get()) {
379 let (s, trimmed) = self.force_print_trimmed_def_path(def_id)?;
381 return Ok((s, true));
385 if !self.tcx().sess.opts.unstable_opts.trim_diagnostic_paths
386 || matches!(self.tcx().sess.opts.trimmed_def_paths, TrimmedDefPaths::Never)
387 || NO_TRIMMED_PATH.with(|flag| flag.get())
388 || SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get())
390 return Ok((self, false));
393 match self.tcx().trimmed_def_paths(()).get(&def_id) {
394 None => Ok((self, false)),
396 write!(self, "{}", Ident::with_dummy_span(*symbol))?;
402 /// Does the work of `try_print_visible_def_path`, building the
403 /// full definition path recursively before attempting to
404 /// post-process it into the valid and visible version that
405 /// accounts for re-exports.
407 /// This method should only be called by itself or
408 /// `try_print_visible_def_path`.
410 /// `callers` is a chain of visible_parent's leading to `def_id`,
411 /// to support cycle detection during recursion.
413 /// This method returns false if we can't print the visible path, so
414 /// `print_def_path` can fall back on the item's real definition path.
415 fn try_print_visible_def_path_recur(
418 callers: &mut Vec<DefId>,
419 ) -> Result<(Self, bool), Self::Error> {
420 define_scoped_cx!(self);
422 debug!("try_print_visible_def_path: def_id={:?}", def_id);
424 // If `def_id` is a direct or injected extern crate, return the
425 // path to the crate followed by the path to the item within the crate.
426 if let Some(cnum) = def_id.as_crate_root() {
427 if cnum == LOCAL_CRATE {
428 return Ok((self.path_crate(cnum)?, true));
431 // In local mode, when we encounter a crate other than
432 // LOCAL_CRATE, execution proceeds in one of two ways:
434 // 1. For a direct dependency, where user added an
435 // `extern crate` manually, we put the `extern
436 // crate` as the parent. So you wind up with
437 // something relative to the current crate.
438 // 2. For an extern inferred from a path or an indirect crate,
439 // where there is no explicit `extern crate`, we just prepend
441 match self.tcx().extern_crate(def_id) {
442 Some(&ExternCrate { src, dependency_of, span, .. }) => match (src, dependency_of) {
443 (ExternCrateSource::Extern(def_id), LOCAL_CRATE) => {
444 // NOTE(eddyb) the only reason `span` might be dummy,
445 // that we're aware of, is that it's the `std`/`core`
446 // `extern crate` injected by default.
447 // FIXME(eddyb) find something better to key this on,
448 // or avoid ending up with `ExternCrateSource::Extern`,
449 // for the injected `std`/`core`.
451 return Ok((self.path_crate(cnum)?, true));
454 // Disable `try_print_trimmed_def_path` behavior within
455 // the `print_def_path` call, to avoid infinite recursion
456 // in cases where the `extern crate foo` has non-trivial
457 // parents, e.g. it's nested in `impl foo::Trait for Bar`
458 // (see also issues #55779 and #87932).
459 self = with_no_visible_paths!(self.print_def_path(def_id, &[])?);
461 return Ok((self, true));
463 (ExternCrateSource::Path, LOCAL_CRATE) => {
464 return Ok((self.path_crate(cnum)?, true));
469 return Ok((self.path_crate(cnum)?, true));
474 if def_id.is_local() {
475 return Ok((self, false));
478 let visible_parent_map = self.tcx().visible_parent_map(());
480 let mut cur_def_key = self.tcx().def_key(def_id);
481 debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
483 // For a constructor, we want the name of its parent rather than <unnamed>.
484 if let DefPathData::Ctor = cur_def_key.disambiguated_data.data {
489 .expect("`DefPathData::Ctor` / `VariantData` missing a parent"),
492 cur_def_key = self.tcx().def_key(parent);
495 let Some(visible_parent) = visible_parent_map.get(&def_id).cloned() else {
496 return Ok((self, false));
499 let actual_parent = self.tcx().opt_parent(def_id);
501 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
502 visible_parent, actual_parent,
505 let mut data = cur_def_key.disambiguated_data.data;
507 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
508 data, visible_parent, actual_parent,
512 // In order to output a path that could actually be imported (valid and visible),
513 // we need to handle re-exports correctly.
515 // For example, take `std::os::unix::process::CommandExt`, this trait is actually
516 // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
518 // `std::os::unix` reexports the contents of `std::sys::unix::ext`. `std::sys` is
519 // private so the "true" path to `CommandExt` isn't accessible.
521 // In this case, the `visible_parent_map` will look something like this:
523 // (child) -> (parent)
524 // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
525 // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
526 // `std::sys::unix::ext` -> `std::os`
528 // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
531 // When printing the path to `CommandExt` and looking at the `cur_def_key` that
532 // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
533 // to the parent - resulting in a mangled path like
534 // `std::os::ext::process::CommandExt`.
536 // Instead, we must detect that there was a re-export and instead print `unix`
537 // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
538 // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
539 // the visible parent (`std::os`). If these do not match, then we iterate over
540 // the children of the visible parent (as was done when computing
541 // `visible_parent_map`), looking for the specific child we currently have and then
542 // have access to the re-exported name.
543 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
544 // Item might be re-exported several times, but filter for the one
545 // that's public and whose identifier isn't `_`.
548 .module_children(visible_parent)
550 .filter(|child| child.res.opt_def_id() == Some(def_id))
551 .find(|child| child.vis.is_public() && child.ident.name != kw::Underscore)
552 .map(|child| child.ident.name);
554 if let Some(new_name) = reexport {
557 // There is no name that is public and isn't `_`, so bail.
558 return Ok((self, false));
561 // Re-exported `extern crate` (#43189).
562 DefPathData::CrateRoot => {
563 data = DefPathData::TypeNs(self.tcx().crate_name(def_id.krate));
567 debug!("try_print_visible_def_path: data={:?}", data);
569 if callers.contains(&visible_parent) {
570 return Ok((self, false));
572 callers.push(visible_parent);
573 // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
574 // knowing ahead of time whether the entire path will succeed or not.
575 // To support printers that do not implement `PrettyPrinter`, a `Vec` or
576 // linked list on the stack would need to be built, before any printing.
577 match self.try_print_visible_def_path_recur(visible_parent, callers)? {
578 (cx, false) => return Ok((cx, false)),
579 (cx, true) => self = cx,
583 Ok((self.path_append(Ok, &DisambiguatedDefPathData { data, disambiguator: 0 })?, true))
586 fn pretty_path_qualified(
589 trait_ref: Option<ty::TraitRef<'tcx>>,
590 ) -> Result<Self::Path, Self::Error> {
591 if trait_ref.is_none() {
592 // Inherent impls. Try to print `Foo::bar` for an inherent
593 // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
594 // anything other than a simple path.
595 match self_ty.kind() {
604 return self_ty.print(self);
611 self.generic_delimiters(|mut cx| {
612 define_scoped_cx!(cx);
615 if let Some(trait_ref) = trait_ref {
616 p!(" as ", print(trait_ref.print_only_trait_path()));
622 fn pretty_path_append_impl(
624 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
626 trait_ref: Option<ty::TraitRef<'tcx>>,
627 ) -> Result<Self::Path, Self::Error> {
628 self = print_prefix(self)?;
630 self.generic_delimiters(|mut cx| {
631 define_scoped_cx!(cx);
634 if let Some(trait_ref) = trait_ref {
635 p!(print(trait_ref.print_only_trait_path()), " for ");
643 fn pretty_print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
644 define_scoped_cx!(self);
647 ty::Bool => p!("bool"),
648 ty::Char => p!("char"),
649 ty::Int(t) => p!(write("{}", t.name_str())),
650 ty::Uint(t) => p!(write("{}", t.name_str())),
651 ty::Float(t) => p!(write("{}", t.name_str())),
652 ty::RawPtr(ref tm) => {
656 hir::Mutability::Mut => "mut",
657 hir::Mutability::Not => "const",
662 ty::Ref(r, ty, mutbl) => {
664 if self.should_print_region(r) {
667 p!(print(ty::TypeAndMut { ty, mutbl }))
669 ty::Never => p!("!"),
670 ty::Tuple(ref tys) => {
671 p!("(", comma_sep(tys.iter()));
677 ty::FnDef(def_id, substs) => {
678 let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs);
679 p!(print(sig), " {{", print_value_path(def_id, substs), "}}");
681 ty::FnPtr(ref bare_fn) => p!(print(bare_fn)),
682 ty::Infer(infer_ty) => {
683 let verbose = self.should_print_verbose();
684 if let ty::TyVar(ty_vid) = infer_ty {
685 if let Some(name) = self.ty_infer_name(ty_vid) {
686 p!(write("{}", name))
689 p!(write("{:?}", infer_ty))
691 p!(write("{}", infer_ty))
695 if verbose { p!(write("{:?}", infer_ty)) } else { p!(write("{}", infer_ty)) }
698 ty::Error(_) => p!("[type error]"),
699 ty::Param(ref param_ty) => p!(print(param_ty)),
700 ty::Bound(debruijn, bound_ty) => match bound_ty.kind {
701 ty::BoundTyKind::Anon(bv) => {
702 self.pretty_print_bound_var(debruijn, ty::BoundVar::from_u32(bv))?
704 ty::BoundTyKind::Param(_, s) => p!(write("{}", s)),
706 ty::Adt(def, substs) => {
707 p!(print_def_path(def.did(), substs));
709 ty::Dynamic(data, r, repr) => {
710 let print_r = self.should_print_region(r);
715 ty::Dyn => p!("dyn "),
716 ty::DynStar => p!("dyn* "),
720 p!(" + ", print(r), ")");
723 ty::Foreign(def_id) => {
724 p!(print_def_path(def_id, &[]));
726 ty::Alias(ty::Projection, ref data) => {
727 if !(self.should_print_verbose() || NO_QUERIES.with(|q| q.get()))
728 && self.tcx().def_kind(data.def_id) == DefKind::ImplTraitPlaceholder
730 return self.pretty_print_opaque_impl_type(data.def_id, data.substs);
735 ty::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
736 ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => {
737 // FIXME(eddyb) print this with `print_def_path`.
738 // We use verbose printing in 'NO_QUERIES' mode, to
739 // avoid needing to call `predicates_of`. This should
740 // only affect certain debug messages (e.g. messages printed
741 // from `rustc_middle::ty` during the computation of `tcx.predicates_of`),
742 // and should have no effect on any compiler output.
743 if self.should_print_verbose() || NO_QUERIES.with(|q| q.get()) {
744 p!(write("Opaque({:?}, {:?})", def_id, substs));
748 let parent = self.tcx().parent(def_id);
749 match self.tcx().def_kind(parent) {
750 DefKind::TyAlias | DefKind::AssocTy => {
751 if let ty::Alias(ty::Opaque, ty::AliasTy { def_id: d, .. }) =
752 *self.tcx().type_of(parent).kind()
755 // If the type alias directly starts with the `impl` of the
756 // opaque type we're printing, then skip the `::{opaque#1}`.
757 p!(print_def_path(parent, substs));
761 // Complex opaque type, e.g. `type Foo = (i32, impl Debug);`
762 p!(print_def_path(def_id, substs));
765 _ => return self.pretty_print_opaque_impl_type(def_id, substs),
768 ty::Str => p!("str"),
769 ty::Generator(did, substs, movability) => {
771 let generator_kind = self.tcx().generator_kind(did).unwrap();
772 let should_print_movability =
773 self.should_print_verbose() || generator_kind == hir::GeneratorKind::Gen;
775 if should_print_movability {
777 hir::Movability::Movable => {}
778 hir::Movability::Static => p!("static "),
782 if !self.should_print_verbose() {
783 p!(write("{}", generator_kind));
784 // FIXME(eddyb) should use `def_span`.
785 if let Some(did) = did.as_local() {
786 let span = self.tcx().def_span(did);
789 // This may end up in stderr diagnostics but it may also be emitted
790 // into MIR. Hence we use the remapped path if available
791 self.tcx().sess.source_map().span_to_embeddable_string(span)
794 p!(write("@"), print_def_path(did, substs));
797 p!(print_def_path(did, substs));
799 if !substs.as_generator().is_valid() {
802 self = self.comma_sep(substs.as_generator().upvar_tys())?;
806 if substs.as_generator().is_valid() {
807 p!(" ", print(substs.as_generator().witness()));
813 ty::GeneratorWitness(types) => {
814 p!(in_binder(&types));
816 ty::GeneratorWitnessMIR(did, substs) => {
818 if !self.tcx().sess.verbose() {
819 p!("generator witness");
820 // FIXME(eddyb) should use `def_span`.
821 if let Some(did) = did.as_local() {
822 let span = self.tcx().def_span(did);
825 // This may end up in stderr diagnostics but it may also be emitted
826 // into MIR. Hence we use the remapped path if available
827 self.tcx().sess.source_map().span_to_embeddable_string(span)
830 p!(write("@"), print_def_path(did, substs));
833 p!(print_def_path(did, substs));
838 ty::Closure(did, substs) => {
840 if !self.should_print_verbose() {
841 p!(write("closure"));
842 // FIXME(eddyb) should use `def_span`.
843 if let Some(did) = did.as_local() {
844 if self.tcx().sess.opts.unstable_opts.span_free_formats {
845 p!("@", print_def_path(did.to_def_id(), substs));
847 let span = self.tcx().def_span(did);
848 let preference = if FORCE_TRIMMED_PATH.with(|flag| flag.get()) {
849 FileNameDisplayPreference::Short
851 FileNameDisplayPreference::Remapped
855 // This may end up in stderr diagnostics but it may also be emitted
856 // into MIR. Hence we use the remapped path if available
857 self.tcx().sess.source_map().span_to_string(span, preference)
861 p!(write("@"), print_def_path(did, substs));
864 p!(print_def_path(did, substs));
865 if !substs.as_closure().is_valid() {
866 p!(" closure_substs=(unavailable)");
867 p!(write(" substs={:?}", substs));
869 p!(" closure_kind_ty=", print(substs.as_closure().kind_ty()));
871 " closure_sig_as_fn_ptr_ty=",
872 print(substs.as_closure().sig_as_fn_ptr_ty())
875 self = self.comma_sep(substs.as_closure().upvar_tys())?;
881 ty::Array(ty, sz) => p!("[", print(ty), "; ", print(sz), "]"),
882 ty::Slice(ty) => p!("[", print(ty), "]"),
888 fn pretty_print_opaque_impl_type(
891 substs: &'tcx ty::List<ty::GenericArg<'tcx>>,
892 ) -> Result<Self::Type, Self::Error> {
893 let tcx = self.tcx();
895 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
896 // by looking up the projections associated with the def_id.
897 let bounds = tcx.bound_explicit_item_bounds(def_id);
899 let mut traits = FxIndexMap::default();
900 let mut fn_traits = FxIndexMap::default();
901 let mut is_sized = false;
902 let mut lifetimes = SmallVec::<[ty::Region<'tcx>; 1]>::new();
904 for (predicate, _) in bounds.subst_iter_copied(tcx, substs) {
905 let bound_predicate = predicate.kind();
907 match bound_predicate.skip_binder() {
908 ty::PredicateKind::Clause(ty::Clause::Trait(pred)) => {
909 let trait_ref = bound_predicate.rebind(pred.trait_ref);
911 // Don't print + Sized, but rather + ?Sized if absent.
912 if Some(trait_ref.def_id()) == tcx.lang_items().sized_trait() {
917 self.insert_trait_and_projection(trait_ref, None, &mut traits, &mut fn_traits);
919 ty::PredicateKind::Clause(ty::Clause::Projection(pred)) => {
920 let proj_ref = bound_predicate.rebind(pred);
921 let trait_ref = proj_ref.required_poly_trait_ref(tcx);
923 // Projection type entry -- the def-id for naming, and the ty.
924 let proj_ty = (proj_ref.projection_def_id(), proj_ref.term());
926 self.insert_trait_and_projection(
933 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(outlives)) => {
934 lifetimes.push(outlives.1);
940 write!(self, "impl ")?;
942 let mut first = true;
943 // Insert parenthesis around (Fn(A, B) -> C) if the opaque ty has more than one other trait
944 let paren_needed = fn_traits.len() > 1 || traits.len() > 0 || !is_sized;
946 for (fn_once_trait_ref, entry) in fn_traits {
947 write!(self, "{}", if first { "" } else { " + " })?;
948 write!(self, "{}", if paren_needed { "(" } else { "" })?;
950 self = self.wrap_binder(&fn_once_trait_ref, |trait_ref, mut cx| {
951 define_scoped_cx!(cx);
952 // Get the (single) generic ty (the args) of this FnOnce trait ref.
953 let generics = tcx.generics_of(trait_ref.def_id);
954 let args = generics.own_substs_no_defaults(tcx, trait_ref.substs);
956 match (entry.return_ty, args[0].expect_ty()) {
957 // We can only print `impl Fn() -> ()` if we have a tuple of args and we recorded
959 (Some(return_ty), arg_tys) if matches!(arg_tys.kind(), ty::Tuple(_)) => {
960 let name = if entry.fn_trait_ref.is_some() {
962 } else if entry.fn_mut_trait_ref.is_some() {
968 p!(write("{}(", name));
970 for (idx, ty) in arg_tys.tuple_fields().iter().enumerate() {
978 if let Some(ty) = return_ty.skip_binder().ty() {
980 p!(" -> ", print(return_ty));
983 p!(write("{}", if paren_needed { ")" } else { "" }));
987 // If we got here, we can't print as a `impl Fn(A, B) -> C`. Just record the
988 // trait_refs we collected in the OpaqueFnEntry as normal trait refs.
990 if entry.has_fn_once {
991 traits.entry(fn_once_trait_ref).or_default().extend(
992 // Group the return ty with its def id, if we had one.
995 .map(|ty| (tcx.require_lang_item(LangItem::FnOnce, None), ty)),
998 if let Some(trait_ref) = entry.fn_mut_trait_ref {
999 traits.entry(trait_ref).or_default();
1001 if let Some(trait_ref) = entry.fn_trait_ref {
1002 traits.entry(trait_ref).or_default();
1011 // Print the rest of the trait types (that aren't Fn* family of traits)
1012 for (trait_ref, assoc_items) in traits {
1013 write!(self, "{}", if first { "" } else { " + " })?;
1015 self = self.wrap_binder(&trait_ref, |trait_ref, mut cx| {
1016 define_scoped_cx!(cx);
1017 p!(print(trait_ref.print_only_trait_name()));
1019 let generics = tcx.generics_of(trait_ref.def_id);
1020 let args = generics.own_substs_no_defaults(tcx, trait_ref.substs);
1022 if !args.is_empty() || !assoc_items.is_empty() {
1023 let mut first = true;
1035 for (assoc_item_def_id, term) in assoc_items {
1036 // Skip printing `<[generator@] as Generator<_>>::Return` from async blocks,
1037 // unless we can find out what generator return type it comes from.
1038 let term = if let Some(ty) = term.skip_binder().ty()
1039 && let ty::Alias(ty::Projection, proj) = ty.kind()
1040 && let Some(assoc) = tcx.opt_associated_item(proj.def_id)
1041 && assoc.trait_container(tcx) == tcx.lang_items().gen_trait()
1042 && assoc.name == rustc_span::sym::Return
1044 if let ty::Generator(_, substs, _) = substs.type_at(0).kind() {
1045 let return_ty = substs.as_generator().return_ty();
1046 if !return_ty.is_ty_var() {
1065 p!(write("{} = ", tcx.associated_item(assoc_item_def_id).name));
1067 match term.unpack() {
1068 TermKind::Ty(ty) => p!(print(ty)),
1069 TermKind::Const(c) => p!(print(c)),
1084 write!(self, "{}?Sized", if first { "" } else { " + " })?;
1086 write!(self, "Sized")?;
1089 if !FORCE_TRIMMED_PATH.with(|flag| flag.get()) {
1090 for re in lifetimes {
1091 write!(self, " + ")?;
1092 self = self.print_region(re)?;
1099 /// Insert the trait ref and optionally a projection type associated with it into either the
1100 /// traits map or fn_traits map, depending on if the trait is in the Fn* family of traits.
1101 fn insert_trait_and_projection(
1103 trait_ref: ty::PolyTraitRef<'tcx>,
1104 proj_ty: Option<(DefId, ty::Binder<'tcx, Term<'tcx>>)>,
1105 traits: &mut FxIndexMap<
1106 ty::PolyTraitRef<'tcx>,
1107 FxIndexMap<DefId, ty::Binder<'tcx, Term<'tcx>>>,
1109 fn_traits: &mut FxIndexMap<ty::PolyTraitRef<'tcx>, OpaqueFnEntry<'tcx>>,
1111 let trait_def_id = trait_ref.def_id();
1113 // If our trait_ref is FnOnce or any of its children, project it onto the parent FnOnce
1114 // super-trait ref and record it there.
1115 if let Some(fn_once_trait) = self.tcx().lang_items().fn_once_trait() {
1116 // If we have a FnOnce, then insert it into
1117 if trait_def_id == fn_once_trait {
1118 let entry = fn_traits.entry(trait_ref).or_default();
1119 // Optionally insert the return_ty as well.
1120 if let Some((_, ty)) = proj_ty {
1121 entry.return_ty = Some(ty);
1123 entry.has_fn_once = true;
1125 } else if Some(trait_def_id) == self.tcx().lang_items().fn_mut_trait() {
1126 let super_trait_ref = crate::traits::util::supertraits(self.tcx(), trait_ref)
1127 .find(|super_trait_ref| super_trait_ref.def_id() == fn_once_trait)
1130 fn_traits.entry(super_trait_ref).or_default().fn_mut_trait_ref = Some(trait_ref);
1132 } else if Some(trait_def_id) == self.tcx().lang_items().fn_trait() {
1133 let super_trait_ref = crate::traits::util::supertraits(self.tcx(), trait_ref)
1134 .find(|super_trait_ref| super_trait_ref.def_id() == fn_once_trait)
1137 fn_traits.entry(super_trait_ref).or_default().fn_trait_ref = Some(trait_ref);
1142 // Otherwise, just group our traits and projection types.
1143 traits.entry(trait_ref).or_default().extend(proj_ty);
1146 fn pretty_print_bound_var(
1148 debruijn: ty::DebruijnIndex,
1150 ) -> Result<(), Self::Error> {
1151 if debruijn == ty::INNERMOST {
1152 write!(self, "^{}", var.index())
1154 write!(self, "^{}_{}", debruijn.index(), var.index())
1158 fn ty_infer_name(&self, _: ty::TyVid) -> Option<Symbol> {
1162 fn const_infer_name(&self, _: ty::ConstVid<'tcx>) -> Option<Symbol> {
1166 fn pretty_print_dyn_existential(
1168 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1169 ) -> Result<Self::DynExistential, Self::Error> {
1170 // Generate the main trait ref, including associated types.
1171 let mut first = true;
1173 if let Some(principal) = predicates.principal() {
1174 self = self.wrap_binder(&principal, |principal, mut cx| {
1175 define_scoped_cx!(cx);
1176 p!(print_def_path(principal.def_id, &[]));
1178 let mut resugared = false;
1180 // Special-case `Fn(...) -> ...` and re-sugar it.
1181 let fn_trait_kind = cx.tcx().fn_trait_kind_from_def_id(principal.def_id);
1182 if !cx.should_print_verbose() && fn_trait_kind.is_some() {
1183 if let ty::Tuple(tys) = principal.substs.type_at(0).kind() {
1184 let mut projections = predicates.projection_bounds();
1185 if let (Some(proj), None) = (projections.next(), projections.next()) {
1189 proj.skip_binder().term.ty().expect("Return type was a const")
1196 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
1197 // in order to place the projections inside the `<...>`.
1199 // Use a type that can't appear in defaults of type parameters.
1200 let dummy_cx = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1201 let principal = principal.with_self_ty(cx.tcx(), dummy_cx);
1205 .generics_of(principal.def_id)
1206 .own_substs_no_defaults(cx.tcx(), principal.substs);
1208 let mut projections = predicates.projection_bounds();
1210 let mut args = args.iter().cloned();
1211 let arg0 = args.next();
1212 let projection0 = projections.next();
1213 if arg0.is_some() || projection0.is_some() {
1214 let args = arg0.into_iter().chain(args);
1215 let projections = projection0.into_iter().chain(projections);
1217 p!(generic_delimiters(|mut cx| {
1218 cx = cx.comma_sep(args)?;
1219 if arg0.is_some() && projection0.is_some() {
1222 cx.comma_sep(projections)
1232 define_scoped_cx!(self);
1235 // FIXME(eddyb) avoid printing twice (needed to ensure
1236 // that the auto traits are sorted *and* printed via cx).
1237 let mut auto_traits: Vec<_> = predicates.auto_traits().collect();
1239 // The auto traits come ordered by `DefPathHash`. While
1240 // `DefPathHash` is *stable* in the sense that it depends on
1241 // neither the host nor the phase of the moon, it depends
1242 // "pseudorandomly" on the compiler version and the target.
1244 // To avoid causing instabilities in compiletest
1245 // output, sort the auto-traits alphabetically.
1246 auto_traits.sort_by_cached_key(|did| with_no_trimmed_paths!(self.tcx().def_path_str(*did)));
1248 for def_id in auto_traits {
1254 p!(print_def_path(def_id, &[]));
1262 inputs: &[Ty<'tcx>],
1265 ) -> Result<Self, Self::Error> {
1266 define_scoped_cx!(self);
1268 p!("(", comma_sep(inputs.iter().copied()));
1270 if !inputs.is_empty() {
1276 if !output.is_unit() {
1277 p!(" -> ", print(output));
1283 fn pretty_print_const(
1285 ct: ty::Const<'tcx>,
1287 ) -> Result<Self::Const, Self::Error> {
1288 define_scoped_cx!(self);
1290 if self.should_print_verbose() {
1291 p!(write("Const({:?}: {:?})", ct.kind(), ct.ty()));
1295 macro_rules! print_underscore {
1298 self = self.typed_value(
1303 |this| this.print_type(ct.ty()),
1313 ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, substs }) => {
1314 match self.tcx().def_kind(def.did) {
1315 DefKind::Const | DefKind::AssocConst => {
1316 p!(print_value_path(def.did, substs))
1318 DefKind::AnonConst => {
1320 && let span = self.tcx().def_span(def.did)
1321 && let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span)
1323 p!(write("{}", snip))
1325 // Do not call `print_value_path` as if a parent of this anon const is an impl it will
1326 // attempt to print out the impl trait ref i.e. `<T as Trait>::{constant#0}`. This would
1327 // cause printing to enter an infinite recursion if the anon const is in the self type i.e.
1328 // `impl<T: Default> Default for [T; 32 - 1 - 1 - 1] {`
1329 // where we would try to print `<[T; /* print `constant#0` again */] as Default>::{constant#0}`
1330 p!(write("{}::{}", self.tcx().crate_name(def.did.krate), self.tcx().def_path(def.did).to_string_no_crate_verbose()))
1333 defkind => bug!("`{:?}` has unexpcted defkind {:?}", ct, defkind),
1336 ty::ConstKind::Infer(infer_ct) => {
1338 ty::InferConst::Var(ct_vid)
1339 if let Some(name) = self.const_infer_name(ct_vid) =>
1340 p!(write("{}", name)),
1341 _ => print_underscore!(),
1344 ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)),
1345 ty::ConstKind::Value(value) => {
1346 return self.pretty_print_const_valtree(value, ct.ty(), print_ty);
1349 ty::ConstKind::Bound(debruijn, bound_var) => {
1350 self.pretty_print_bound_var(debruijn, bound_var)?
1352 ty::ConstKind::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
1353 // FIXME(generic_const_exprs):
1354 // write out some legible representation of an abstract const?
1355 ty::ConstKind::Expr(_) => p!("[const expr]"),
1356 ty::ConstKind::Error(_) => p!("[const error]"),
1361 fn pretty_print_const_scalar(
1366 ) -> Result<Self::Const, Self::Error> {
1368 Scalar::Ptr(ptr, _size) => self.pretty_print_const_scalar_ptr(ptr, ty, print_ty),
1369 Scalar::Int(int) => self.pretty_print_const_scalar_int(int, ty, print_ty),
1373 fn pretty_print_const_scalar_ptr(
1378 ) -> Result<Self::Const, Self::Error> {
1379 define_scoped_cx!(self);
1381 let (alloc_id, offset) = ptr.into_parts();
1383 // Byte strings (&[u8; N])
1384 ty::Ref(_, inner, _) => {
1385 if let ty::Array(elem, len) = inner.kind() {
1386 if let ty::Uint(ty::UintTy::U8) = elem.kind() {
1387 if let ty::ConstKind::Value(ty::ValTree::Leaf(int)) = len.kind() {
1388 match self.tcx().try_get_global_alloc(alloc_id) {
1389 Some(GlobalAlloc::Memory(alloc)) => {
1390 let len = int.assert_bits(self.tcx().data_layout.pointer_size);
1392 AllocRange { start: offset, size: Size::from_bytes(len) };
1393 if let Ok(byte_str) =
1394 alloc.inner().get_bytes_strip_provenance(&self.tcx(), range)
1396 p!(pretty_print_byte_str(byte_str))
1398 p!("<too short allocation>")
1401 // FIXME: for statics, vtables, and functions, we could in principle print more detail.
1402 Some(GlobalAlloc::Static(def_id)) => {
1403 p!(write("<static({:?})>", def_id))
1405 Some(GlobalAlloc::Function(_)) => p!("<function>"),
1406 Some(GlobalAlloc::VTable(..)) => p!("<vtable>"),
1407 None => p!("<dangling pointer>"),
1415 // FIXME: We should probably have a helper method to share code with the "Byte strings"
1416 // printing above (which also has to handle pointers to all sorts of things).
1417 if let Some(GlobalAlloc::Function(instance)) =
1418 self.tcx().try_get_global_alloc(alloc_id)
1420 self = self.typed_value(
1421 |this| this.print_value_path(instance.def_id(), instance.substs),
1422 |this| this.print_type(ty),
1430 // Any pointer values not covered by a branch above
1431 self = self.pretty_print_const_pointer(ptr, ty, print_ty)?;
1435 fn pretty_print_const_scalar_int(
1440 ) -> Result<Self::Const, Self::Error> {
1441 define_scoped_cx!(self);
1445 ty::Bool if int == ScalarInt::FALSE => p!("false"),
1446 ty::Bool if int == ScalarInt::TRUE => p!("true"),
1448 ty::Float(ty::FloatTy::F32) => {
1449 p!(write("{}f32", Single::try_from(int).unwrap()))
1451 ty::Float(ty::FloatTy::F64) => {
1452 p!(write("{}f64", Double::try_from(int).unwrap()))
1455 ty::Uint(_) | ty::Int(_) => {
1457 ConstInt::new(int, matches!(ty.kind(), ty::Int(_)), ty.is_ptr_sized_integral());
1458 if print_ty { p!(write("{:#?}", int)) } else { p!(write("{:?}", int)) }
1461 ty::Char if char::try_from(int).is_ok() => {
1462 p!(write("{:?}", char::try_from(int).unwrap()))
1465 ty::Ref(..) | ty::RawPtr(_) | ty::FnPtr(_) => {
1466 let data = int.assert_bits(self.tcx().data_layout.pointer_size);
1467 self = self.typed_value(
1469 write!(this, "0x{:x}", data)?;
1472 |this| this.print_type(ty),
1476 // Nontrivial types with scalar bit representation
1478 let print = |mut this: Self| {
1479 if int.size() == Size::ZERO {
1480 write!(this, "transmute(())")?;
1482 write!(this, "transmute(0x{:x})", int)?;
1486 self = if print_ty {
1487 self.typed_value(print, |this| this.print_type(ty), ": ")?
1496 /// This is overridden for MIR printing because we only want to hide alloc ids from users, not
1497 /// from MIR where it is actually useful.
1498 fn pretty_print_const_pointer<Prov: Provenance>(
1503 ) -> Result<Self::Const, Self::Error> {
1507 this.write_str("&_")?;
1510 |this| this.print_type(ty),
1514 self.write_str("&_")?;
1519 fn pretty_print_byte_str(mut self, byte_str: &'tcx [u8]) -> Result<Self::Const, Self::Error> {
1520 write!(self, "b\"{}\"", byte_str.escape_ascii())?;
1524 fn pretty_print_const_valtree(
1526 valtree: ty::ValTree<'tcx>,
1529 ) -> Result<Self::Const, Self::Error> {
1530 define_scoped_cx!(self);
1532 if self.should_print_verbose() {
1533 p!(write("ValTree({:?}: ", valtree), print(ty), ")");
1537 let u8_type = self.tcx().types.u8;
1538 match (valtree, ty.kind()) {
1539 (ty::ValTree::Branch(_), ty::Ref(_, inner_ty, _)) => match inner_ty.kind() {
1540 ty::Slice(t) if *t == u8_type => {
1541 let bytes = valtree.try_to_raw_bytes(self.tcx(), ty).unwrap_or_else(|| {
1543 "expected to convert valtree {:?} to raw bytes for type {:?}",
1548 return self.pretty_print_byte_str(bytes);
1551 let bytes = valtree.try_to_raw_bytes(self.tcx(), ty).unwrap_or_else(|| {
1552 bug!("expected to convert valtree to raw bytes for type {:?}", ty)
1554 p!(write("{:?}", String::from_utf8_lossy(bytes)));
1559 p!(pretty_print_const_valtree(valtree, *inner_ty, print_ty));
1563 (ty::ValTree::Branch(_), ty::Array(t, _)) if *t == u8_type => {
1564 let bytes = valtree.try_to_raw_bytes(self.tcx(), ty).unwrap_or_else(|| {
1565 bug!("expected to convert valtree to raw bytes for type {:?}", t)
1568 p!(pretty_print_byte_str(bytes));
1571 // Aggregates, printed as array/tuple/struct/variant construction syntax.
1572 (ty::ValTree::Branch(_), ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) => {
1573 let contents = self.tcx().destructure_const(self.tcx().mk_const(valtree, ty));
1574 let fields = contents.fields.iter().copied();
1577 p!("[", comma_sep(fields), "]");
1580 p!("(", comma_sep(fields));
1581 if contents.fields.len() == 1 {
1586 ty::Adt(def, _) if def.variants().is_empty() => {
1587 self = self.typed_value(
1589 write!(this, "unreachable()")?;
1592 |this| this.print_type(ty),
1596 ty::Adt(def, substs) => {
1598 contents.variant.expect("destructed const of adt without variant idx");
1599 let variant_def = &def.variant(variant_idx);
1600 p!(print_value_path(variant_def.def_id, substs));
1601 match variant_def.ctor_kind() {
1602 Some(CtorKind::Const) => {}
1603 Some(CtorKind::Fn) => {
1604 p!("(", comma_sep(fields), ")");
1608 let mut first = true;
1609 for (field_def, field) in iter::zip(&variant_def.fields, fields) {
1613 p!(write("{}: ", field_def.name), print(field));
1620 _ => unreachable!(),
1624 (ty::ValTree::Leaf(leaf), ty::Ref(_, inner_ty, _)) => {
1626 return self.pretty_print_const_scalar_int(leaf, *inner_ty, print_ty);
1628 (ty::ValTree::Leaf(leaf), _) => {
1629 return self.pretty_print_const_scalar_int(leaf, ty, print_ty);
1631 // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
1632 // their fields instead of just dumping the memory.
1637 if valtree == ty::ValTree::zst() {
1640 p!(write("{:?}", valtree));
1643 p!(": ", print(ty));
1648 fn pretty_closure_as_impl(
1650 closure: ty::ClosureSubsts<'tcx>,
1651 ) -> Result<Self::Const, Self::Error> {
1652 let sig = closure.sig();
1653 let kind = closure.kind_ty().to_opt_closure_kind().unwrap_or(ty::ClosureKind::Fn);
1655 write!(self, "impl ")?;
1656 self.wrap_binder(&sig, |sig, mut cx| {
1657 define_scoped_cx!(cx);
1659 p!(print(kind), "(");
1660 for (i, arg) in sig.inputs()[0].tuple_fields().iter().enumerate() {
1668 if !sig.output().is_unit() {
1669 p!(" -> ", print(sig.output()));
1676 fn should_print_verbose(&self) -> bool {
1677 self.tcx().sess.verbose()
1681 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
1682 pub struct FmtPrinter<'a, 'tcx>(Box<FmtPrinterData<'a, 'tcx>>);
1684 pub struct FmtPrinterData<'a, 'tcx> {
1690 pub print_alloc_ids: bool,
1692 // set of all named (non-anonymous) region names
1693 used_region_names: FxHashSet<Symbol>,
1695 region_index: usize,
1696 binder_depth: usize,
1697 printed_type_count: usize,
1698 type_length_limit: Limit,
1701 pub region_highlight_mode: RegionHighlightMode<'tcx>,
1703 pub ty_infer_name_resolver: Option<Box<dyn Fn(ty::TyVid) -> Option<Symbol> + 'a>>,
1704 pub const_infer_name_resolver: Option<Box<dyn Fn(ty::ConstVid<'tcx>) -> Option<Symbol> + 'a>>,
1707 impl<'a, 'tcx> Deref for FmtPrinter<'a, 'tcx> {
1708 type Target = FmtPrinterData<'a, 'tcx>;
1709 fn deref(&self) -> &Self::Target {
1714 impl DerefMut for FmtPrinter<'_, '_> {
1715 fn deref_mut(&mut self) -> &mut Self::Target {
1720 impl<'a, 'tcx> FmtPrinter<'a, 'tcx> {
1721 pub fn new(tcx: TyCtxt<'tcx>, ns: Namespace) -> Self {
1722 Self::new_with_limit(tcx, ns, tcx.type_length_limit())
1725 pub fn new_with_limit(tcx: TyCtxt<'tcx>, ns: Namespace, type_length_limit: Limit) -> Self {
1726 FmtPrinter(Box::new(FmtPrinterData {
1728 // Estimated reasonable capacity to allocate upfront based on a few
1730 fmt: String::with_capacity(64),
1732 in_value: ns == Namespace::ValueNS,
1733 print_alloc_ids: false,
1734 used_region_names: Default::default(),
1737 printed_type_count: 0,
1740 region_highlight_mode: RegionHighlightMode::new(tcx),
1741 ty_infer_name_resolver: None,
1742 const_infer_name_resolver: None,
1746 pub fn into_buffer(self) -> String {
1751 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1752 // (but also some things just print a `DefId` generally so maybe we need this?)
1753 fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
1754 match tcx.def_key(def_id).disambiguated_data.data {
1755 DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::ImplTrait => {
1759 DefPathData::ValueNs(..)
1760 | DefPathData::AnonConst
1761 | DefPathData::ClosureExpr
1762 | DefPathData::Ctor => Namespace::ValueNS,
1764 DefPathData::MacroNs(..) => Namespace::MacroNS,
1766 _ => Namespace::TypeNS,
1770 impl<'t> TyCtxt<'t> {
1771 /// Returns a string identifying this `DefId`. This string is
1772 /// suitable for user output.
1773 pub fn def_path_str(self, def_id: DefId) -> String {
1774 self.def_path_str_with_substs(def_id, &[])
1777 pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1778 let ns = guess_def_namespace(self, def_id);
1779 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1780 FmtPrinter::new(self, ns).print_def_path(def_id, substs).unwrap().into_buffer()
1783 pub fn value_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1784 let ns = guess_def_namespace(self, def_id);
1785 debug!("value_path_str: def_id={:?}, ns={:?}", def_id, ns);
1786 FmtPrinter::new(self, ns).print_value_path(def_id, substs).unwrap().into_buffer()
1790 impl fmt::Write for FmtPrinter<'_, '_> {
1791 fn write_str(&mut self, s: &str) -> fmt::Result {
1792 self.fmt.push_str(s);
1797 impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> {
1798 type Error = fmt::Error;
1803 type DynExistential = Self;
1806 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
1813 substs: &'tcx [GenericArg<'tcx>],
1814 ) -> Result<Self::Path, Self::Error> {
1815 define_scoped_cx!(self);
1817 if substs.is_empty() {
1818 match self.try_print_trimmed_def_path(def_id)? {
1819 (cx, true) => return Ok(cx),
1820 (cx, false) => self = cx,
1823 match self.try_print_visible_def_path(def_id)? {
1824 (cx, true) => return Ok(cx),
1825 (cx, false) => self = cx,
1829 let key = self.tcx.def_key(def_id);
1830 if let DefPathData::Impl = key.disambiguated_data.data {
1831 // Always use types for non-local impls, where types are always
1832 // available, and filename/line-number is mostly uninteresting.
1833 let use_types = !def_id.is_local() || {
1834 // Otherwise, use filename/line-number if forced.
1835 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1840 // If no type info is available, fall back to
1841 // pretty printing some span information. This should
1842 // only occur very early in the compiler pipeline.
1843 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1844 let span = self.tcx.def_span(def_id);
1846 self = self.print_def_path(parent_def_id, &[])?;
1848 // HACK(eddyb) copy of `path_append` to avoid
1849 // constructing a `DisambiguatedDefPathData`.
1850 if !self.empty_path {
1851 write!(self, "::")?;
1856 // This may end up in stderr diagnostics but it may also be emitted
1857 // into MIR. Hence we use the remapped path if available
1858 self.tcx.sess.source_map().span_to_embeddable_string(span)
1860 self.empty_path = false;
1866 self.default_print_def_path(def_id, substs)
1869 fn print_region(self, region: ty::Region<'tcx>) -> Result<Self::Region, Self::Error> {
1870 self.pretty_print_region(region)
1873 fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1874 if self.type_length_limit.value_within_limit(self.printed_type_count) {
1875 self.printed_type_count += 1;
1876 self.pretty_print_type(ty)
1878 self.truncated = true;
1879 write!(self, "...")?;
1884 fn print_dyn_existential(
1886 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1887 ) -> Result<Self::DynExistential, Self::Error> {
1888 self.pretty_print_dyn_existential(predicates)
1891 fn print_const(self, ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1892 self.pretty_print_const(ct, false)
1895 fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1896 self.empty_path = true;
1897 if cnum == LOCAL_CRATE {
1898 if self.tcx.sess.rust_2018() {
1899 // We add the `crate::` keyword on Rust 2018, only when desired.
1900 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1901 write!(self, "{}", kw::Crate)?;
1902 self.empty_path = false;
1906 write!(self, "{}", self.tcx.crate_name(cnum))?;
1907 self.empty_path = false;
1915 trait_ref: Option<ty::TraitRef<'tcx>>,
1916 ) -> Result<Self::Path, Self::Error> {
1917 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1918 self.empty_path = false;
1922 fn path_append_impl(
1924 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1925 _disambiguated_data: &DisambiguatedDefPathData,
1927 trait_ref: Option<ty::TraitRef<'tcx>>,
1928 ) -> Result<Self::Path, Self::Error> {
1929 self = self.pretty_path_append_impl(
1931 cx = print_prefix(cx)?;
1941 self.empty_path = false;
1947 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1948 disambiguated_data: &DisambiguatedDefPathData,
1949 ) -> Result<Self::Path, Self::Error> {
1950 self = print_prefix(self)?;
1952 // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
1953 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
1957 let name = disambiguated_data.data.name();
1958 if !self.empty_path {
1959 write!(self, "::")?;
1962 if let DefPathDataName::Named(name) = name {
1963 if Ident::with_dummy_span(name).is_raw_guess() {
1964 write!(self, "r#")?;
1968 let verbose = self.should_print_verbose();
1969 disambiguated_data.fmt_maybe_verbose(&mut self, verbose)?;
1971 self.empty_path = false;
1976 fn path_generic_args(
1978 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1979 args: &[GenericArg<'tcx>],
1980 ) -> Result<Self::Path, Self::Error> {
1981 self = print_prefix(self)?;
1983 if args.first().is_some() {
1985 write!(self, "::")?;
1987 self.generic_delimiters(|cx| cx.comma_sep(args.iter().cloned()))
1994 impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> {
1995 fn ty_infer_name(&self, id: ty::TyVid) -> Option<Symbol> {
1996 self.0.ty_infer_name_resolver.as_ref().and_then(|func| func(id))
1999 fn reset_type_limit(&mut self) {
2000 self.printed_type_count = 0;
2003 fn const_infer_name(&self, id: ty::ConstVid<'tcx>) -> Option<Symbol> {
2004 self.0.const_infer_name_resolver.as_ref().and_then(|func| func(id))
2007 fn print_value_path(
2010 substs: &'tcx [GenericArg<'tcx>],
2011 ) -> Result<Self::Path, Self::Error> {
2012 let was_in_value = std::mem::replace(&mut self.in_value, true);
2013 self = self.print_def_path(def_id, substs)?;
2014 self.in_value = was_in_value;
2019 fn in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, Self::Error>
2021 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
2023 self.pretty_in_binder(value)
2026 fn wrap_binder<T, C: FnOnce(&T, Self) -> Result<Self, Self::Error>>(
2028 value: &ty::Binder<'tcx, T>,
2030 ) -> Result<Self, Self::Error>
2032 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
2034 self.pretty_wrap_binder(value, f)
2039 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
2040 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
2042 ) -> Result<Self::Const, Self::Error> {
2043 self.write_str("{")?;
2045 self.write_str(conversion)?;
2046 let was_in_value = std::mem::replace(&mut self.in_value, false);
2048 self.in_value = was_in_value;
2049 self.write_str("}")?;
2053 fn generic_delimiters(
2055 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
2056 ) -> Result<Self, Self::Error> {
2059 let was_in_value = std::mem::replace(&mut self.in_value, false);
2060 let mut inner = f(self)?;
2061 inner.in_value = was_in_value;
2063 write!(inner, ">")?;
2067 fn should_print_region(&self, region: ty::Region<'tcx>) -> bool {
2068 let highlight = self.region_highlight_mode;
2069 if highlight.region_highlighted(region).is_some() {
2073 if self.should_print_verbose() {
2077 if FORCE_TRIMMED_PATH.with(|flag| flag.get()) {
2081 let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
2084 ty::ReEarlyBound(ref data) => data.has_name(),
2086 ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
2087 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
2088 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
2093 if let Some((region, _)) = highlight.highlight_bound_region {
2102 ty::ReVar(_) if identify_regions => true,
2104 ty::ReVar(_) | ty::ReErased => false,
2106 ty::ReStatic => true,
2110 fn pretty_print_const_pointer<Prov: Provenance>(
2115 ) -> Result<Self::Const, Self::Error> {
2116 let print = |mut this: Self| {
2117 define_scoped_cx!(this);
2118 if this.print_alloc_ids {
2119 p!(write("{:?}", p));
2126 self.typed_value(print, |this| this.print_type(ty), ": ")
2133 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
2134 impl<'tcx> FmtPrinter<'_, 'tcx> {
2135 pub fn pretty_print_region(mut self, region: ty::Region<'tcx>) -> Result<Self, fmt::Error> {
2136 define_scoped_cx!(self);
2138 // Watch out for region highlights.
2139 let highlight = self.region_highlight_mode;
2140 if let Some(n) = highlight.region_highlighted(region) {
2141 p!(write("'{}", n));
2145 if self.should_print_verbose() {
2146 p!(write("{:?}", region));
2150 let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
2152 // These printouts are concise. They do not contain all the information
2153 // the user might want to diagnose an error, but there is basically no way
2154 // to fit that into a short string. Hence the recommendation to use
2155 // `explain_region()` or `note_and_explain_region()`.
2157 ty::ReEarlyBound(ref data) => {
2158 if data.name != kw::Empty {
2159 p!(write("{}", data.name));
2163 ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
2164 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
2165 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
2166 if let ty::BrNamed(_, name) = br && br.is_named() {
2167 p!(write("{}", name));
2171 if let Some((region, counter)) = highlight.highlight_bound_region {
2173 p!(write("'{}", counter));
2178 ty::ReVar(region_vid) if identify_regions => {
2179 p!(write("{:?}", region_vid));
2196 /// Folds through bound vars and placeholders, naming them
2197 struct RegionFolder<'a, 'tcx> {
2199 current_index: ty::DebruijnIndex,
2200 region_map: BTreeMap<ty::BoundRegion, ty::Region<'tcx>>,
2203 Option<ty::DebruijnIndex>, // Debruijn index of the folded late-bound region
2204 ty::DebruijnIndex, // Index corresponding to binder level
2206 ) -> ty::Region<'tcx>
2211 impl<'a, 'tcx> ty::TypeFolder<'tcx> for RegionFolder<'a, 'tcx> {
2212 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
2216 fn fold_binder<T: TypeFoldable<'tcx>>(
2218 t: ty::Binder<'tcx, T>,
2219 ) -> ty::Binder<'tcx, T> {
2220 self.current_index.shift_in(1);
2221 let t = t.super_fold_with(self);
2222 self.current_index.shift_out(1);
2226 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
2228 _ if t.has_vars_bound_at_or_above(self.current_index) || t.has_placeholders() => {
2229 return t.super_fold_with(self);
2236 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
2237 let name = &mut self.name;
2238 let region = match *r {
2239 ty::ReLateBound(db, br) if db >= self.current_index => {
2240 *self.region_map.entry(br).or_insert_with(|| name(Some(db), self.current_index, br))
2242 ty::RePlaceholder(ty::PlaceholderRegion { name: kind, .. }) => {
2243 // If this is an anonymous placeholder, don't rename. Otherwise, in some
2244 // async fns, we get a `for<'r> Send` bound
2246 ty::BrAnon(..) | ty::BrEnv => r,
2248 // Index doesn't matter, since this is just for naming and these never get bound
2249 let br = ty::BoundRegion { var: ty::BoundVar::from_u32(0), kind };
2253 .or_insert_with(|| name(None, self.current_index, br))
2259 if let ty::ReLateBound(debruijn1, br) = *region {
2260 assert_eq!(debruijn1, ty::INNERMOST);
2261 self.tcx.mk_region(ty::ReLateBound(self.current_index, br))
2268 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
2269 // `region_index` and `used_region_names`.
2270 impl<'tcx> FmtPrinter<'_, 'tcx> {
2271 pub fn name_all_regions<T>(
2273 value: &ty::Binder<'tcx, T>,
2274 ) -> Result<(Self, T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>), fmt::Error>
2276 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2278 fn name_by_region_index(
2280 available_names: &mut Vec<Symbol>,
2281 num_available: usize,
2283 if let Some(name) = available_names.pop() {
2286 Symbol::intern(&format!("'z{}", index - num_available))
2290 debug!("name_all_regions");
2292 // Replace any anonymous late-bound regions with named
2293 // variants, using new unique identifiers, so that we can
2294 // clearly differentiate between named and unnamed regions in
2295 // the output. We'll probably want to tweak this over time to
2296 // decide just how much information to give.
2297 if self.binder_depth == 0 {
2298 self.prepare_region_info(value);
2301 debug!("self.used_region_names: {:?}", &self.used_region_names);
2303 let mut empty = true;
2304 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
2311 let _ = write!(cx, "{}", w);
2313 let do_continue = |cx: &mut Self, cont: Symbol| {
2314 let _ = write!(cx, "{}", cont);
2317 define_scoped_cx!(self);
2319 let possible_names = ('a'..='z').rev().map(|s| Symbol::intern(&format!("'{s}")));
2321 let mut available_names = possible_names
2322 .filter(|name| !self.used_region_names.contains(&name))
2323 .collect::<Vec<_>>();
2324 debug!(?available_names);
2325 let num_available = available_names.len();
2327 let mut region_index = self.region_index;
2328 let mut next_name = |this: &Self| {
2332 name = name_by_region_index(region_index, &mut available_names, num_available);
2335 if !this.used_region_names.contains(&name) {
2343 // If we want to print verbosely, then print *all* binders, even if they
2344 // aren't named. Eventually, we might just want this as the default, but
2345 // this is not *quite* right and changes the ordering of some output
2347 let (new_value, map) = if self.should_print_verbose() {
2348 for var in value.bound_vars().iter() {
2349 start_or_continue(&mut self, "for<", ", ");
2350 write!(self, "{:?}", var)?;
2352 start_or_continue(&mut self, "", "> ");
2353 (value.clone().skip_binder(), BTreeMap::default())
2357 let trim_path = FORCE_TRIMMED_PATH.with(|flag| flag.get());
2358 // Closure used in `RegionFolder` to create names for anonymous late-bound
2359 // regions. We use two `DebruijnIndex`es (one for the currently folded
2360 // late-bound region and the other for the binder level) to determine
2361 // whether a name has already been created for the currently folded region,
2362 // see issue #102392.
2363 let mut name = |lifetime_idx: Option<ty::DebruijnIndex>,
2364 binder_level_idx: ty::DebruijnIndex,
2365 br: ty::BoundRegion| {
2366 let (name, kind) = match br.kind {
2367 ty::BrAnon(..) | ty::BrEnv => {
2368 let name = next_name(&self);
2370 if let Some(lt_idx) = lifetime_idx {
2371 if lt_idx > binder_level_idx {
2372 let kind = ty::BrNamed(CRATE_DEF_ID.to_def_id(), name);
2373 return tcx.mk_region(ty::ReLateBound(
2375 ty::BoundRegion { var: br.var, kind },
2380 (name, ty::BrNamed(CRATE_DEF_ID.to_def_id(), name))
2382 ty::BrNamed(def_id, kw::UnderscoreLifetime | kw::Empty) => {
2383 let name = next_name(&self);
2385 if let Some(lt_idx) = lifetime_idx {
2386 if lt_idx > binder_level_idx {
2387 let kind = ty::BrNamed(def_id, name);
2388 return tcx.mk_region(ty::ReLateBound(
2390 ty::BoundRegion { var: br.var, kind },
2395 (name, ty::BrNamed(def_id, name))
2397 ty::BrNamed(_, name) => {
2398 if let Some(lt_idx) = lifetime_idx {
2399 if lt_idx > binder_level_idx {
2401 return tcx.mk_region(ty::ReLateBound(
2403 ty::BoundRegion { var: br.var, kind },
2413 start_or_continue(&mut self, "for<", ", ");
2414 do_continue(&mut self, name);
2416 tcx.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BoundRegion { var: br.var, kind }))
2418 let mut folder = RegionFolder {
2420 current_index: ty::INNERMOST,
2422 region_map: BTreeMap::new(),
2424 let new_value = value.clone().skip_binder().fold_with(&mut folder);
2425 let region_map = folder.region_map;
2427 start_or_continue(&mut self, "", "> ");
2429 (new_value, region_map)
2432 self.binder_depth += 1;
2433 self.region_index = region_index;
2434 Ok((self, new_value, map))
2437 pub fn pretty_in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, fmt::Error>
2439 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2441 let old_region_index = self.region_index;
2442 let (new, new_value, _) = self.name_all_regions(value)?;
2443 let mut inner = new_value.print(new)?;
2444 inner.region_index = old_region_index;
2445 inner.binder_depth -= 1;
2449 pub fn pretty_wrap_binder<T, C: FnOnce(&T, Self) -> Result<Self, fmt::Error>>(
2451 value: &ty::Binder<'tcx, T>,
2453 ) -> Result<Self, fmt::Error>
2455 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2457 let old_region_index = self.region_index;
2458 let (new, new_value, _) = self.name_all_regions(value)?;
2459 let mut inner = f(&new_value, new)?;
2460 inner.region_index = old_region_index;
2461 inner.binder_depth -= 1;
2465 fn prepare_region_info<T>(&mut self, value: &ty::Binder<'tcx, T>)
2467 T: TypeVisitable<'tcx>,
2469 struct RegionNameCollector<'tcx> {
2470 used_region_names: FxHashSet<Symbol>,
2471 type_collector: SsoHashSet<Ty<'tcx>>,
2474 impl<'tcx> RegionNameCollector<'tcx> {
2476 RegionNameCollector {
2477 used_region_names: Default::default(),
2478 type_collector: SsoHashSet::new(),
2483 impl<'tcx> ty::visit::TypeVisitor<'tcx> for RegionNameCollector<'tcx> {
2486 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
2487 trace!("address: {:p}", r.0.0);
2489 // Collect all named lifetimes. These allow us to prevent duplication
2490 // of already existing lifetime names when introducing names for
2491 // anonymous late-bound regions.
2492 if let Some(name) = r.get_name() {
2493 self.used_region_names.insert(name);
2496 r.super_visit_with(self)
2499 // We collect types in order to prevent really large types from compiling for
2500 // a really long time. See issue #83150 for why this is necessary.
2501 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
2502 let not_previously_inserted = self.type_collector.insert(ty);
2503 if not_previously_inserted {
2504 ty.super_visit_with(self)
2506 ControlFlow::Continue(())
2511 let mut collector = RegionNameCollector::new();
2512 value.visit_with(&mut collector);
2513 self.used_region_names = collector.used_region_names;
2514 self.region_index = 0;
2518 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<'tcx, T>
2520 T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
2523 type Error = P::Error;
2525 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
2530 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
2532 T: Print<'tcx, P, Output = P, Error = P::Error>,
2533 U: Print<'tcx, P, Output = P, Error = P::Error>,
2536 type Error = P::Error;
2537 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
2538 define_scoped_cx!(cx);
2539 p!(print(self.0), ": ", print(self.1));
2544 macro_rules! forward_display_to_print {
2546 // Some of the $ty arguments may not actually use 'tcx
2547 $(#[allow(unused_lifetimes)] impl<'tcx> fmt::Display for $ty {
2548 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2549 ty::tls::with(|tcx| {
2550 let cx = tcx.lift(*self)
2551 .expect("could not lift for printing")
2552 .print(FmtPrinter::new(tcx, Namespace::TypeNS))?;
2553 f.write_str(&cx.into_buffer())?;
2561 macro_rules! define_print_and_forward_display {
2562 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
2563 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
2565 type Error = fmt::Error;
2566 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
2567 #[allow(unused_mut)]
2569 define_scoped_cx!($cx);
2571 #[allow(unreachable_code)]
2576 forward_display_to_print!($($ty),+);
2580 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2581 /// the trait path. That is, it will print `Trait<U>` instead of
2582 /// `<T as Trait<U>>`.
2583 #[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
2584 pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
2586 impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
2587 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2588 fmt::Display::fmt(self, f)
2592 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2593 /// the trait name. That is, it will print `Trait` instead of
2594 /// `<T as Trait<U>>`.
2595 #[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
2596 pub struct TraitRefPrintOnlyTraitName<'tcx>(ty::TraitRef<'tcx>);
2598 impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitName<'tcx> {
2599 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2600 fmt::Display::fmt(self, f)
2604 impl<'tcx> ty::TraitRef<'tcx> {
2605 pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
2606 TraitRefPrintOnlyTraitPath(self)
2609 pub fn print_only_trait_name(self) -> TraitRefPrintOnlyTraitName<'tcx> {
2610 TraitRefPrintOnlyTraitName(self)
2614 impl<'tcx> ty::Binder<'tcx, ty::TraitRef<'tcx>> {
2615 pub fn print_only_trait_path(self) -> ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>> {
2616 self.map_bound(|tr| tr.print_only_trait_path())
2620 #[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
2621 pub struct TraitPredPrintModifiersAndPath<'tcx>(ty::TraitPredicate<'tcx>);
2623 impl<'tcx> fmt::Debug for TraitPredPrintModifiersAndPath<'tcx> {
2624 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2625 fmt::Display::fmt(self, f)
2629 impl<'tcx> ty::TraitPredicate<'tcx> {
2630 pub fn print_modifiers_and_trait_path(self) -> TraitPredPrintModifiersAndPath<'tcx> {
2631 TraitPredPrintModifiersAndPath(self)
2635 impl<'tcx> ty::PolyTraitPredicate<'tcx> {
2636 pub fn print_modifiers_and_trait_path(
2638 ) -> ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>> {
2639 self.map_bound(TraitPredPrintModifiersAndPath)
2643 #[derive(Debug, Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
2644 pub struct PrintClosureAsImpl<'tcx> {
2645 pub closure: ty::ClosureSubsts<'tcx>,
2648 forward_display_to_print! {
2651 &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2654 // HACK(eddyb) these are exhaustive instead of generic,
2655 // because `for<'tcx>` isn't possible yet.
2656 ty::PolyExistentialPredicate<'tcx>,
2657 ty::Binder<'tcx, ty::TraitRef<'tcx>>,
2658 ty::Binder<'tcx, ty::ExistentialTraitRef<'tcx>>,
2659 ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>>,
2660 ty::Binder<'tcx, TraitRefPrintOnlyTraitName<'tcx>>,
2661 ty::Binder<'tcx, ty::FnSig<'tcx>>,
2662 ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2663 ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>>,
2664 ty::Binder<'tcx, ty::SubtypePredicate<'tcx>>,
2665 ty::Binder<'tcx, ty::ProjectionPredicate<'tcx>>,
2666 ty::Binder<'tcx, ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
2667 ty::Binder<'tcx, ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
2669 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
2670 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
2673 define_print_and_forward_display! {
2676 &'tcx ty::List<Ty<'tcx>> {
2677 p!("{{", comma_sep(self.iter()), "}}")
2680 ty::TypeAndMut<'tcx> {
2681 p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
2684 ty::ExistentialTraitRef<'tcx> {
2685 // Use a type that can't appear in defaults of type parameters.
2686 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
2687 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
2688 p!(print(trait_ref.print_only_trait_path()))
2691 ty::ExistentialProjection<'tcx> {
2692 let name = cx.tcx().associated_item(self.def_id).name;
2693 p!(write("{} = ", name), print(self.term))
2696 ty::ExistentialPredicate<'tcx> {
2698 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
2699 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
2700 ty::ExistentialPredicate::AutoTrait(def_id) => {
2701 p!(print_def_path(def_id, &[]));
2707 p!(write("{}", self.unsafety.prefix_str()));
2709 if self.abi != Abi::Rust {
2710 p!(write("extern {} ", self.abi));
2713 p!("fn", pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
2716 ty::TraitRef<'tcx> {
2717 p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
2720 TraitRefPrintOnlyTraitPath<'tcx> {
2721 p!(print_def_path(self.0.def_id, self.0.substs));
2724 TraitRefPrintOnlyTraitName<'tcx> {
2725 p!(print_def_path(self.0.def_id, &[]));
2728 TraitPredPrintModifiersAndPath<'tcx> {
2729 if let ty::BoundConstness::ConstIfConst = self.0.constness {
2733 if let ty::ImplPolarity::Negative = self.0.polarity {
2737 p!(print(self.0.trait_ref.print_only_trait_path()));
2740 PrintClosureAsImpl<'tcx> {
2741 p!(pretty_closure_as_impl(self.closure))
2745 p!(write("{}", self.name))
2749 p!(write("{}", self.name))
2752 ty::SubtypePredicate<'tcx> {
2753 p!(print(self.a), " <: ");
2754 cx.reset_type_limit();
2758 ty::CoercePredicate<'tcx> {
2759 p!(print(self.a), " -> ");
2760 cx.reset_type_limit();
2764 ty::TraitPredicate<'tcx> {
2765 p!(print(self.trait_ref.self_ty()), ": ");
2766 if let ty::BoundConstness::ConstIfConst = self.constness && cx.tcx().features().const_trait_impl {
2769 p!(print(self.trait_ref.print_only_trait_path()))
2772 ty::ProjectionPredicate<'tcx> {
2773 p!(print(self.projection_ty), " == ");
2774 cx.reset_type_limit();
2775 p!(print(self.term))
2779 match self.unpack() {
2780 ty::TermKind::Ty(ty) => p!(print(ty)),
2781 ty::TermKind::Const(c) => p!(print(c)),
2786 p!(print_def_path(self.def_id, self.substs));
2791 ty::ClosureKind::Fn => p!("Fn"),
2792 ty::ClosureKind::FnMut => p!("FnMut"),
2793 ty::ClosureKind::FnOnce => p!("FnOnce"),
2797 ty::Predicate<'tcx> {
2798 let binder = self.kind();
2802 ty::PredicateKind<'tcx> {
2804 ty::PredicateKind::Clause(ty::Clause::Trait(ref data)) => {
2807 ty::PredicateKind::Subtype(predicate) => p!(print(predicate)),
2808 ty::PredicateKind::Coerce(predicate) => p!(print(predicate)),
2809 ty::PredicateKind::Clause(ty::Clause::RegionOutlives(predicate)) => p!(print(predicate)),
2810 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(predicate)) => p!(print(predicate)),
2811 ty::PredicateKind::Clause(ty::Clause::Projection(predicate)) => p!(print(predicate)),
2812 ty::PredicateKind::WellFormed(arg) => p!(print(arg), " well-formed"),
2813 ty::PredicateKind::ObjectSafe(trait_def_id) => {
2814 p!("the trait `", print_def_path(trait_def_id, &[]), "` is object-safe")
2816 ty::PredicateKind::ClosureKind(closure_def_id, _closure_substs, kind) => {
2818 print_value_path(closure_def_id, &[]),
2819 write("` implements the trait `{}`", kind))
2821 ty::PredicateKind::ConstEvaluatable(ct) => {
2822 p!("the constant `", print(ct), "` can be evaluated")
2824 ty::PredicateKind::ConstEquate(c1, c2) => {
2825 p!("the constant `", print(c1), "` equals `", print(c2), "`")
2827 ty::PredicateKind::TypeWellFormedFromEnv(ty) => {
2828 p!("the type `", print(ty), "` is found in the environment")
2830 ty::PredicateKind::Ambiguous => p!("ambiguous"),
2835 match self.unpack() {
2836 GenericArgKind::Lifetime(lt) => p!(print(lt)),
2837 GenericArgKind::Type(ty) => p!(print(ty)),
2838 GenericArgKind::Const(ct) => p!(print(ct)),
2843 fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
2844 // Iterate all local crate items no matter where they are defined.
2845 let hir = tcx.hir();
2846 for id in hir.items() {
2847 if matches!(tcx.def_kind(id.owner_id), DefKind::Use) {
2851 let item = hir.item(id);
2852 if item.ident.name == kw::Empty {
2856 let def_id = item.owner_id.to_def_id();
2857 let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
2858 collect_fn(&item.ident, ns, def_id);
2861 // Now take care of extern crate items.
2862 let queue = &mut Vec::new();
2863 let mut seen_defs: DefIdSet = Default::default();
2865 for &cnum in tcx.crates(()).iter() {
2866 let def_id = cnum.as_def_id();
2868 // Ignore crates that are not direct dependencies.
2869 match tcx.extern_crate(def_id) {
2871 Some(extern_crate) => {
2872 if !extern_crate.is_direct() {
2881 // Iterate external crate defs but be mindful about visibility
2882 while let Some(def) = queue.pop() {
2883 for child in tcx.module_children(def).iter() {
2884 if !child.vis.is_public() {
2889 def::Res::Def(DefKind::AssocTy, _) => {}
2890 def::Res::Def(DefKind::TyAlias, _) => {}
2891 def::Res::Def(defkind, def_id) => {
2892 if let Some(ns) = defkind.ns() {
2893 collect_fn(&child.ident, ns, def_id);
2896 if matches!(defkind, DefKind::Mod | DefKind::Enum | DefKind::Trait)
2897 && seen_defs.insert(def_id)
2908 /// The purpose of this function is to collect public symbols names that are unique across all
2909 /// crates in the build. Later, when printing about types we can use those names instead of the
2910 /// full exported path to them.
2912 /// So essentially, if a symbol name can only be imported from one place for a type, and as
2913 /// long as it was not glob-imported anywhere in the current crate, we can trim its printed
2914 /// path and print only the name.
2916 /// This has wide implications on error messages with types, for example, shortening
2917 /// `std::vec::Vec` to just `Vec`, as long as there is no other `Vec` importable anywhere.
2919 /// The implementation uses similar import discovery logic to that of 'use' suggestions.
2921 /// See also [`DelayDm`](rustc_error_messages::DelayDm) and [`with_no_trimmed_paths`].
2922 fn trimmed_def_paths(tcx: TyCtxt<'_>, (): ()) -> FxHashMap<DefId, Symbol> {
2923 let mut map: FxHashMap<DefId, Symbol> = FxHashMap::default();
2925 if let TrimmedDefPaths::GoodPath = tcx.sess.opts.trimmed_def_paths {
2926 // Trimming paths is expensive and not optimized, since we expect it to only be used for error reporting.
2928 // For good paths causing this bug, the `rustc_middle::ty::print::with_no_trimmed_paths`
2929 // wrapper can be used to suppress this query, in exchange for full paths being formatted.
2930 tcx.sess.delay_good_path_bug(
2931 "trimmed_def_paths constructed but no error emitted; use `DelayDm` for lints or `with_no_trimmed_paths` for debugging",
2935 let unique_symbols_rev: &mut FxHashMap<(Namespace, Symbol), Option<DefId>> =
2936 &mut FxHashMap::default();
2938 for symbol_set in tcx.resolutions(()).glob_map.values() {
2939 for symbol in symbol_set {
2940 unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
2941 unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
2942 unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
2946 for_each_def(tcx, |ident, ns, def_id| {
2947 use std::collections::hash_map::Entry::{Occupied, Vacant};
2949 match unique_symbols_rev.entry((ns, ident.name)) {
2950 Occupied(mut v) => match v.get() {
2953 if *existing != def_id {
2959 v.insert(Some(def_id));
2964 for ((_, symbol), opt_def_id) in unique_symbols_rev.drain() {
2965 use std::collections::hash_map::Entry::{Occupied, Vacant};
2967 if let Some(def_id) = opt_def_id {
2968 match map.entry(def_id) {
2969 Occupied(mut v) => {
2970 // A single DefId can be known under multiple names (e.g.,
2971 // with a `pub use ... as ...;`). We need to ensure that the
2972 // name placed in this map is chosen deterministically, so
2973 // if we find multiple names (`symbol`) resolving to the
2974 // same `def_id`, we prefer the lexicographically smallest
2977 // Any stable ordering would be fine here though.
2978 if *v.get() != symbol {
2979 if v.get().as_str() > symbol.as_str() {
2994 pub fn provide(providers: &mut ty::query::Providers) {
2995 *providers = ty::query::Providers { trimmed_def_paths, ..*providers };
2999 pub struct OpaqueFnEntry<'tcx> {
3000 // The trait ref is already stored as a key, so just track if we have it as a real predicate
3002 fn_mut_trait_ref: Option<ty::PolyTraitRef<'tcx>>,
3003 fn_trait_ref: Option<ty::PolyTraitRef<'tcx>>,
3004 return_ty: Option<ty::Binder<'tcx, Term<'tcx>>>,