1 use crate::mir::interpret::{AllocRange, ConstValue, GlobalAlloc, Pointer, Provenance, Scalar};
2 use crate::ty::subst::{GenericArg, GenericArgKind, Subst};
3 use crate::ty::{self, ConstInt, DefIdTree, ParamConst, ScalarInt, Term, Ty, TyCtxt, TypeFoldable};
4 use rustc_apfloat::ieee::{Double, Single};
5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_data_structures::sso::SsoHashSet;
8 use rustc_hir::def::{self, CtorKind, DefKind, Namespace};
9 use rustc_hir::def_id::{DefId, DefIdSet, CRATE_DEF_INDEX, LOCAL_CRATE};
10 use rustc_hir::definitions::{DefPathData, DefPathDataName, DisambiguatedDefPathData};
11 use rustc_session::config::TrimmedDefPaths;
12 use rustc_session::cstore::{ExternCrate, ExternCrateSource};
13 use rustc_span::symbol::{kw, Ident, Symbol};
14 use rustc_target::abi::Size;
15 use rustc_target::spec::abi::Abi;
19 use std::collections::BTreeMap;
20 use std::convert::TryFrom;
21 use std::fmt::{self, Write as _};
23 use std::ops::{ControlFlow, Deref, DerefMut};
25 // `pretty` is a separate module only for organization.
30 write!(scoped_cx!(), $lit)?
32 (@write($($data:expr),+)) => {
33 write!(scoped_cx!(), $($data),+)?
35 (@print($x:expr)) => {
36 scoped_cx!() = $x.print(scoped_cx!())?
38 (@$method:ident($($arg:expr),*)) => {
39 scoped_cx!() = scoped_cx!().$method($($arg),*)?
41 ($($elem:tt $(($($args:tt)*))?),+) => {{
42 $(p!(@ $elem $(($($args)*))?);)+
45 macro_rules! define_scoped_cx {
47 #[allow(unused_macros)]
48 macro_rules! scoped_cx {
57 static FORCE_IMPL_FILENAME_LINE: Cell<bool> = const { Cell::new(false) };
58 static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = const { Cell::new(false) };
59 static NO_TRIMMED_PATH: Cell<bool> = const { Cell::new(false) };
60 static NO_QUERIES: Cell<bool> = const { Cell::new(false) };
61 static NO_VISIBLE_PATH: Cell<bool> = const { Cell::new(false) };
64 macro_rules! define_helper {
65 ($($(#[$a:meta])* fn $name:ident($helper:ident, $tl:ident);)+) => {
68 pub struct $helper(bool);
71 pub fn new() -> $helper {
72 $helper($tl.with(|c| c.replace(true)))
77 pub macro $name($e:expr) {
79 let _guard = $helper::new();
84 impl Drop for $helper {
86 $tl.with(|c| c.set(self.0))
94 /// Avoids running any queries during any prints that occur
95 /// during the closure. This may alter the appearance of some
96 /// types (e.g. forcing verbose printing for opaque types).
97 /// This method is used during some queries (e.g. `explicit_item_bounds`
98 /// for opaque types), to ensure that any debug printing that
99 /// occurs during the query computation does not end up recursively
100 /// calling the same query.
101 fn with_no_queries(NoQueriesGuard, NO_QUERIES);
102 /// Force us to name impls with just the filename/line number. We
103 /// normally try to use types. But at some points, notably while printing
104 /// cycle errors, this can result in extra or suboptimal error output,
105 /// so this variable disables that check.
106 fn with_forced_impl_filename_line(ForcedImplGuard, FORCE_IMPL_FILENAME_LINE);
107 /// Adds the `crate::` prefix to paths where appropriate.
108 fn with_crate_prefix(CratePrefixGuard, SHOULD_PREFIX_WITH_CRATE);
109 /// Prevent path trimming if it is turned on. Path trimming affects `Display` impl
110 /// of various rustc types, for example `std::vec::Vec` would be trimmed to `Vec`,
111 /// if no other `Vec` is found.
112 fn with_no_trimmed_paths(NoTrimmedGuard, NO_TRIMMED_PATH);
113 /// Prevent selection of visible paths. `Display` impl of DefId will prefer
114 /// visible (public) reexports of types as paths.
115 fn with_no_visible_paths(NoVisibleGuard, NO_VISIBLE_PATH);
118 /// The "region highlights" are used to control region printing during
119 /// specific error messages. When a "region highlight" is enabled, it
120 /// gives an alternate way to print specific regions. For now, we
121 /// always print those regions using a number, so something like "`'0`".
123 /// Regions not selected by the region highlight mode are presently
125 #[derive(Copy, Clone)]
126 pub struct RegionHighlightMode<'tcx> {
129 /// If enabled, when we see the selected region, use "`'N`"
130 /// instead of the ordinary behavior.
131 highlight_regions: [Option<(ty::Region<'tcx>, usize)>; 3],
133 /// If enabled, when printing a "free region" that originated from
134 /// the given `ty::BoundRegionKind`, print it as "`'1`". Free regions that would ordinarily
135 /// have names print as normal.
137 /// This is used when you have a signature like `fn foo(x: &u32,
138 /// y: &'a u32)` and we want to give a name to the region of the
140 highlight_bound_region: Option<(ty::BoundRegionKind, usize)>,
143 impl<'tcx> RegionHighlightMode<'tcx> {
144 pub fn new(tcx: TyCtxt<'tcx>) -> Self {
147 highlight_regions: Default::default(),
148 highlight_bound_region: Default::default(),
152 /// If `region` and `number` are both `Some`, invokes
153 /// `highlighting_region`.
154 pub fn maybe_highlighting_region(
156 region: Option<ty::Region<'tcx>>,
157 number: Option<usize>,
159 if let Some(k) = region {
160 if let Some(n) = number {
161 self.highlighting_region(k, n);
166 /// Highlights the region inference variable `vid` as `'N`.
167 pub fn highlighting_region(&mut self, region: ty::Region<'tcx>, number: usize) {
168 let num_slots = self.highlight_regions.len();
169 let first_avail_slot =
170 self.highlight_regions.iter_mut().find(|s| s.is_none()).unwrap_or_else(|| {
171 bug!("can only highlight {} placeholders at a time", num_slots,)
173 *first_avail_slot = Some((region, number));
176 /// Convenience wrapper for `highlighting_region`.
177 pub fn highlighting_region_vid(&mut self, vid: ty::RegionVid, number: usize) {
178 self.highlighting_region(self.tcx.mk_region(ty::ReVar(vid)), number)
181 /// Returns `Some(n)` with the number to use for the given region, if any.
182 fn region_highlighted(&self, region: ty::Region<'_>) -> Option<usize> {
183 self.highlight_regions.iter().find_map(|h| match h {
184 Some((r, n)) if *r == region => Some(*n),
189 /// Highlight the given bound region.
190 /// We can only highlight one bound region at a time. See
191 /// the field `highlight_bound_region` for more detailed notes.
192 pub fn highlighting_bound_region(&mut self, br: ty::BoundRegionKind, number: usize) {
193 assert!(self.highlight_bound_region.is_none());
194 self.highlight_bound_region = Some((br, number));
198 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
199 pub trait PrettyPrinter<'tcx>:
206 DynExistential = Self,
210 /// Like `print_def_path` but for value paths.
214 substs: &'tcx [GenericArg<'tcx>],
215 ) -> Result<Self::Path, Self::Error> {
216 self.print_def_path(def_id, substs)
219 fn in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, Self::Error>
221 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
223 value.as_ref().skip_binder().print(self)
226 fn wrap_binder<T, F: Fn(&T, Self) -> Result<Self, fmt::Error>>(
228 value: &ty::Binder<'tcx, T>,
230 ) -> Result<Self, Self::Error>
232 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
234 f(value.as_ref().skip_binder(), self)
237 /// Prints comma-separated elements.
238 fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
240 T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
242 if let Some(first) = elems.next() {
243 self = first.print(self)?;
245 self.write_str(", ")?;
246 self = elem.print(self)?;
252 /// Prints `{f: t}` or `{f as t}` depending on the `cast` argument
255 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
256 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
258 ) -> Result<Self::Const, Self::Error> {
259 self.write_str("{")?;
261 self.write_str(conversion)?;
263 self.write_str("}")?;
267 /// Prints `<...>` around what `f` prints.
268 fn generic_delimiters(
270 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
271 ) -> Result<Self, Self::Error>;
273 /// Returns `true` if the region should be printed in
274 /// optional positions, e.g., `&'a T` or `dyn Tr + 'b`.
275 /// This is typically the case for all non-`'_` regions.
276 fn should_print_region(&self, region: ty::Region<'_>) -> bool;
278 // Defaults (should not be overridden):
280 /// If possible, this returns a global path resolving to `def_id` that is visible
281 /// from at least one local module, and returns `true`. If the crate defining `def_id` is
282 /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
283 fn try_print_visible_def_path(self, def_id: DefId) -> Result<(Self, bool), Self::Error> {
284 if NO_VISIBLE_PATH.with(|flag| flag.get()) {
285 return Ok((self, false));
288 let mut callers = Vec::new();
289 self.try_print_visible_def_path_recur(def_id, &mut callers)
292 /// Try to see if this path can be trimmed to a unique symbol name.
293 fn try_print_trimmed_def_path(
296 ) -> Result<(Self::Path, bool), Self::Error> {
297 if !self.tcx().sess.opts.debugging_opts.trim_diagnostic_paths
298 || matches!(self.tcx().sess.opts.trimmed_def_paths, TrimmedDefPaths::Never)
299 || NO_TRIMMED_PATH.with(|flag| flag.get())
300 || SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get())
302 return Ok((self, false));
305 match self.tcx().trimmed_def_paths(()).get(&def_id) {
306 None => Ok((self, false)),
308 self.write_str(symbol.as_str())?;
314 /// Does the work of `try_print_visible_def_path`, building the
315 /// full definition path recursively before attempting to
316 /// post-process it into the valid and visible version that
317 /// accounts for re-exports.
319 /// This method should only be called by itself or
320 /// `try_print_visible_def_path`.
322 /// `callers` is a chain of visible_parent's leading to `def_id`,
323 /// to support cycle detection during recursion.
325 /// This method returns false if we can't print the visible path, so
326 /// `print_def_path` can fall back on the item's real definition path.
327 fn try_print_visible_def_path_recur(
330 callers: &mut Vec<DefId>,
331 ) -> Result<(Self, bool), Self::Error> {
332 define_scoped_cx!(self);
334 debug!("try_print_visible_def_path: def_id={:?}", def_id);
336 // If `def_id` is a direct or injected extern crate, return the
337 // path to the crate followed by the path to the item within the crate.
338 if def_id.index == CRATE_DEF_INDEX {
339 let cnum = def_id.krate;
341 if cnum == LOCAL_CRATE {
342 return Ok((self.path_crate(cnum)?, true));
345 // In local mode, when we encounter a crate other than
346 // LOCAL_CRATE, execution proceeds in one of two ways:
348 // 1. For a direct dependency, where user added an
349 // `extern crate` manually, we put the `extern
350 // crate` as the parent. So you wind up with
351 // something relative to the current crate.
352 // 2. For an extern inferred from a path or an indirect crate,
353 // where there is no explicit `extern crate`, we just prepend
355 match self.tcx().extern_crate(def_id) {
356 Some(&ExternCrate { src, dependency_of, span, .. }) => match (src, dependency_of) {
357 (ExternCrateSource::Extern(def_id), LOCAL_CRATE) => {
358 // NOTE(eddyb) the only reason `span` might be dummy,
359 // that we're aware of, is that it's the `std`/`core`
360 // `extern crate` injected by default.
361 // FIXME(eddyb) find something better to key this on,
362 // or avoid ending up with `ExternCrateSource::Extern`,
363 // for the injected `std`/`core`.
365 return Ok((self.path_crate(cnum)?, true));
368 // Disable `try_print_trimmed_def_path` behavior within
369 // the `print_def_path` call, to avoid infinite recursion
370 // in cases where the `extern crate foo` has non-trivial
371 // parents, e.g. it's nested in `impl foo::Trait for Bar`
372 // (see also issues #55779 and #87932).
373 self = with_no_visible_paths!(self.print_def_path(def_id, &[])?);
375 return Ok((self, true));
377 (ExternCrateSource::Path, LOCAL_CRATE) => {
378 return Ok((self.path_crate(cnum)?, true));
383 return Ok((self.path_crate(cnum)?, true));
388 if def_id.is_local() {
389 return Ok((self, false));
392 let visible_parent_map = self.tcx().visible_parent_map(());
394 let mut cur_def_key = self.tcx().def_key(def_id);
395 debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
397 // For a constructor, we want the name of its parent rather than <unnamed>.
398 if let DefPathData::Ctor = cur_def_key.disambiguated_data.data {
403 .expect("`DefPathData::Ctor` / `VariantData` missing a parent"),
406 cur_def_key = self.tcx().def_key(parent);
409 let Some(visible_parent) = visible_parent_map.get(&def_id).cloned() else {
410 return Ok((self, false));
413 let actual_parent = self.tcx().parent(def_id);
415 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
416 visible_parent, actual_parent,
419 let mut data = cur_def_key.disambiguated_data.data;
421 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
422 data, visible_parent, actual_parent,
426 // In order to output a path that could actually be imported (valid and visible),
427 // we need to handle re-exports correctly.
429 // For example, take `std::os::unix::process::CommandExt`, this trait is actually
430 // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
432 // `std::os::unix` reexports the contents of `std::sys::unix::ext`. `std::sys` is
433 // private so the "true" path to `CommandExt` isn't accessible.
435 // In this case, the `visible_parent_map` will look something like this:
437 // (child) -> (parent)
438 // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
439 // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
440 // `std::sys::unix::ext` -> `std::os`
442 // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
445 // When printing the path to `CommandExt` and looking at the `cur_def_key` that
446 // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
447 // to the parent - resulting in a mangled path like
448 // `std::os::ext::process::CommandExt`.
450 // Instead, we must detect that there was a re-export and instead print `unix`
451 // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
452 // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
453 // the visible parent (`std::os`). If these do not match, then we iterate over
454 // the children of the visible parent (as was done when computing
455 // `visible_parent_map`), looking for the specific child we currently have and then
456 // have access to the re-exported name.
457 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
458 // Item might be re-exported several times, but filter for the one
459 // that's public and whose identifier isn't `_`.
462 .module_children(visible_parent)
464 .filter(|child| child.res.opt_def_id() == Some(def_id))
465 .find(|child| child.vis.is_public() && child.ident.name != kw::Underscore)
466 .map(|child| child.ident.name);
468 if let Some(new_name) = reexport {
471 // There is no name that is public and isn't `_`, so bail.
472 return Ok((self, false));
475 // Re-exported `extern crate` (#43189).
476 DefPathData::CrateRoot => {
477 data = DefPathData::TypeNs(self.tcx().crate_name(def_id.krate));
481 debug!("try_print_visible_def_path: data={:?}", data);
483 if callers.contains(&visible_parent) {
484 return Ok((self, false));
486 callers.push(visible_parent);
487 // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
488 // knowing ahead of time whether the entire path will succeed or not.
489 // To support printers that do not implement `PrettyPrinter`, a `Vec` or
490 // linked list on the stack would need to be built, before any printing.
491 match self.try_print_visible_def_path_recur(visible_parent, callers)? {
492 (cx, false) => return Ok((cx, false)),
493 (cx, true) => self = cx,
497 Ok((self.path_append(Ok, &DisambiguatedDefPathData { data, disambiguator: 0 })?, true))
500 fn pretty_path_qualified(
503 trait_ref: Option<ty::TraitRef<'tcx>>,
504 ) -> Result<Self::Path, Self::Error> {
505 if trait_ref.is_none() {
506 // Inherent impls. Try to print `Foo::bar` for an inherent
507 // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
508 // anything other than a simple path.
509 match self_ty.kind() {
518 return self_ty.print(self);
525 self.generic_delimiters(|mut cx| {
526 define_scoped_cx!(cx);
529 if let Some(trait_ref) = trait_ref {
530 p!(" as ", print(trait_ref.print_only_trait_path()));
536 fn pretty_path_append_impl(
538 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
540 trait_ref: Option<ty::TraitRef<'tcx>>,
541 ) -> Result<Self::Path, Self::Error> {
542 self = print_prefix(self)?;
544 self.generic_delimiters(|mut cx| {
545 define_scoped_cx!(cx);
548 if let Some(trait_ref) = trait_ref {
549 p!(print(trait_ref.print_only_trait_path()), " for ");
557 fn pretty_print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
558 define_scoped_cx!(self);
561 ty::Bool => p!("bool"),
562 ty::Char => p!("char"),
563 ty::Int(t) => p!(write("{}", t.name_str())),
564 ty::Uint(t) => p!(write("{}", t.name_str())),
565 ty::Float(t) => p!(write("{}", t.name_str())),
566 ty::RawPtr(ref tm) => {
570 hir::Mutability::Mut => "mut",
571 hir::Mutability::Not => "const",
576 ty::Ref(r, ty, mutbl) => {
578 if self.should_print_region(r) {
581 p!(print(ty::TypeAndMut { ty, mutbl }))
583 ty::Never => p!("!"),
584 ty::Tuple(ref tys) => {
585 p!("(", comma_sep(tys.iter()));
591 ty::FnDef(def_id, substs) => {
592 let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs);
593 p!(print(sig), " {{", print_value_path(def_id, substs), "}}");
595 ty::FnPtr(ref bare_fn) => p!(print(bare_fn)),
596 ty::Infer(infer_ty) => {
597 let verbose = self.tcx().sess.verbose();
598 if let ty::TyVar(ty_vid) = infer_ty {
599 if let Some(name) = self.ty_infer_name(ty_vid) {
600 p!(write("{}", name))
603 p!(write("{:?}", infer_ty))
605 p!(write("{}", infer_ty))
609 if verbose { p!(write("{:?}", infer_ty)) } else { p!(write("{}", infer_ty)) }
612 ty::Error(_) => p!("[type error]"),
613 ty::Param(ref param_ty) => p!(print(param_ty)),
614 ty::Bound(debruijn, bound_ty) => match bound_ty.kind {
615 ty::BoundTyKind::Anon => self.pretty_print_bound_var(debruijn, bound_ty.var)?,
616 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
618 ty::Adt(def, substs) => {
619 p!(print_def_path(def.did(), substs));
621 ty::Dynamic(data, r) => {
622 let print_r = self.should_print_region(r);
626 p!("dyn ", print(data));
628 p!(" + ", print(r), ")");
631 ty::Foreign(def_id) => {
632 p!(print_def_path(def_id, &[]));
634 ty::Projection(ref data) => p!(print(data)),
635 ty::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
636 ty::Opaque(def_id, substs) => {
637 // FIXME(eddyb) print this with `print_def_path`.
638 // We use verbose printing in 'NO_QUERIES' mode, to
639 // avoid needing to call `predicates_of`. This should
640 // only affect certain debug messages (e.g. messages printed
641 // from `rustc_middle::ty` during the computation of `tcx.predicates_of`),
642 // and should have no effect on any compiler output.
643 if self.tcx().sess.verbose() || NO_QUERIES.with(|q| q.get()) {
644 p!(write("Opaque({:?}, {:?})", def_id, substs));
648 let parent = self.tcx().parent(def_id).expect("opaque types always have a parent");
649 match self.tcx().def_kind(parent) {
650 DefKind::TyAlias | DefKind::AssocTy => {
651 if let ty::Opaque(d, _) = *self.tcx().type_of(parent).kind() {
653 // If the type alias directly starts with the `impl` of the
654 // opaque type we're printing, then skip the `::{opaque#1}`.
655 p!(print_def_path(parent, substs));
659 // Complex opaque type, e.g. `type Foo = (i32, impl Debug);`
660 p!(print_def_path(def_id, substs));
663 _ => return self.pretty_print_opaque_impl_type(def_id, substs),
666 ty::Str => p!("str"),
667 ty::Generator(did, substs, movability) => {
670 hir::Movability::Movable => {}
671 hir::Movability::Static => p!("static "),
674 if !self.tcx().sess.verbose() {
676 // FIXME(eddyb) should use `def_span`.
677 if let Some(did) = did.as_local() {
678 let span = self.tcx().def_span(did);
681 // This may end up in stderr diagnostics but it may also be emitted
682 // into MIR. Hence we use the remapped path if available
683 self.tcx().sess.source_map().span_to_embeddable_string(span)
686 p!(write("@"), print_def_path(did, substs));
689 p!(print_def_path(did, substs));
691 if !substs.as_generator().is_valid() {
694 self = self.comma_sep(substs.as_generator().upvar_tys())?;
698 if substs.as_generator().is_valid() {
699 p!(" ", print(substs.as_generator().witness()));
705 ty::GeneratorWitness(types) => {
706 p!(in_binder(&types));
708 ty::Closure(did, substs) => {
710 if !self.tcx().sess.verbose() {
711 p!(write("closure"));
712 // FIXME(eddyb) should use `def_span`.
713 if let Some(did) = did.as_local() {
714 if self.tcx().sess.opts.debugging_opts.span_free_formats {
715 p!("@", print_def_path(did.to_def_id(), substs));
717 let span = self.tcx().def_span(did);
720 // This may end up in stderr diagnostics but it may also be emitted
721 // into MIR. Hence we use the remapped path if available
722 self.tcx().sess.source_map().span_to_embeddable_string(span)
726 p!(write("@"), print_def_path(did, substs));
729 p!(print_def_path(did, substs));
730 if !substs.as_closure().is_valid() {
731 p!(" closure_substs=(unavailable)");
732 p!(write(" substs={:?}", substs));
734 p!(" closure_kind_ty=", print(substs.as_closure().kind_ty()));
736 " closure_sig_as_fn_ptr_ty=",
737 print(substs.as_closure().sig_as_fn_ptr_ty())
740 self = self.comma_sep(substs.as_closure().upvar_tys())?;
746 ty::Array(ty, sz) => {
747 p!("[", print(ty), "; ");
748 if self.tcx().sess.verbose() {
749 p!(write("{:?}", sz));
750 } else if let ty::ConstKind::Unevaluated(..) = sz.val() {
751 // Do not try to evaluate unevaluated constants. If we are const evaluating an
752 // array length anon const, rustc will (with debug assertions) print the
753 // constant's path. Which will end up here again.
755 } else if let Some(n) = sz.val().try_to_bits(self.tcx().data_layout.pointer_size) {
757 } else if let ty::ConstKind::Param(param) = sz.val() {
764 ty::Slice(ty) => p!("[", print(ty), "]"),
770 fn pretty_print_opaque_impl_type(
773 substs: &'tcx ty::List<ty::GenericArg<'tcx>>,
774 ) -> Result<Self::Type, Self::Error> {
775 define_scoped_cx!(self);
777 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
778 // by looking up the projections associated with the def_id.
779 let bounds = self.tcx().explicit_item_bounds(def_id);
781 let mut traits = BTreeMap::new();
782 let mut fn_traits = BTreeMap::new();
783 let mut is_sized = false;
785 for (predicate, _) in bounds {
786 let predicate = predicate.subst(self.tcx(), substs);
787 let bound_predicate = predicate.kind();
789 match bound_predicate.skip_binder() {
790 ty::PredicateKind::Trait(pred) => {
791 let trait_ref = bound_predicate.rebind(pred.trait_ref);
793 // Don't print + Sized, but rather + ?Sized if absent.
794 if Some(trait_ref.def_id()) == self.tcx().lang_items().sized_trait() {
799 self.insert_trait_and_projection(trait_ref, None, &mut traits, &mut fn_traits);
801 ty::PredicateKind::Projection(pred) => {
802 let proj_ref = bound_predicate.rebind(pred);
803 let trait_ref = proj_ref.required_poly_trait_ref(self.tcx());
805 // Projection type entry -- the def-id for naming, and the ty.
806 let proj_ty = (proj_ref.projection_def_id(), proj_ref.term());
808 self.insert_trait_and_projection(
819 let mut first = true;
820 // Insert parenthesis around (Fn(A, B) -> C) if the opaque ty has more than one other trait
821 let paren_needed = fn_traits.len() > 1 || traits.len() > 0 || !is_sized;
825 for (fn_once_trait_ref, entry) in fn_traits {
826 // Get the (single) generic ty (the args) of this FnOnce trait ref.
827 let generics = self.generic_args_to_print(
828 self.tcx().generics_of(fn_once_trait_ref.def_id()),
829 fn_once_trait_ref.skip_binder().substs,
832 match (entry.return_ty, generics[0].expect_ty()) {
833 // We can only print `impl Fn() -> ()` if we have a tuple of args and we recorded
835 (Some(return_ty), arg_tys) if matches!(arg_tys.kind(), ty::Tuple(_)) => {
836 let name = if entry.fn_trait_ref.is_some() {
838 } else if entry.fn_mut_trait_ref.is_some() {
845 write("{}", if first { " " } else { " + " }),
846 write("{}{}(", if paren_needed { "(" } else { "" }, name)
849 for (idx, ty) in arg_tys.tuple_fields().iter().enumerate() {
857 if let Term::Ty(ty) = return_ty.skip_binder() {
859 p!("-> ", print(return_ty));
862 p!(write("{}", if paren_needed { ")" } else { "" }));
866 // If we got here, we can't print as a `impl Fn(A, B) -> C`. Just record the
867 // trait_refs we collected in the OpaqueFnEntry as normal trait refs.
869 if entry.has_fn_once {
870 traits.entry(fn_once_trait_ref).or_default().extend(
871 // Group the return ty with its def id, if we had one.
874 .map(|ty| (self.tcx().lang_items().fn_once_output().unwrap(), ty)),
877 if let Some(trait_ref) = entry.fn_mut_trait_ref {
878 traits.entry(trait_ref).or_default();
880 if let Some(trait_ref) = entry.fn_trait_ref {
881 traits.entry(trait_ref).or_default();
887 // Print the rest of the trait types (that aren't Fn* family of traits)
888 for (trait_ref, assoc_items) in traits {
890 write("{}", if first { " " } else { " + " }),
891 print(trait_ref.skip_binder().print_only_trait_name())
894 let generics = self.generic_args_to_print(
895 self.tcx().generics_of(trait_ref.def_id()),
896 trait_ref.skip_binder().substs,
899 if !generics.is_empty() || !assoc_items.is_empty() {
900 let mut first = true;
909 p!(print(trait_ref.rebind(*ty)));
912 for (assoc_item_def_id, term) in assoc_items {
913 // Skip printing `<[generator@] as Generator<_>>::Return` from async blocks,
914 // unless we can find out what generator return type it comes from.
915 let term = if let Some(ty) = term.skip_binder().ty()
916 && let ty::Projection(ty::ProjectionTy { item_def_id, substs }) = ty.kind()
917 && Some(*item_def_id) == self.tcx().lang_items().generator_return()
919 if let ty::Generator(_, substs, _) = substs.type_at(0).kind() {
920 let return_ty = substs.as_generator().return_ty();
921 if !return_ty.is_ty_infer() {
940 p!(write("{} = ", self.tcx().associated_item(assoc_item_def_id).name));
961 p!(write("{}?Sized", if first { " " } else { " + " }));
969 /// Insert the trait ref and optionally a projection type associated with it into either the
970 /// traits map or fn_traits map, depending on if the trait is in the Fn* family of traits.
971 fn insert_trait_and_projection(
973 trait_ref: ty::PolyTraitRef<'tcx>,
974 proj_ty: Option<(DefId, ty::Binder<'tcx, Term<'tcx>>)>,
975 traits: &mut BTreeMap<
976 ty::PolyTraitRef<'tcx>,
977 BTreeMap<DefId, ty::Binder<'tcx, Term<'tcx>>>,
979 fn_traits: &mut BTreeMap<ty::PolyTraitRef<'tcx>, OpaqueFnEntry<'tcx>>,
981 let trait_def_id = trait_ref.def_id();
983 // If our trait_ref is FnOnce or any of its children, project it onto the parent FnOnce
984 // super-trait ref and record it there.
985 if let Some(fn_once_trait) = self.tcx().lang_items().fn_once_trait() {
986 // If we have a FnOnce, then insert it into
987 if trait_def_id == fn_once_trait {
988 let entry = fn_traits.entry(trait_ref).or_default();
989 // Optionally insert the return_ty as well.
990 if let Some((_, ty)) = proj_ty {
991 entry.return_ty = Some(ty);
993 entry.has_fn_once = true;
995 } else if Some(trait_def_id) == self.tcx().lang_items().fn_mut_trait() {
996 let super_trait_ref = crate::traits::util::supertraits(self.tcx(), trait_ref)
997 .find(|super_trait_ref| super_trait_ref.def_id() == fn_once_trait)
1000 fn_traits.entry(super_trait_ref).or_default().fn_mut_trait_ref = Some(trait_ref);
1002 } else if Some(trait_def_id) == self.tcx().lang_items().fn_trait() {
1003 let super_trait_ref = crate::traits::util::supertraits(self.tcx(), trait_ref)
1004 .find(|super_trait_ref| super_trait_ref.def_id() == fn_once_trait)
1007 fn_traits.entry(super_trait_ref).or_default().fn_trait_ref = Some(trait_ref);
1012 // Otherwise, just group our traits and projection types.
1013 traits.entry(trait_ref).or_default().extend(proj_ty);
1016 fn pretty_print_bound_var(
1018 debruijn: ty::DebruijnIndex,
1020 ) -> Result<(), Self::Error> {
1021 if debruijn == ty::INNERMOST {
1022 write!(self, "^{}", var.index())
1024 write!(self, "^{}_{}", debruijn.index(), var.index())
1028 fn ty_infer_name(&self, _: ty::TyVid) -> Option<String> {
1032 fn const_infer_name(&self, _: ty::ConstVid<'tcx>) -> Option<String> {
1036 fn pretty_print_dyn_existential(
1038 predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
1039 ) -> Result<Self::DynExistential, Self::Error> {
1040 // Generate the main trait ref, including associated types.
1041 let mut first = true;
1043 if let Some(principal) = predicates.principal() {
1044 self = self.wrap_binder(&principal, |principal, mut cx| {
1045 define_scoped_cx!(cx);
1046 p!(print_def_path(principal.def_id, &[]));
1048 let mut resugared = false;
1050 // Special-case `Fn(...) -> ...` and re-sugar it.
1051 let fn_trait_kind = cx.tcx().fn_trait_kind_from_lang_item(principal.def_id);
1052 if !cx.tcx().sess.verbose() && fn_trait_kind.is_some() {
1053 if let ty::Tuple(tys) = principal.substs.type_at(0).kind() {
1054 let mut projections = predicates.projection_bounds();
1055 if let (Some(proj), None) = (projections.next(), projections.next()) {
1059 proj.skip_binder().term.ty().expect("Return type was a const")
1066 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
1067 // in order to place the projections inside the `<...>`.
1069 // Use a type that can't appear in defaults of type parameters.
1070 let dummy_cx = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1071 let principal = principal.with_self_ty(cx.tcx(), dummy_cx);
1073 let args = cx.generic_args_to_print(
1074 cx.tcx().generics_of(principal.def_id),
1078 // Don't print `'_` if there's no unerased regions.
1079 let print_regions = args.iter().any(|arg| match arg.unpack() {
1080 GenericArgKind::Lifetime(r) => !r.is_erased(),
1083 let mut args = args.iter().cloned().filter(|arg| match arg.unpack() {
1084 GenericArgKind::Lifetime(_) => print_regions,
1087 let mut projections = predicates.projection_bounds();
1089 let arg0 = args.next();
1090 let projection0 = projections.next();
1091 if arg0.is_some() || projection0.is_some() {
1092 let args = arg0.into_iter().chain(args);
1093 let projections = projection0.into_iter().chain(projections);
1095 p!(generic_delimiters(|mut cx| {
1096 cx = cx.comma_sep(args)?;
1097 if arg0.is_some() && projection0.is_some() {
1100 cx.comma_sep(projections)
1110 define_scoped_cx!(self);
1113 // FIXME(eddyb) avoid printing twice (needed to ensure
1114 // that the auto traits are sorted *and* printed via cx).
1115 let mut auto_traits: Vec<_> =
1116 predicates.auto_traits().map(|did| (self.tcx().def_path_str(did), did)).collect();
1118 // The auto traits come ordered by `DefPathHash`. While
1119 // `DefPathHash` is *stable* in the sense that it depends on
1120 // neither the host nor the phase of the moon, it depends
1121 // "pseudorandomly" on the compiler version and the target.
1123 // To avoid that causing instabilities in compiletest
1124 // output, sort the auto-traits alphabetically.
1127 for (_, def_id) in auto_traits {
1133 p!(print_def_path(def_id, &[]));
1141 inputs: &[Ty<'tcx>],
1144 ) -> Result<Self, Self::Error> {
1145 define_scoped_cx!(self);
1147 p!("(", comma_sep(inputs.iter().copied()));
1149 if !inputs.is_empty() {
1155 if !output.is_unit() {
1156 p!(" -> ", print(output));
1162 fn pretty_print_const(
1164 ct: ty::Const<'tcx>,
1166 ) -> Result<Self::Const, Self::Error> {
1167 define_scoped_cx!(self);
1169 if self.tcx().sess.verbose() {
1170 p!(write("Const({:?}: {:?})", ct.val(), ct.ty()));
1174 macro_rules! print_underscore {
1177 self = self.typed_value(
1182 |this| this.print_type(ct.ty()),
1192 ty::ConstKind::Unevaluated(ty::Unevaluated {
1195 promoted: Some(promoted),
1197 p!(print_value_path(def.did, substs));
1198 p!(write("::{:?}", promoted));
1200 ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted: None }) => {
1201 match self.tcx().def_kind(def.did) {
1202 DefKind::Static(..) | DefKind::Const | DefKind::AssocConst => {
1203 p!(print_value_path(def.did, substs))
1207 let span = self.tcx().def_span(def.did);
1208 if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span) {
1209 p!(write("{}", snip))
1219 ty::ConstKind::Infer(infer_ct) => {
1221 ty::InferConst::Var(ct_vid)
1222 if let Some(name) = self.const_infer_name(ct_vid) =>
1223 p!(write("{}", name)),
1224 _ => print_underscore!(),
1227 ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)),
1228 ty::ConstKind::Value(value) => {
1229 return self.pretty_print_const_value(value, ct.ty(), print_ty);
1232 ty::ConstKind::Bound(debruijn, bound_var) => {
1233 self.pretty_print_bound_var(debruijn, bound_var)?
1235 ty::ConstKind::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
1236 ty::ConstKind::Error(_) => p!("[const error]"),
1241 fn pretty_print_const_scalar(
1246 ) -> Result<Self::Const, Self::Error> {
1248 Scalar::Ptr(ptr, _size) => self.pretty_print_const_scalar_ptr(ptr, ty, print_ty),
1249 Scalar::Int(int) => self.pretty_print_const_scalar_int(int, ty, print_ty),
1253 fn pretty_print_const_scalar_ptr(
1258 ) -> Result<Self::Const, Self::Error> {
1259 define_scoped_cx!(self);
1261 let (alloc_id, offset) = ptr.into_parts();
1263 // Byte strings (&[u8; N])
1264 ty::Ref(_, inner, _) => {
1265 if let ty::Array(elem, len) = inner.kind() {
1266 if let ty::Uint(ty::UintTy::U8) = elem.kind() {
1267 if let ty::ConstKind::Value(ConstValue::Scalar(int)) = len.val() {
1268 match self.tcx().get_global_alloc(alloc_id) {
1269 Some(GlobalAlloc::Memory(alloc)) => {
1270 let len = int.assert_bits(self.tcx().data_layout.pointer_size);
1272 AllocRange { start: offset, size: Size::from_bytes(len) };
1273 if let Ok(byte_str) =
1274 alloc.inner().get_bytes(&self.tcx(), range)
1276 p!(pretty_print_byte_str(byte_str))
1278 p!("<too short allocation>")
1281 // FIXME: for statics and functions, we could in principle print more detail.
1282 Some(GlobalAlloc::Static(def_id)) => {
1283 p!(write("<static({:?})>", def_id))
1285 Some(GlobalAlloc::Function(_)) => p!("<function>"),
1286 None => p!("<dangling pointer>"),
1294 // FIXME: We should probably have a helper method to share code with the "Byte strings"
1295 // printing above (which also has to handle pointers to all sorts of things).
1296 if let Some(GlobalAlloc::Function(instance)) = self.tcx().get_global_alloc(alloc_id)
1298 self = self.typed_value(
1299 |this| this.print_value_path(instance.def_id(), instance.substs),
1300 |this| this.print_type(ty),
1308 // Any pointer values not covered by a branch above
1309 self = self.pretty_print_const_pointer(ptr, ty, print_ty)?;
1313 fn pretty_print_const_scalar_int(
1318 ) -> Result<Self::Const, Self::Error> {
1319 define_scoped_cx!(self);
1323 ty::Bool if int == ScalarInt::FALSE => p!("false"),
1324 ty::Bool if int == ScalarInt::TRUE => p!("true"),
1326 ty::Float(ty::FloatTy::F32) => {
1327 p!(write("{}f32", Single::try_from(int).unwrap()))
1329 ty::Float(ty::FloatTy::F64) => {
1330 p!(write("{}f64", Double::try_from(int).unwrap()))
1333 ty::Uint(_) | ty::Int(_) => {
1335 ConstInt::new(int, matches!(ty.kind(), ty::Int(_)), ty.is_ptr_sized_integral());
1336 if print_ty { p!(write("{:#?}", int)) } else { p!(write("{:?}", int)) }
1339 ty::Char if char::try_from(int).is_ok() => {
1340 p!(write("{:?}", char::try_from(int).unwrap()))
1343 ty::Ref(..) | ty::RawPtr(_) | ty::FnPtr(_) => {
1344 let data = int.assert_bits(self.tcx().data_layout.pointer_size);
1345 self = self.typed_value(
1347 write!(this, "0x{:x}", data)?;
1350 |this| this.print_type(ty),
1354 // For function type zsts just printing the path is enough
1355 ty::FnDef(d, s) if int == ScalarInt::ZST => {
1356 p!(print_value_path(*d, s))
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_value(
1415 ct: ConstValue<'tcx>,
1418 ) -> Result<Self::Const, Self::Error> {
1419 define_scoped_cx!(self);
1421 if self.tcx().sess.verbose() {
1422 p!(write("ConstValue({:?}: ", ct), print(ty), ")");
1426 let u8_type = self.tcx().types.u8;
1428 match (ct, ty.kind()) {
1429 // Byte/string slices, printed as (byte) string literals.
1430 (ConstValue::Slice { data, start, end }, ty::Ref(_, inner, _)) => {
1431 match inner.kind() {
1434 // The `inspect` here is okay since we checked the bounds, and there are
1435 // no relocations (we have an active slice reference here). We don't use
1436 // this result to affect interpreter execution.
1439 .inspect_with_uninit_and_ptr_outside_interpreter(start..end);
1440 return self.pretty_print_byte_str(byte_str);
1444 // The `inspect` here is okay since we checked the bounds, and there are no
1445 // relocations (we have an active `str` reference here). We don't use this
1446 // result to affect interpreter execution.
1449 .inspect_with_uninit_and_ptr_outside_interpreter(start..end);
1450 p!(write("{:?}", String::from_utf8_lossy(slice)));
1456 (ConstValue::ByRef { alloc, offset }, ty::Array(t, n)) if *t == u8_type => {
1457 let n = n.val().try_to_bits(self.tcx().data_layout.pointer_size).unwrap();
1458 // cast is ok because we already checked for pointer size (32 or 64 bit) above
1459 let range = AllocRange { start: offset, size: Size::from_bytes(n) };
1461 let byte_str = alloc.inner().get_bytes(&self.tcx(), range).unwrap();
1463 p!(pretty_print_byte_str(byte_str));
1467 // Aggregates, printed as array/tuple/struct/variant construction syntax.
1469 // NB: the `has_param_types_or_consts` check ensures that we can use
1470 // the `destructure_const` query with an empty `ty::ParamEnv` without
1471 // introducing ICEs (e.g. via `layout_of`) from missing bounds.
1472 // E.g. `transmute([0usize; 2]): (u8, *mut T)` needs to know `T: Sized`
1473 // to be able to destructure the tuple into `(0u8, *mut T)
1475 // FIXME(eddyb) for `--emit=mir`/`-Z dump-mir`, we should provide the
1476 // correct `ty::ParamEnv` to allow printing *all* constant values.
1477 (_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) if !ty.has_param_types_or_consts() => {
1478 let Some(contents) = self.tcx().try_destructure_const(
1479 ty::ParamEnv::reveal_all()
1480 .and(self.tcx().mk_const(ty::ConstS { val: ty::ConstKind::Value(ct), ty })),
1482 // Fall back to debug pretty printing for invalid constants.
1483 p!(write("{:?}", ct));
1485 p!(": ", print(ty));
1490 let fields = contents.fields.iter().copied();
1494 p!("[", comma_sep(fields), "]");
1497 p!("(", comma_sep(fields));
1498 if contents.fields.len() == 1 {
1503 ty::Adt(def, _) if def.variants().is_empty() => {
1504 self = self.typed_value(
1506 write!(this, "unreachable()")?;
1509 |this| this.print_type(ty),
1513 ty::Adt(def, substs) => {
1515 contents.variant.expect("destructed const of adt without variant idx");
1516 let variant_def = &def.variant(variant_idx);
1517 p!(print_value_path(variant_def.def_id, substs));
1519 match variant_def.ctor_kind {
1520 CtorKind::Const => {}
1522 p!("(", comma_sep(fields), ")");
1524 CtorKind::Fictive => {
1526 let mut first = true;
1527 for (field_def, field) in iter::zip(&variant_def.fields, fields) {
1531 p!(write("{}: ", field_def.name), print(field));
1538 _ => unreachable!(),
1544 (ConstValue::Scalar(scalar), _) => {
1545 return self.pretty_print_const_scalar(scalar, ty, print_ty);
1548 // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
1549 // their fields instead of just dumping the memory.
1554 p!(write("{:?}", ct));
1556 p!(": ", print(ty));
1562 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
1563 pub struct FmtPrinter<'a, 'tcx>(Box<FmtPrinterData<'a, 'tcx>>);
1565 pub struct FmtPrinterData<'a, 'tcx> {
1571 pub print_alloc_ids: bool,
1573 used_region_names: FxHashSet<Symbol>,
1574 region_index: usize,
1575 binder_depth: usize,
1576 printed_type_count: usize,
1578 pub region_highlight_mode: RegionHighlightMode<'tcx>,
1580 pub ty_infer_name_resolver: Option<Box<dyn Fn(ty::TyVid) -> Option<String> + 'a>>,
1581 pub const_infer_name_resolver: Option<Box<dyn Fn(ty::ConstVid<'tcx>) -> Option<String> + 'a>>,
1584 impl<'a, 'tcx> Deref for FmtPrinter<'a, 'tcx> {
1585 type Target = FmtPrinterData<'a, 'tcx>;
1586 fn deref(&self) -> &Self::Target {
1591 impl DerefMut for FmtPrinter<'_, '_> {
1592 fn deref_mut(&mut self) -> &mut Self::Target {
1597 impl<'a, 'tcx> FmtPrinter<'a, 'tcx> {
1598 pub fn new(tcx: TyCtxt<'tcx>, ns: Namespace) -> Self {
1599 FmtPrinter(Box::new(FmtPrinterData {
1601 // Estimated reasonable capacity to allocate upfront based on a few
1603 fmt: String::with_capacity(64),
1605 in_value: ns == Namespace::ValueNS,
1606 print_alloc_ids: false,
1607 used_region_names: Default::default(),
1610 printed_type_count: 0,
1611 region_highlight_mode: RegionHighlightMode::new(tcx),
1612 ty_infer_name_resolver: None,
1613 const_infer_name_resolver: None,
1617 pub fn into_buffer(self) -> String {
1622 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1623 // (but also some things just print a `DefId` generally so maybe we need this?)
1624 fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
1625 match tcx.def_key(def_id).disambiguated_data.data {
1626 DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::ImplTrait => {
1630 DefPathData::ValueNs(..)
1631 | DefPathData::AnonConst
1632 | DefPathData::ClosureExpr
1633 | DefPathData::Ctor => Namespace::ValueNS,
1635 DefPathData::MacroNs(..) => Namespace::MacroNS,
1637 _ => Namespace::TypeNS,
1641 impl<'t> TyCtxt<'t> {
1642 /// Returns a string identifying this `DefId`. This string is
1643 /// suitable for user output.
1644 pub fn def_path_str(self, def_id: DefId) -> String {
1645 self.def_path_str_with_substs(def_id, &[])
1648 pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1649 let ns = guess_def_namespace(self, def_id);
1650 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1651 FmtPrinter::new(self, ns).print_def_path(def_id, substs).unwrap().into_buffer()
1655 impl fmt::Write for FmtPrinter<'_, '_> {
1656 fn write_str(&mut self, s: &str) -> fmt::Result {
1657 self.fmt.push_str(s);
1662 impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> {
1663 type Error = fmt::Error;
1668 type DynExistential = Self;
1671 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
1678 substs: &'tcx [GenericArg<'tcx>],
1679 ) -> Result<Self::Path, Self::Error> {
1680 define_scoped_cx!(self);
1682 if substs.is_empty() {
1683 match self.try_print_trimmed_def_path(def_id)? {
1684 (cx, true) => return Ok(cx),
1685 (cx, false) => self = cx,
1688 match self.try_print_visible_def_path(def_id)? {
1689 (cx, true) => return Ok(cx),
1690 (cx, false) => self = cx,
1694 let key = self.tcx.def_key(def_id);
1695 if let DefPathData::Impl = key.disambiguated_data.data {
1696 // Always use types for non-local impls, where types are always
1697 // available, and filename/line-number is mostly uninteresting.
1698 let use_types = !def_id.is_local() || {
1699 // Otherwise, use filename/line-number if forced.
1700 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1705 // If no type info is available, fall back to
1706 // pretty printing some span information. This should
1707 // only occur very early in the compiler pipeline.
1708 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1709 let span = self.tcx.def_span(def_id);
1711 self = self.print_def_path(parent_def_id, &[])?;
1713 // HACK(eddyb) copy of `path_append` to avoid
1714 // constructing a `DisambiguatedDefPathData`.
1715 if !self.empty_path {
1716 write!(self, "::")?;
1721 // This may end up in stderr diagnostics but it may also be emitted
1722 // into MIR. Hence we use the remapped path if available
1723 self.tcx.sess.source_map().span_to_embeddable_string(span)
1725 self.empty_path = false;
1731 self.default_print_def_path(def_id, substs)
1734 fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
1735 self.pretty_print_region(region)
1738 fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1739 let type_length_limit = self.tcx.type_length_limit();
1740 if type_length_limit.value_within_limit(self.printed_type_count) {
1741 self.printed_type_count += 1;
1742 self.pretty_print_type(ty)
1744 write!(self, "...")?;
1749 fn print_dyn_existential(
1751 predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
1752 ) -> Result<Self::DynExistential, Self::Error> {
1753 self.pretty_print_dyn_existential(predicates)
1756 fn print_const(self, ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1757 self.pretty_print_const(ct, true)
1760 fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1761 self.empty_path = true;
1762 if cnum == LOCAL_CRATE {
1763 if self.tcx.sess.rust_2018() {
1764 // We add the `crate::` keyword on Rust 2018, only when desired.
1765 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1766 write!(self, "{}", kw::Crate)?;
1767 self.empty_path = false;
1771 write!(self, "{}", self.tcx.crate_name(cnum))?;
1772 self.empty_path = false;
1780 trait_ref: Option<ty::TraitRef<'tcx>>,
1781 ) -> Result<Self::Path, Self::Error> {
1782 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1783 self.empty_path = false;
1787 fn path_append_impl(
1789 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1790 _disambiguated_data: &DisambiguatedDefPathData,
1792 trait_ref: Option<ty::TraitRef<'tcx>>,
1793 ) -> Result<Self::Path, Self::Error> {
1794 self = self.pretty_path_append_impl(
1796 cx = print_prefix(cx)?;
1806 self.empty_path = false;
1812 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1813 disambiguated_data: &DisambiguatedDefPathData,
1814 ) -> Result<Self::Path, Self::Error> {
1815 self = print_prefix(self)?;
1817 // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
1818 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
1822 let name = disambiguated_data.data.name();
1823 if !self.empty_path {
1824 write!(self, "::")?;
1827 if let DefPathDataName::Named(name) = name {
1828 if Ident::with_dummy_span(name).is_raw_guess() {
1829 write!(self, "r#")?;
1833 let verbose = self.tcx.sess.verbose();
1834 disambiguated_data.fmt_maybe_verbose(&mut self, verbose)?;
1836 self.empty_path = false;
1841 fn path_generic_args(
1843 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1844 args: &[GenericArg<'tcx>],
1845 ) -> Result<Self::Path, Self::Error> {
1846 self = print_prefix(self)?;
1848 // Don't print `'_` if there's no unerased regions.
1849 let print_regions = self.tcx.sess.verbose()
1850 || args.iter().any(|arg| match arg.unpack() {
1851 GenericArgKind::Lifetime(r) => !r.is_erased(),
1854 let args = args.iter().cloned().filter(|arg| match arg.unpack() {
1855 GenericArgKind::Lifetime(_) => print_regions,
1859 if args.clone().next().is_some() {
1861 write!(self, "::")?;
1863 self.generic_delimiters(|cx| cx.comma_sep(args))
1870 impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> {
1871 fn ty_infer_name(&self, id: ty::TyVid) -> Option<String> {
1872 self.0.ty_infer_name_resolver.as_ref().and_then(|func| func(id))
1875 fn const_infer_name(&self, id: ty::ConstVid<'tcx>) -> Option<String> {
1876 self.0.const_infer_name_resolver.as_ref().and_then(|func| func(id))
1879 fn print_value_path(
1882 substs: &'tcx [GenericArg<'tcx>],
1883 ) -> Result<Self::Path, Self::Error> {
1884 let was_in_value = std::mem::replace(&mut self.in_value, true);
1885 self = self.print_def_path(def_id, substs)?;
1886 self.in_value = was_in_value;
1891 fn in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, Self::Error>
1893 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1895 self.pretty_in_binder(value)
1898 fn wrap_binder<T, C: Fn(&T, Self) -> Result<Self, Self::Error>>(
1900 value: &ty::Binder<'tcx, T>,
1902 ) -> Result<Self, Self::Error>
1904 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1906 self.pretty_wrap_binder(value, f)
1911 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1912 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
1914 ) -> Result<Self::Const, Self::Error> {
1915 self.write_str("{")?;
1917 self.write_str(conversion)?;
1918 let was_in_value = std::mem::replace(&mut self.in_value, false);
1920 self.in_value = was_in_value;
1921 self.write_str("}")?;
1925 fn generic_delimiters(
1927 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1928 ) -> Result<Self, Self::Error> {
1931 let was_in_value = std::mem::replace(&mut self.in_value, false);
1932 let mut inner = f(self)?;
1933 inner.in_value = was_in_value;
1935 write!(inner, ">")?;
1939 fn should_print_region(&self, region: ty::Region<'_>) -> bool {
1940 let highlight = self.region_highlight_mode;
1941 if highlight.region_highlighted(region).is_some() {
1945 if self.tcx.sess.verbose() {
1949 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1952 ty::ReEarlyBound(ref data) => {
1953 data.name != kw::Empty && data.name != kw::UnderscoreLifetime
1956 ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
1957 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1958 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1959 if let ty::BrNamed(_, name) = br {
1960 if name != kw::Empty && name != kw::UnderscoreLifetime {
1965 if let Some((region, _)) = highlight.highlight_bound_region {
1974 ty::ReVar(_) if identify_regions => true,
1976 ty::ReVar(_) | ty::ReErased => false,
1978 ty::ReStatic | ty::ReEmpty(_) => true,
1982 fn pretty_print_const_pointer<Tag: Provenance>(
1987 ) -> Result<Self::Const, Self::Error> {
1988 let print = |mut this: Self| {
1989 define_scoped_cx!(this);
1990 if this.print_alloc_ids {
1991 p!(write("{:?}", p));
1998 self.typed_value(print, |this| this.print_type(ty), ": ")
2005 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
2006 impl FmtPrinter<'_, '_> {
2007 pub fn pretty_print_region(mut self, region: ty::Region<'_>) -> Result<Self, fmt::Error> {
2008 define_scoped_cx!(self);
2010 // Watch out for region highlights.
2011 let highlight = self.region_highlight_mode;
2012 if let Some(n) = highlight.region_highlighted(region) {
2013 p!(write("'{}", n));
2017 if self.tcx.sess.verbose() {
2018 p!(write("{:?}", region));
2022 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
2024 // These printouts are concise. They do not contain all the information
2025 // the user might want to diagnose an error, but there is basically no way
2026 // to fit that into a short string. Hence the recommendation to use
2027 // `explain_region()` or `note_and_explain_region()`.
2029 ty::ReEarlyBound(ref data) => {
2030 if data.name != kw::Empty {
2031 p!(write("{}", data.name));
2035 ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
2036 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
2037 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
2038 if let ty::BrNamed(_, name) = br {
2039 if name != kw::Empty && name != kw::UnderscoreLifetime {
2040 p!(write("{}", name));
2045 if let Some((region, counter)) = highlight.highlight_bound_region {
2047 p!(write("'{}", counter));
2052 ty::ReVar(region_vid) if identify_regions => {
2053 p!(write("{:?}", region_vid));
2062 ty::ReEmpty(ty::UniverseIndex::ROOT) => {
2066 ty::ReEmpty(ui) => {
2067 p!(write("'<empty:{:?}>", ui));
2078 /// Folds through bound vars and placeholders, naming them
2079 struct RegionFolder<'a, 'tcx> {
2081 current_index: ty::DebruijnIndex,
2082 region_map: BTreeMap<ty::BoundRegion, ty::Region<'tcx>>,
2083 name: &'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a),
2086 impl<'a, 'tcx> ty::TypeFolder<'tcx> for RegionFolder<'a, 'tcx> {
2087 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
2091 fn fold_binder<T: TypeFoldable<'tcx>>(
2093 t: ty::Binder<'tcx, T>,
2094 ) -> ty::Binder<'tcx, T> {
2095 self.current_index.shift_in(1);
2096 let t = t.super_fold_with(self);
2097 self.current_index.shift_out(1);
2101 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
2103 _ if t.has_vars_bound_at_or_above(self.current_index) || t.has_placeholders() => {
2104 return t.super_fold_with(self);
2111 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
2112 let name = &mut self.name;
2113 let region = match *r {
2114 ty::ReLateBound(_, br) => *self.region_map.entry(br).or_insert_with(|| name(br)),
2115 ty::RePlaceholder(ty::PlaceholderRegion { name: kind, .. }) => {
2116 // If this is an anonymous placeholder, don't rename. Otherwise, in some
2117 // async fns, we get a `for<'r> Send` bound
2119 ty::BrAnon(_) | ty::BrEnv => r,
2121 // Index doesn't matter, since this is just for naming and these never get bound
2122 let br = ty::BoundRegion { var: ty::BoundVar::from_u32(0), kind };
2123 *self.region_map.entry(br).or_insert_with(|| name(br))
2129 if let ty::ReLateBound(debruijn1, br) = *region {
2130 assert_eq!(debruijn1, ty::INNERMOST);
2131 self.tcx.mk_region(ty::ReLateBound(self.current_index, br))
2138 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
2139 // `region_index` and `used_region_names`.
2140 impl<'tcx> FmtPrinter<'_, 'tcx> {
2141 pub fn name_all_regions<T>(
2143 value: &ty::Binder<'tcx, T>,
2144 ) -> Result<(Self, T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>), fmt::Error>
2146 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2148 fn name_by_region_index(index: usize) -> Symbol {
2150 0 => Symbol::intern("'r"),
2151 1 => Symbol::intern("'s"),
2152 i => Symbol::intern(&format!("'t{}", i - 2)),
2156 // Replace any anonymous late-bound regions with named
2157 // variants, using new unique identifiers, so that we can
2158 // clearly differentiate between named and unnamed regions in
2159 // the output. We'll probably want to tweak this over time to
2160 // decide just how much information to give.
2161 if self.binder_depth == 0 {
2162 self.prepare_late_bound_region_info(value);
2165 let mut empty = true;
2166 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
2173 let _ = write!(cx, "{}", w);
2175 let do_continue = |cx: &mut Self, cont: Symbol| {
2176 let _ = write!(cx, "{}", cont);
2179 define_scoped_cx!(self);
2181 let mut region_index = self.region_index;
2182 // If we want to print verbosely, then print *all* binders, even if they
2183 // aren't named. Eventually, we might just want this as the default, but
2184 // this is not *quite* right and changes the ordering of some output
2186 let (new_value, map) = if self.tcx().sess.verbose() {
2187 // anon index + 1 (BrEnv takes 0) -> name
2188 let mut region_map: BTreeMap<u32, Symbol> = BTreeMap::default();
2189 let bound_vars = value.bound_vars();
2190 for var in bound_vars {
2192 ty::BoundVariableKind::Region(ty::BrNamed(_, name)) => {
2193 start_or_continue(&mut self, "for<", ", ");
2194 do_continue(&mut self, name);
2196 ty::BoundVariableKind::Region(ty::BrAnon(i)) => {
2197 start_or_continue(&mut self, "for<", ", ");
2199 let name = name_by_region_index(region_index);
2201 if !self.used_region_names.contains(&name) {
2205 do_continue(&mut self, name);
2206 region_map.insert(i + 1, name);
2208 ty::BoundVariableKind::Region(ty::BrEnv) => {
2209 start_or_continue(&mut self, "for<", ", ");
2211 let name = name_by_region_index(region_index);
2213 if !self.used_region_names.contains(&name) {
2217 do_continue(&mut self, name);
2218 region_map.insert(0, name);
2223 start_or_continue(&mut self, "", "> ");
2225 self.tcx.replace_late_bound_regions(value.clone(), |br| {
2226 let kind = match br.kind {
2227 ty::BrNamed(_, _) => br.kind,
2229 let name = region_map[&(i + 1)];
2230 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
2233 let name = region_map[&0];
2234 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
2237 self.tcx.mk_region(ty::ReLateBound(
2239 ty::BoundRegion { var: br.var, kind },
2244 let mut name = |br: ty::BoundRegion| {
2245 start_or_continue(&mut self, "for<", ", ");
2246 let kind = match br.kind {
2247 ty::BrNamed(_, name) => {
2248 do_continue(&mut self, name);
2251 ty::BrAnon(_) | ty::BrEnv => {
2253 let name = name_by_region_index(region_index);
2255 if !self.used_region_names.contains(&name) {
2259 do_continue(&mut self, name);
2260 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
2263 tcx.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BoundRegion { var: br.var, kind }))
2265 let mut folder = RegionFolder {
2267 current_index: ty::INNERMOST,
2269 region_map: BTreeMap::new(),
2271 let new_value = value.clone().skip_binder().fold_with(&mut folder);
2272 let region_map = folder.region_map;
2273 start_or_continue(&mut self, "", "> ");
2274 (new_value, region_map)
2277 self.binder_depth += 1;
2278 self.region_index = region_index;
2279 Ok((self, new_value, map))
2282 pub fn pretty_in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, fmt::Error>
2284 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2286 let old_region_index = self.region_index;
2287 let (new, new_value, _) = self.name_all_regions(value)?;
2288 let mut inner = new_value.print(new)?;
2289 inner.region_index = old_region_index;
2290 inner.binder_depth -= 1;
2294 pub fn pretty_wrap_binder<T, C: Fn(&T, Self) -> Result<Self, fmt::Error>>(
2296 value: &ty::Binder<'tcx, T>,
2298 ) -> Result<Self, fmt::Error>
2300 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2302 let old_region_index = self.region_index;
2303 let (new, new_value, _) = self.name_all_regions(value)?;
2304 let mut inner = f(&new_value, new)?;
2305 inner.region_index = old_region_index;
2306 inner.binder_depth -= 1;
2310 #[instrument(skip(self), level = "debug")]
2311 fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<'tcx, T>)
2313 T: TypeFoldable<'tcx>,
2315 struct LateBoundRegionNameCollector<'a, 'tcx> {
2316 used_region_names: &'a mut FxHashSet<Symbol>,
2317 type_collector: SsoHashSet<Ty<'tcx>>,
2320 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_, 'tcx> {
2323 #[instrument(skip(self), level = "trace")]
2324 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
2325 trace!("address: {:p}", r.0.0);
2326 if let ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name), .. }) = *r {
2327 self.used_region_names.insert(name);
2328 } else if let ty::RePlaceholder(ty::PlaceholderRegion {
2329 name: ty::BrNamed(_, name),
2333 self.used_region_names.insert(name);
2335 r.super_visit_with(self)
2338 // We collect types in order to prevent really large types from compiling for
2339 // a really long time. See issue #83150 for why this is necessary.
2340 #[instrument(skip(self), level = "trace")]
2341 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
2342 let not_previously_inserted = self.type_collector.insert(ty);
2343 if not_previously_inserted {
2344 ty.super_visit_with(self)
2346 ControlFlow::CONTINUE
2351 self.used_region_names.clear();
2352 let mut collector = LateBoundRegionNameCollector {
2353 used_region_names: &mut self.used_region_names,
2354 type_collector: SsoHashSet::new(),
2356 value.visit_with(&mut collector);
2357 self.region_index = 0;
2361 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<'tcx, T>
2363 T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
2366 type Error = P::Error;
2367 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
2372 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
2374 T: Print<'tcx, P, Output = P, Error = P::Error>,
2375 U: Print<'tcx, P, Output = P, Error = P::Error>,
2378 type Error = P::Error;
2379 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
2380 define_scoped_cx!(cx);
2381 p!(print(self.0), ": ", print(self.1));
2386 macro_rules! forward_display_to_print {
2388 // Some of the $ty arguments may not actually use 'tcx
2389 $(#[allow(unused_lifetimes)] impl<'tcx> fmt::Display for $ty {
2390 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2391 ty::tls::with(|tcx| {
2392 let cx = tcx.lift(*self)
2393 .expect("could not lift for printing")
2394 .print(FmtPrinter::new(tcx, Namespace::TypeNS))?;
2395 f.write_str(&cx.into_buffer())?;
2403 macro_rules! define_print_and_forward_display {
2404 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
2405 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
2407 type Error = fmt::Error;
2408 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
2409 #[allow(unused_mut)]
2411 define_scoped_cx!($cx);
2413 #[allow(unreachable_code)]
2418 forward_display_to_print!($($ty),+);
2422 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
2423 impl<'tcx> fmt::Display for ty::Region<'tcx> {
2424 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2425 ty::tls::with(|tcx| {
2426 f.write_str(&self.print(FmtPrinter::new(tcx, Namespace::TypeNS))?.into_buffer())
2431 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2432 /// the trait path. That is, it will print `Trait<U>` instead of
2433 /// `<T as Trait<U>>`.
2434 #[derive(Copy, Clone, TypeFoldable, Lift)]
2435 pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
2437 impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
2438 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2439 fmt::Display::fmt(self, f)
2443 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2444 /// the trait name. That is, it will print `Trait` instead of
2445 /// `<T as Trait<U>>`.
2446 #[derive(Copy, Clone, TypeFoldable, Lift)]
2447 pub struct TraitRefPrintOnlyTraitName<'tcx>(ty::TraitRef<'tcx>);
2449 impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitName<'tcx> {
2450 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2451 fmt::Display::fmt(self, f)
2455 impl<'tcx> ty::TraitRef<'tcx> {
2456 pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
2457 TraitRefPrintOnlyTraitPath(self)
2460 pub fn print_only_trait_name(self) -> TraitRefPrintOnlyTraitName<'tcx> {
2461 TraitRefPrintOnlyTraitName(self)
2465 impl<'tcx> ty::Binder<'tcx, ty::TraitRef<'tcx>> {
2466 pub fn print_only_trait_path(self) -> ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>> {
2467 self.map_bound(|tr| tr.print_only_trait_path())
2471 #[derive(Copy, Clone, TypeFoldable, Lift)]
2472 pub struct TraitPredPrintModifiersAndPath<'tcx>(ty::TraitPredicate<'tcx>);
2474 impl<'tcx> fmt::Debug for TraitPredPrintModifiersAndPath<'tcx> {
2475 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2476 fmt::Display::fmt(self, f)
2480 impl<'tcx> ty::TraitPredicate<'tcx> {
2481 pub fn print_modifiers_and_trait_path(self) -> TraitPredPrintModifiersAndPath<'tcx> {
2482 TraitPredPrintModifiersAndPath(self)
2486 impl<'tcx> ty::PolyTraitPredicate<'tcx> {
2487 pub fn print_modifiers_and_trait_path(
2489 ) -> ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>> {
2490 self.map_bound(TraitPredPrintModifiersAndPath)
2494 forward_display_to_print! {
2496 &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
2499 // HACK(eddyb) these are exhaustive instead of generic,
2500 // because `for<'tcx>` isn't possible yet.
2501 ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>,
2502 ty::Binder<'tcx, ty::TraitRef<'tcx>>,
2503 ty::Binder<'tcx, ty::ExistentialTraitRef<'tcx>>,
2504 ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>>,
2505 ty::Binder<'tcx, TraitRefPrintOnlyTraitName<'tcx>>,
2506 ty::Binder<'tcx, ty::FnSig<'tcx>>,
2507 ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2508 ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>>,
2509 ty::Binder<'tcx, ty::SubtypePredicate<'tcx>>,
2510 ty::Binder<'tcx, ty::ProjectionPredicate<'tcx>>,
2511 ty::Binder<'tcx, ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
2512 ty::Binder<'tcx, ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
2514 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
2515 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
2518 define_print_and_forward_display! {
2521 &'tcx ty::List<Ty<'tcx>> {
2522 p!("{{", comma_sep(self.iter()), "}}")
2525 ty::TypeAndMut<'tcx> {
2526 p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
2529 ty::ExistentialTraitRef<'tcx> {
2530 // Use a type that can't appear in defaults of type parameters.
2531 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
2532 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
2533 p!(print(trait_ref.print_only_trait_path()))
2536 ty::ExistentialProjection<'tcx> {
2537 let name = cx.tcx().associated_item(self.item_def_id).name;
2538 p!(write("{} = ", name), print(self.term))
2541 ty::ExistentialPredicate<'tcx> {
2543 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
2544 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
2545 ty::ExistentialPredicate::AutoTrait(def_id) => {
2546 p!(print_def_path(def_id, &[]));
2552 p!(write("{}", self.unsafety.prefix_str()));
2554 if self.abi != Abi::Rust {
2555 p!(write("extern {} ", self.abi));
2558 p!("fn", pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
2561 ty::TraitRef<'tcx> {
2562 p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
2565 TraitRefPrintOnlyTraitPath<'tcx> {
2566 p!(print_def_path(self.0.def_id, self.0.substs));
2569 TraitRefPrintOnlyTraitName<'tcx> {
2570 p!(print_def_path(self.0.def_id, &[]));
2573 TraitPredPrintModifiersAndPath<'tcx> {
2574 if let ty::BoundConstness::ConstIfConst = self.0.constness {
2578 if let ty::ImplPolarity::Negative = self.0.polarity {
2582 p!(print(self.0.trait_ref.print_only_trait_path()));
2586 p!(write("{}", self.name))
2590 p!(write("{}", self.name))
2593 ty::SubtypePredicate<'tcx> {
2594 p!(print(self.a), " <: ", print(self.b))
2597 ty::CoercePredicate<'tcx> {
2598 p!(print(self.a), " -> ", print(self.b))
2601 ty::TraitPredicate<'tcx> {
2602 p!(print(self.trait_ref.self_ty()), ": ");
2603 if let ty::BoundConstness::ConstIfConst = self.constness {
2606 p!(print(self.trait_ref.print_only_trait_path()))
2609 ty::ProjectionPredicate<'tcx> {
2610 p!(print(self.projection_ty), " == ", print(self.term))
2615 ty::Term::Ty(ty) => p!(print(ty)),
2616 ty::Term::Const(c) => p!(print(c)),
2620 ty::ProjectionTy<'tcx> {
2621 p!(print_def_path(self.item_def_id, self.substs));
2626 ty::ClosureKind::Fn => p!("Fn"),
2627 ty::ClosureKind::FnMut => p!("FnMut"),
2628 ty::ClosureKind::FnOnce => p!("FnOnce"),
2632 ty::Predicate<'tcx> {
2633 let binder = self.kind();
2637 ty::PredicateKind<'tcx> {
2639 ty::PredicateKind::Trait(ref data) => {
2642 ty::PredicateKind::Subtype(predicate) => p!(print(predicate)),
2643 ty::PredicateKind::Coerce(predicate) => p!(print(predicate)),
2644 ty::PredicateKind::RegionOutlives(predicate) => p!(print(predicate)),
2645 ty::PredicateKind::TypeOutlives(predicate) => p!(print(predicate)),
2646 ty::PredicateKind::Projection(predicate) => p!(print(predicate)),
2647 ty::PredicateKind::WellFormed(arg) => p!(print(arg), " well-formed"),
2648 ty::PredicateKind::ObjectSafe(trait_def_id) => {
2649 p!("the trait `", print_def_path(trait_def_id, &[]), "` is object-safe")
2651 ty::PredicateKind::ClosureKind(closure_def_id, _closure_substs, kind) => {
2653 print_value_path(closure_def_id, &[]),
2654 write("` implements the trait `{}`", kind))
2656 ty::PredicateKind::ConstEvaluatable(uv) => {
2657 p!("the constant `", print_value_path(uv.def.did, uv.substs), "` can be evaluated")
2659 ty::PredicateKind::ConstEquate(c1, c2) => {
2660 p!("the constant `", print(c1), "` equals `", print(c2), "`")
2662 ty::PredicateKind::TypeWellFormedFromEnv(ty) => {
2663 p!("the type `", print(ty), "` is found in the environment")
2669 match self.unpack() {
2670 GenericArgKind::Lifetime(lt) => p!(print(lt)),
2671 GenericArgKind::Type(ty) => p!(print(ty)),
2672 GenericArgKind::Const(ct) => p!(print(ct)),
2677 fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
2678 // Iterate all local crate items no matter where they are defined.
2679 let hir = tcx.hir();
2680 for id in hir.items() {
2681 if matches!(hir.def_kind(id.def_id), DefKind::Use) {
2685 let item = hir.item(id);
2686 if item.ident.name == kw::Empty {
2690 let def_id = item.def_id.to_def_id();
2691 let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
2692 collect_fn(&item.ident, ns, def_id);
2695 // Now take care of extern crate items.
2696 let queue = &mut Vec::new();
2697 let mut seen_defs: DefIdSet = Default::default();
2699 for &cnum in tcx.crates(()).iter() {
2700 let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
2702 // Ignore crates that are not direct dependencies.
2703 match tcx.extern_crate(def_id) {
2705 Some(extern_crate) => {
2706 if !extern_crate.is_direct() {
2715 // Iterate external crate defs but be mindful about visibility
2716 while let Some(def) = queue.pop() {
2717 for child in tcx.module_children(def).iter() {
2718 if !child.vis.is_public() {
2723 def::Res::Def(DefKind::AssocTy, _) => {}
2724 def::Res::Def(DefKind::TyAlias, _) => {}
2725 def::Res::Def(defkind, def_id) => {
2726 if let Some(ns) = defkind.ns() {
2727 collect_fn(&child.ident, ns, def_id);
2730 if matches!(defkind, DefKind::Mod | DefKind::Enum | DefKind::Trait)
2731 && seen_defs.insert(def_id)
2742 /// The purpose of this function is to collect public symbols names that are unique across all
2743 /// crates in the build. Later, when printing about types we can use those names instead of the
2744 /// full exported path to them.
2746 /// So essentially, if a symbol name can only be imported from one place for a type, and as
2747 /// long as it was not glob-imported anywhere in the current crate, we can trim its printed
2748 /// path and print only the name.
2750 /// This has wide implications on error messages with types, for example, shortening
2751 /// `std::vec::Vec` to just `Vec`, as long as there is no other `Vec` importable anywhere.
2753 /// The implementation uses similar import discovery logic to that of 'use' suggestions.
2754 fn trimmed_def_paths(tcx: TyCtxt<'_>, (): ()) -> FxHashMap<DefId, Symbol> {
2755 let mut map: FxHashMap<DefId, Symbol> = FxHashMap::default();
2757 if let TrimmedDefPaths::GoodPath = tcx.sess.opts.trimmed_def_paths {
2758 // For good paths causing this bug, the `rustc_middle::ty::print::with_no_trimmed_paths`
2759 // wrapper can be used to suppress this query, in exchange for full paths being formatted.
2760 tcx.sess.delay_good_path_bug("trimmed_def_paths constructed");
2763 let unique_symbols_rev: &mut FxHashMap<(Namespace, Symbol), Option<DefId>> =
2764 &mut FxHashMap::default();
2766 for symbol_set in tcx.resolutions(()).glob_map.values() {
2767 for symbol in symbol_set {
2768 unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
2769 unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
2770 unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
2774 for_each_def(tcx, |ident, ns, def_id| {
2775 use std::collections::hash_map::Entry::{Occupied, Vacant};
2777 match unique_symbols_rev.entry((ns, ident.name)) {
2778 Occupied(mut v) => match v.get() {
2781 if *existing != def_id {
2787 v.insert(Some(def_id));
2792 for ((_, symbol), opt_def_id) in unique_symbols_rev.drain() {
2793 use std::collections::hash_map::Entry::{Occupied, Vacant};
2795 if let Some(def_id) = opt_def_id {
2796 match map.entry(def_id) {
2797 Occupied(mut v) => {
2798 // A single DefId can be known under multiple names (e.g.,
2799 // with a `pub use ... as ...;`). We need to ensure that the
2800 // name placed in this map is chosen deterministically, so
2801 // if we find multiple names (`symbol`) resolving to the
2802 // same `def_id`, we prefer the lexicographically smallest
2805 // Any stable ordering would be fine here though.
2806 if *v.get() != symbol {
2807 if v.get().as_str() > symbol.as_str() {
2822 pub fn provide(providers: &mut ty::query::Providers) {
2823 *providers = ty::query::Providers { trimmed_def_paths, ..*providers };
2827 pub struct OpaqueFnEntry<'tcx> {
2828 // The trait ref is already stored as a key, so just track if we have it as a real predicate
2830 fn_mut_trait_ref: Option<ty::PolyTraitRef<'tcx>>,
2831 fn_trait_ref: Option<ty::PolyTraitRef<'tcx>>,
2832 return_ty: Option<ty::Binder<'tcx, Term<'tcx>>>,