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::intern::Interned;
7 use rustc_data_structures::sso::SsoHashSet;
9 use rustc_hir::def::{self, CtorKind, DefKind, Namespace};
10 use rustc_hir::def_id::{DefId, DefIdSet, CRATE_DEF_INDEX, LOCAL_CRATE};
11 use rustc_hir::definitions::{DefPathData, DefPathDataName, DisambiguatedDefPathData};
12 use rustc_hir::ItemKind;
13 use rustc_session::config::TrimmedDefPaths;
14 use rustc_session::cstore::{ExternCrate, ExternCrateSource};
15 use rustc_span::symbol::{kw, Ident, Symbol};
16 use rustc_target::abi::Size;
17 use rustc_target::spec::abi::Abi;
21 use std::collections::BTreeMap;
22 use std::convert::TryFrom;
23 use std::fmt::{self, Write as _};
25 use std::ops::{ControlFlow, Deref, DerefMut};
27 // `pretty` is a separate module only for organization.
32 write!(scoped_cx!(), $lit)?
34 (@write($($data:expr),+)) => {
35 write!(scoped_cx!(), $($data),+)?
37 (@print($x:expr)) => {
38 scoped_cx!() = $x.print(scoped_cx!())?
40 (@$method:ident($($arg:expr),*)) => {
41 scoped_cx!() = scoped_cx!().$method($($arg),*)?
43 ($($elem:tt $(($($args:tt)*))?),+) => {{
44 $(p!(@ $elem $(($($args)*))?);)+
47 macro_rules! define_scoped_cx {
49 #[allow(unused_macros)]
50 macro_rules! scoped_cx {
59 static FORCE_IMPL_FILENAME_LINE: Cell<bool> = const { Cell::new(false) };
60 static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = const { Cell::new(false) };
61 static NO_TRIMMED_PATH: Cell<bool> = const { Cell::new(false) };
62 static NO_QUERIES: Cell<bool> = const { Cell::new(false) };
63 static NO_VISIBLE_PATH: Cell<bool> = const { Cell::new(false) };
66 macro_rules! define_helper {
67 ($($(#[$a:meta])* fn $name:ident($helper:ident, $tl:ident);)+) => {
70 pub struct $helper(bool);
73 pub fn new() -> $helper {
74 $helper($tl.with(|c| c.replace(true)))
79 pub macro $name($e:expr) {
81 let _guard = $helper::new();
86 impl Drop for $helper {
88 $tl.with(|c| c.set(self.0))
96 /// Avoids running any queries during any prints that occur
97 /// during the closure. This may alter the appearance of some
98 /// types (e.g. forcing verbose printing for opaque types).
99 /// This method is used during some queries (e.g. `explicit_item_bounds`
100 /// for opaque types), to ensure that any debug printing that
101 /// occurs during the query computation does not end up recursively
102 /// calling the same query.
103 fn with_no_queries(NoQueriesGuard, NO_QUERIES);
104 /// Force us to name impls with just the filename/line number. We
105 /// normally try to use types. But at some points, notably while printing
106 /// cycle errors, this can result in extra or suboptimal error output,
107 /// so this variable disables that check.
108 fn with_forced_impl_filename_line(ForcedImplGuard, FORCE_IMPL_FILENAME_LINE);
109 /// Adds the `crate::` prefix to paths where appropriate.
110 fn with_crate_prefix(CratePrefixGuard, SHOULD_PREFIX_WITH_CRATE);
111 /// Prevent path trimming if it is turned on. Path trimming affects `Display` impl
112 /// of various rustc types, for example `std::vec::Vec` would be trimmed to `Vec`,
113 /// if no other `Vec` is found.
114 fn with_no_trimmed_paths(NoTrimmedGuard, NO_TRIMMED_PATH);
115 /// Prevent selection of visible paths. `Display` impl of DefId will prefer
116 /// visible (public) reexports of types as paths.
117 fn with_no_visible_paths(NoVisibleGuard, NO_VISIBLE_PATH);
120 /// The "region highlights" are used to control region printing during
121 /// specific error messages. When a "region highlight" is enabled, it
122 /// gives an alternate way to print specific regions. For now, we
123 /// always print those regions using a number, so something like "`'0`".
125 /// Regions not selected by the region highlight mode are presently
127 #[derive(Copy, Clone)]
128 pub struct RegionHighlightMode<'tcx> {
131 /// If enabled, when we see the selected region, use "`'N`"
132 /// instead of the ordinary behavior.
133 highlight_regions: [Option<(ty::Region<'tcx>, usize)>; 3],
135 /// If enabled, when printing a "free region" that originated from
136 /// the given `ty::BoundRegionKind`, print it as "`'1`". Free regions that would ordinarily
137 /// have names print as normal.
139 /// This is used when you have a signature like `fn foo(x: &u32,
140 /// y: &'a u32)` and we want to give a name to the region of the
142 highlight_bound_region: Option<(ty::BoundRegionKind, usize)>,
145 impl<'tcx> RegionHighlightMode<'tcx> {
146 pub fn new(tcx: TyCtxt<'tcx>) -> Self {
149 highlight_regions: Default::default(),
150 highlight_bound_region: Default::default(),
154 /// If `region` and `number` are both `Some`, invokes
155 /// `highlighting_region`.
156 pub fn maybe_highlighting_region(
158 region: Option<ty::Region<'tcx>>,
159 number: Option<usize>,
161 if let Some(k) = region {
162 if let Some(n) = number {
163 self.highlighting_region(k, n);
168 /// Highlights the region inference variable `vid` as `'N`.
169 pub fn highlighting_region(&mut self, region: ty::Region<'tcx>, number: usize) {
170 let num_slots = self.highlight_regions.len();
171 let first_avail_slot =
172 self.highlight_regions.iter_mut().find(|s| s.is_none()).unwrap_or_else(|| {
173 bug!("can only highlight {} placeholders at a time", num_slots,)
175 *first_avail_slot = Some((region, number));
178 /// Convenience wrapper for `highlighting_region`.
179 pub fn highlighting_region_vid(&mut self, vid: ty::RegionVid, number: usize) {
180 self.highlighting_region(self.tcx.mk_region(ty::ReVar(vid)), number)
183 /// Returns `Some(n)` with the number to use for the given region, if any.
184 fn region_highlighted(&self, region: ty::Region<'_>) -> Option<usize> {
185 self.highlight_regions.iter().find_map(|h| match h {
186 Some((r, n)) if *r == region => Some(*n),
191 /// Highlight the given bound region.
192 /// We can only highlight one bound region at a time. See
193 /// the field `highlight_bound_region` for more detailed notes.
194 pub fn highlighting_bound_region(&mut self, br: ty::BoundRegionKind, number: usize) {
195 assert!(self.highlight_bound_region.is_none());
196 self.highlight_bound_region = Some((br, number));
200 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
201 pub trait PrettyPrinter<'tcx>:
208 DynExistential = Self,
212 /// Like `print_def_path` but for value paths.
216 substs: &'tcx [GenericArg<'tcx>],
217 ) -> Result<Self::Path, Self::Error> {
218 self.print_def_path(def_id, substs)
221 fn in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, Self::Error>
223 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
225 value.as_ref().skip_binder().print(self)
228 fn wrap_binder<T, F: Fn(&T, Self) -> Result<Self, fmt::Error>>(
230 value: &ty::Binder<'tcx, T>,
232 ) -> Result<Self, Self::Error>
234 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
236 f(value.as_ref().skip_binder(), self)
239 /// Prints comma-separated elements.
240 fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
242 T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
244 if let Some(first) = elems.next() {
245 self = first.print(self)?;
247 self.write_str(", ")?;
248 self = elem.print(self)?;
254 /// Prints `{f: t}` or `{f as t}` depending on the `cast` argument
257 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
258 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
260 ) -> Result<Self::Const, Self::Error> {
261 self.write_str("{")?;
263 self.write_str(conversion)?;
265 self.write_str("}")?;
269 /// Prints `<...>` around what `f` prints.
270 fn generic_delimiters(
272 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
273 ) -> Result<Self, Self::Error>;
275 /// Returns `true` if the region should be printed in
276 /// optional positions, e.g., `&'a T` or `dyn Tr + 'b`.
277 /// This is typically the case for all non-`'_` regions.
278 fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool;
280 // Defaults (should not be overridden):
282 /// If possible, this returns a global path resolving to `def_id` that is visible
283 /// from at least one local module, and returns `true`. If the crate defining `def_id` is
284 /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
285 fn try_print_visible_def_path(self, def_id: DefId) -> Result<(Self, bool), Self::Error> {
286 if NO_VISIBLE_PATH.with(|flag| flag.get()) {
287 return Ok((self, false));
290 let mut callers = Vec::new();
291 self.try_print_visible_def_path_recur(def_id, &mut callers)
294 /// Try to see if this path can be trimmed to a unique symbol name.
295 fn try_print_trimmed_def_path(
298 ) -> Result<(Self::Path, bool), Self::Error> {
299 if !self.tcx().sess.opts.debugging_opts.trim_diagnostic_paths
300 || matches!(self.tcx().sess.opts.trimmed_def_paths, TrimmedDefPaths::Never)
301 || NO_TRIMMED_PATH.with(|flag| flag.get())
302 || SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get())
304 return Ok((self, false));
307 match self.tcx().trimmed_def_paths(()).get(&def_id) {
308 None => Ok((self, false)),
310 self.write_str(symbol.as_str())?;
316 /// Does the work of `try_print_visible_def_path`, building the
317 /// full definition path recursively before attempting to
318 /// post-process it into the valid and visible version that
319 /// accounts for re-exports.
321 /// This method should only be called by itself or
322 /// `try_print_visible_def_path`.
324 /// `callers` is a chain of visible_parent's leading to `def_id`,
325 /// to support cycle detection during recursion.
327 /// This method returns false if we can't print the visible path, so
328 /// `print_def_path` can fall back on the item's real definition path.
329 fn try_print_visible_def_path_recur(
332 callers: &mut Vec<DefId>,
333 ) -> Result<(Self, bool), Self::Error> {
334 define_scoped_cx!(self);
336 debug!("try_print_visible_def_path: def_id={:?}", def_id);
338 // If `def_id` is a direct or injected extern crate, return the
339 // path to the crate followed by the path to the item within the crate.
340 if def_id.index == CRATE_DEF_INDEX {
341 let cnum = def_id.krate;
343 if cnum == LOCAL_CRATE {
344 return Ok((self.path_crate(cnum)?, true));
347 // In local mode, when we encounter a crate other than
348 // LOCAL_CRATE, execution proceeds in one of two ways:
350 // 1. For a direct dependency, where user added an
351 // `extern crate` manually, we put the `extern
352 // crate` as the parent. So you wind up with
353 // something relative to the current crate.
354 // 2. For an extern inferred from a path or an indirect crate,
355 // where there is no explicit `extern crate`, we just prepend
357 match self.tcx().extern_crate(def_id) {
358 Some(&ExternCrate { src, dependency_of, span, .. }) => match (src, dependency_of) {
359 (ExternCrateSource::Extern(def_id), LOCAL_CRATE) => {
360 // NOTE(eddyb) the only reason `span` might be dummy,
361 // that we're aware of, is that it's the `std`/`core`
362 // `extern crate` injected by default.
363 // FIXME(eddyb) find something better to key this on,
364 // or avoid ending up with `ExternCrateSource::Extern`,
365 // for the injected `std`/`core`.
367 return Ok((self.path_crate(cnum)?, true));
370 // Disable `try_print_trimmed_def_path` behavior within
371 // the `print_def_path` call, to avoid infinite recursion
372 // in cases where the `extern crate foo` has non-trivial
373 // parents, e.g. it's nested in `impl foo::Trait for Bar`
374 // (see also issues #55779 and #87932).
375 self = with_no_visible_paths!(self.print_def_path(def_id, &[])?);
377 return Ok((self, true));
379 (ExternCrateSource::Path, LOCAL_CRATE) => {
380 return Ok((self.path_crate(cnum)?, true));
385 return Ok((self.path_crate(cnum)?, true));
390 if def_id.is_local() {
391 return Ok((self, false));
394 let visible_parent_map = self.tcx().visible_parent_map(());
396 let mut cur_def_key = self.tcx().def_key(def_id);
397 debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
399 // For a constructor, we want the name of its parent rather than <unnamed>.
400 if let DefPathData::Ctor = cur_def_key.disambiguated_data.data {
405 .expect("`DefPathData::Ctor` / `VariantData` missing a parent"),
408 cur_def_key = self.tcx().def_key(parent);
411 let Some(visible_parent) = visible_parent_map.get(&def_id).cloned() else {
412 return Ok((self, false));
415 let actual_parent = self.tcx().parent(def_id);
417 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
418 visible_parent, actual_parent,
421 let mut data = cur_def_key.disambiguated_data.data;
423 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
424 data, visible_parent, actual_parent,
428 // In order to output a path that could actually be imported (valid and visible),
429 // we need to handle re-exports correctly.
431 // For example, take `std::os::unix::process::CommandExt`, this trait is actually
432 // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
434 // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is
435 // private so the "true" path to `CommandExt` isn't accessible.
437 // In this case, the `visible_parent_map` will look something like this:
439 // (child) -> (parent)
440 // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
441 // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
442 // `std::sys::unix::ext` -> `std::os`
444 // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
447 // When printing the path to `CommandExt` and looking at the `cur_def_key` that
448 // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
449 // to the parent - resulting in a mangled path like
450 // `std::os::ext::process::CommandExt`.
452 // Instead, we must detect that there was a re-export and instead print `unix`
453 // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
454 // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
455 // the visible parent (`std::os`). If these do not match, then we iterate over
456 // the children of the visible parent (as was done when computing
457 // `visible_parent_map`), looking for the specific child we currently have and then
458 // have access to the re-exported name.
459 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
460 // Item might be re-exported several times, but filter for the one
461 // that's public and whose identifier isn't `_`.
464 .module_children(visible_parent)
466 .filter(|child| child.res.opt_def_id() == Some(def_id))
467 .find(|child| child.vis.is_public() && child.ident.name != kw::Underscore)
468 .map(|child| child.ident.name);
470 if let Some(new_name) = reexport {
473 // There is no name that is public and isn't `_`, so bail.
474 return Ok((self, false));
477 // Re-exported `extern crate` (#43189).
478 DefPathData::CrateRoot => {
479 data = DefPathData::TypeNs(self.tcx().crate_name(def_id.krate));
483 debug!("try_print_visible_def_path: data={:?}", data);
485 if callers.contains(&visible_parent) {
486 return Ok((self, false));
488 callers.push(visible_parent);
489 // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
490 // knowing ahead of time whether the entire path will succeed or not.
491 // To support printers that do not implement `PrettyPrinter`, a `Vec` or
492 // linked list on the stack would need to be built, before any printing.
493 match self.try_print_visible_def_path_recur(visible_parent, callers)? {
494 (cx, false) => return Ok((cx, false)),
495 (cx, true) => self = cx,
499 Ok((self.path_append(Ok, &DisambiguatedDefPathData { data, disambiguator: 0 })?, true))
502 fn pretty_path_qualified(
505 trait_ref: Option<ty::TraitRef<'tcx>>,
506 ) -> Result<Self::Path, Self::Error> {
507 if trait_ref.is_none() {
508 // Inherent impls. Try to print `Foo::bar` for an inherent
509 // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
510 // anything other than a simple path.
511 match self_ty.kind() {
520 return self_ty.print(self);
527 self.generic_delimiters(|mut cx| {
528 define_scoped_cx!(cx);
531 if let Some(trait_ref) = trait_ref {
532 p!(" as ", print(trait_ref.print_only_trait_path()));
538 fn pretty_path_append_impl(
540 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
542 trait_ref: Option<ty::TraitRef<'tcx>>,
543 ) -> Result<Self::Path, Self::Error> {
544 self = print_prefix(self)?;
546 self.generic_delimiters(|mut cx| {
547 define_scoped_cx!(cx);
550 if let Some(trait_ref) = trait_ref {
551 p!(print(trait_ref.print_only_trait_path()), " for ");
559 fn pretty_print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
560 define_scoped_cx!(self);
563 ty::Bool => p!("bool"),
564 ty::Char => p!("char"),
565 ty::Int(t) => p!(write("{}", t.name_str())),
566 ty::Uint(t) => p!(write("{}", t.name_str())),
567 ty::Float(t) => p!(write("{}", t.name_str())),
568 ty::RawPtr(ref tm) => {
572 hir::Mutability::Mut => "mut",
573 hir::Mutability::Not => "const",
578 ty::Ref(r, ty, mutbl) => {
580 if self.region_should_not_be_omitted(r) {
583 p!(print(ty::TypeAndMut { ty, mutbl }))
585 ty::Never => p!("!"),
586 ty::Tuple(ref tys) => {
587 p!("(", comma_sep(tys.iter()));
593 ty::FnDef(def_id, substs) => {
594 let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs);
595 p!(print(sig), " {{", print_value_path(def_id, substs), "}}");
597 ty::FnPtr(ref bare_fn) => p!(print(bare_fn)),
598 ty::Infer(infer_ty) => {
599 let verbose = self.tcx().sess.verbose();
600 if let ty::TyVar(ty_vid) = infer_ty {
601 if let Some(name) = self.ty_infer_name(ty_vid) {
602 p!(write("{}", name))
605 p!(write("{:?}", infer_ty))
607 p!(write("{}", infer_ty))
611 if verbose { p!(write("{:?}", infer_ty)) } else { p!(write("{}", infer_ty)) }
614 ty::Error(_) => p!("[type error]"),
615 ty::Param(ref param_ty) => p!(write("{}", param_ty)),
616 ty::Bound(debruijn, bound_ty) => match bound_ty.kind {
617 ty::BoundTyKind::Anon => self.pretty_print_bound_var(debruijn, bound_ty.var)?,
618 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
620 ty::Adt(def, substs) => {
621 p!(print_def_path(def.did, substs));
623 ty::Dynamic(data, r) => {
624 let print_r = self.region_should_not_be_omitted(r);
628 p!("dyn ", print(data));
630 p!(" + ", print(r), ")");
633 ty::Foreign(def_id) => {
634 p!(print_def_path(def_id, &[]));
636 ty::Projection(ref data) => p!(print(data)),
637 ty::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
638 ty::Opaque(def_id, substs) => {
639 // FIXME(eddyb) print this with `print_def_path`.
640 // We use verbose printing in 'NO_QUERIES' mode, to
641 // avoid needing to call `predicates_of`. This should
642 // only affect certain debug messages (e.g. messages printed
643 // from `rustc_middle::ty` during the computation of `tcx.predicates_of`),
644 // and should have no effect on any compiler output.
645 if self.tcx().sess.verbose() || NO_QUERIES.with(|q| q.get()) {
646 p!(write("Opaque({:?}, {:?})", def_id, substs));
650 return with_no_queries!({
651 let def_key = self.tcx().def_key(def_id);
652 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
653 p!(write("{}", name));
654 // FIXME(eddyb) print this with `print_def_path`.
655 if !substs.is_empty() {
657 p!(generic_delimiters(|cx| cx.comma_sep(substs.iter())));
662 self.pretty_print_opaque_impl_type(def_id, substs)
665 ty::Str => p!("str"),
666 ty::Generator(did, substs, movability) => {
669 hir::Movability::Movable => {}
670 hir::Movability::Static => p!("static "),
673 if !self.tcx().sess.verbose() {
675 // FIXME(eddyb) should use `def_span`.
676 if let Some(did) = did.as_local() {
677 let span = self.tcx().def_span(did);
680 // This may end up in stderr diagnostics but it may also be emitted
681 // into MIR. Hence we use the remapped path if available
682 self.tcx().sess.source_map().span_to_embeddable_string(span)
685 p!(write("@"), print_def_path(did, substs));
688 p!(print_def_path(did, substs));
690 if !substs.as_generator().is_valid() {
693 self = self.comma_sep(substs.as_generator().upvar_tys())?;
697 if substs.as_generator().is_valid() {
698 p!(" ", print(substs.as_generator().witness()));
704 ty::GeneratorWitness(types) => {
705 p!(in_binder(&types));
707 ty::Closure(did, substs) => {
709 if !self.tcx().sess.verbose() {
710 p!(write("closure"));
711 // FIXME(eddyb) should use `def_span`.
712 if let Some(did) = did.as_local() {
713 if self.tcx().sess.opts.debugging_opts.span_free_formats {
714 p!("@", print_def_path(did.to_def_id(), substs));
716 let span = self.tcx().def_span(did);
719 // This may end up in stderr diagnostics but it may also be emitted
720 // into MIR. Hence we use the remapped path if available
721 self.tcx().sess.source_map().span_to_embeddable_string(span)
725 p!(write("@"), print_def_path(did, substs));
728 p!(print_def_path(did, substs));
729 if !substs.as_closure().is_valid() {
730 p!(" closure_substs=(unavailable)");
731 p!(write(" substs={:?}", substs));
733 p!(" closure_kind_ty=", print(substs.as_closure().kind_ty()));
735 " closure_sig_as_fn_ptr_ty=",
736 print(substs.as_closure().sig_as_fn_ptr_ty())
739 self = self.comma_sep(substs.as_closure().upvar_tys())?;
745 ty::Array(ty, sz) => {
746 p!("[", print(ty), "; ");
747 if self.tcx().sess.verbose() {
748 p!(write("{:?}", sz));
749 } else if let ty::ConstKind::Unevaluated(..) = sz.val() {
750 // Do not try to evaluate unevaluated constants. If we are const evaluating an
751 // array length anon const, rustc will (with debug assertions) print the
752 // constant's path. Which will end up here again.
754 } else if let Some(n) = sz.val().try_to_bits(self.tcx().data_layout.pointer_size) {
756 } else if let ty::ConstKind::Param(param) = sz.val() {
757 p!(write("{}", param));
763 ty::Slice(ty) => p!("[", print(ty), "]"),
769 fn pretty_print_opaque_impl_type(
772 substs: &'tcx ty::List<ty::GenericArg<'tcx>>,
773 ) -> Result<Self::Type, Self::Error> {
774 define_scoped_cx!(self);
776 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
777 // by looking up the projections associated with the def_id.
778 let bounds = self.tcx().explicit_item_bounds(def_id);
780 let mut traits = BTreeMap::new();
781 let mut fn_traits = BTreeMap::new();
782 let mut is_sized = false;
784 for (predicate, _) in bounds {
785 let predicate = predicate.subst(self.tcx(), substs);
786 let bound_predicate = predicate.kind();
788 match bound_predicate.skip_binder() {
789 ty::PredicateKind::Trait(pred) => {
790 let trait_ref = bound_predicate.rebind(pred.trait_ref);
792 // Don't print + Sized, but rather + ?Sized if absent.
793 if Some(trait_ref.def_id()) == self.tcx().lang_items().sized_trait() {
798 self.insert_trait_and_projection(trait_ref, None, &mut traits, &mut fn_traits);
800 ty::PredicateKind::Projection(pred) => {
801 let proj_ref = bound_predicate.rebind(pred);
802 let trait_ref = proj_ref.required_poly_trait_ref(self.tcx());
804 // Projection type entry -- the def-id for naming, and the ty.
805 let proj_ty = (proj_ref.projection_def_id(), proj_ref.term());
807 self.insert_trait_and_projection(
818 let mut first = true;
819 // Insert parenthesis around (Fn(A, B) -> C) if the opaque ty has more than one other trait
820 let paren_needed = fn_traits.len() > 1 || traits.len() > 0 || !is_sized;
824 for (fn_once_trait_ref, entry) in fn_traits {
825 // Get the (single) generic ty (the args) of this FnOnce trait ref.
826 let generics = self.generic_args_to_print(
827 self.tcx().generics_of(fn_once_trait_ref.def_id()),
828 fn_once_trait_ref.skip_binder().substs,
831 match (entry.return_ty, generics[0].expect_ty()) {
832 // We can only print `impl Fn() -> ()` if we have a tuple of args and we recorded
834 (Some(return_ty), arg_tys) if matches!(arg_tys.kind(), ty::Tuple(_)) => {
835 let name = if entry.fn_trait_ref.is_some() {
837 } else if entry.fn_mut_trait_ref.is_some() {
844 write("{}", if first { " " } else { " + " }),
845 write("{}{}(", if paren_needed { "(" } else { "" }, name)
848 for (idx, ty) in arg_tys.tuple_fields().enumerate() {
856 if let Term::Ty(ty) = return_ty.skip_binder() {
858 p!("-> ", print(return_ty));
861 p!(write("{}", if paren_needed { ")" } else { "" }));
865 // If we got here, we can't print as a `impl Fn(A, B) -> C`. Just record the
866 // trait_refs we collected in the OpaqueFnEntry as normal trait refs.
868 if entry.has_fn_once {
869 traits.entry(fn_once_trait_ref).or_default().extend(
870 // Group the return ty with its def id, if we had one.
873 .map(|ty| (self.tcx().lang_items().fn_once_output().unwrap(), ty)),
876 if let Some(trait_ref) = entry.fn_mut_trait_ref {
877 traits.entry(trait_ref).or_default();
879 if let Some(trait_ref) = entry.fn_trait_ref {
880 traits.entry(trait_ref).or_default();
886 // Print the rest of the trait types (that aren't Fn* family of traits)
887 for (trait_ref, assoc_items) in traits {
889 write("{}", if first { " " } else { " + " }),
890 print(trait_ref.skip_binder().print_only_trait_name())
893 let generics = self.generic_args_to_print(
894 self.tcx().generics_of(trait_ref.def_id()),
895 trait_ref.skip_binder().substs,
898 if !generics.is_empty() || !assoc_items.is_empty() {
900 let mut first = true;
906 p!(print(trait_ref.rebind(*ty)));
910 for (assoc_item_def_id, term) in assoc_items {
914 p!(write("{} = ", self.tcx().associated_item(assoc_item_def_id).name));
916 match term.skip_binder() {
918 // Skip printing `<[generator@] as Generator<_>>::Return` from async blocks
920 ty.kind(), ty::Projection(ty::ProjectionTy { item_def_id, .. })
921 if Some(*item_def_id) == self.tcx().lang_items().generator_return()
943 p!(write("{}?Sized", if first { " " } else { " + " }));
951 /// Insert the trait ref and optionally a projection type associated with it into either the
952 /// traits map or fn_traits map, depending on if the trait is in the Fn* family of traits.
953 fn insert_trait_and_projection(
955 trait_ref: ty::PolyTraitRef<'tcx>,
956 proj_ty: Option<(DefId, ty::Binder<'tcx, Term<'tcx>>)>,
957 traits: &mut BTreeMap<
958 ty::PolyTraitRef<'tcx>,
959 BTreeMap<DefId, ty::Binder<'tcx, Term<'tcx>>>,
961 fn_traits: &mut BTreeMap<ty::PolyTraitRef<'tcx>, OpaqueFnEntry<'tcx>>,
963 let trait_def_id = trait_ref.def_id();
965 // If our trait_ref is FnOnce or any of its children, project it onto the parent FnOnce
966 // super-trait ref and record it there.
967 if let Some(fn_once_trait) = self.tcx().lang_items().fn_once_trait() {
968 // If we have a FnOnce, then insert it into
969 if trait_def_id == fn_once_trait {
970 let entry = fn_traits.entry(trait_ref).or_default();
971 // Optionally insert the return_ty as well.
972 if let Some((_, ty)) = proj_ty {
973 entry.return_ty = Some(ty);
975 entry.has_fn_once = true;
977 } else if Some(trait_def_id) == self.tcx().lang_items().fn_mut_trait() {
978 let super_trait_ref = crate::traits::util::supertraits(self.tcx(), trait_ref)
979 .find(|super_trait_ref| super_trait_ref.def_id() == fn_once_trait)
982 fn_traits.entry(super_trait_ref).or_default().fn_mut_trait_ref = Some(trait_ref);
984 } else if Some(trait_def_id) == self.tcx().lang_items().fn_trait() {
985 let super_trait_ref = crate::traits::util::supertraits(self.tcx(), trait_ref)
986 .find(|super_trait_ref| super_trait_ref.def_id() == fn_once_trait)
989 fn_traits.entry(super_trait_ref).or_default().fn_trait_ref = Some(trait_ref);
994 // Otherwise, just group our traits and projection types.
995 traits.entry(trait_ref).or_default().extend(proj_ty);
998 fn pretty_print_bound_var(
1000 debruijn: ty::DebruijnIndex,
1002 ) -> Result<(), Self::Error> {
1003 if debruijn == ty::INNERMOST {
1004 write!(self, "^{}", var.index())
1006 write!(self, "^{}_{}", debruijn.index(), var.index())
1010 fn ty_infer_name(&self, _: ty::TyVid) -> Option<String> {
1014 fn const_infer_name(&self, _: ty::ConstVid<'tcx>) -> Option<String> {
1018 fn pretty_print_dyn_existential(
1020 predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
1021 ) -> Result<Self::DynExistential, Self::Error> {
1022 // Generate the main trait ref, including associated types.
1023 let mut first = true;
1025 if let Some(principal) = predicates.principal() {
1026 self = self.wrap_binder(&principal, |principal, mut cx| {
1027 define_scoped_cx!(cx);
1028 p!(print_def_path(principal.def_id, &[]));
1030 let mut resugared = false;
1032 // Special-case `Fn(...) -> ...` and resugar it.
1033 let fn_trait_kind = cx.tcx().fn_trait_kind_from_lang_item(principal.def_id);
1034 if !cx.tcx().sess.verbose() && fn_trait_kind.is_some() {
1035 if let ty::Tuple(ref args) = principal.substs.type_at(0).kind() {
1036 let mut projections = predicates.projection_bounds();
1037 if let (Some(proj), None) = (projections.next(), projections.next()) {
1038 let tys: Vec<_> = args.iter().map(|k| k.expect_ty()).collect();
1042 proj.skip_binder().term.ty().expect("Return type was a const")
1049 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
1050 // in order to place the projections inside the `<...>`.
1052 // Use a type that can't appear in defaults of type parameters.
1053 let dummy_cx = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1054 let principal = principal.with_self_ty(cx.tcx(), dummy_cx);
1056 let args = cx.generic_args_to_print(
1057 cx.tcx().generics_of(principal.def_id),
1061 // Don't print `'_` if there's no unerased regions.
1062 let print_regions = args.iter().any(|arg| match arg.unpack() {
1063 GenericArgKind::Lifetime(r) => !r.is_erased(),
1066 let mut args = args.iter().cloned().filter(|arg| match arg.unpack() {
1067 GenericArgKind::Lifetime(_) => print_regions,
1070 let mut projections = predicates.projection_bounds();
1072 let arg0 = args.next();
1073 let projection0 = projections.next();
1074 if arg0.is_some() || projection0.is_some() {
1075 let args = arg0.into_iter().chain(args);
1076 let projections = projection0.into_iter().chain(projections);
1078 p!(generic_delimiters(|mut cx| {
1079 cx = cx.comma_sep(args)?;
1080 if arg0.is_some() && projection0.is_some() {
1083 cx.comma_sep(projections)
1093 define_scoped_cx!(self);
1096 // FIXME(eddyb) avoid printing twice (needed to ensure
1097 // that the auto traits are sorted *and* printed via cx).
1098 let mut auto_traits: Vec<_> =
1099 predicates.auto_traits().map(|did| (self.tcx().def_path_str(did), did)).collect();
1101 // The auto traits come ordered by `DefPathHash`. While
1102 // `DefPathHash` is *stable* in the sense that it depends on
1103 // neither the host nor the phase of the moon, it depends
1104 // "pseudorandomly" on the compiler version and the target.
1106 // To avoid that causing instabilities in compiletest
1107 // output, sort the auto-traits alphabetically.
1110 for (_, def_id) in auto_traits {
1116 p!(print_def_path(def_id, &[]));
1124 inputs: &[Ty<'tcx>],
1127 ) -> Result<Self, Self::Error> {
1128 define_scoped_cx!(self);
1130 p!("(", comma_sep(inputs.iter().copied()));
1132 if !inputs.is_empty() {
1138 if !output.is_unit() {
1139 p!(" -> ", print(output));
1145 fn pretty_print_const(
1147 ct: ty::Const<'tcx>,
1149 ) -> Result<Self::Const, Self::Error> {
1150 define_scoped_cx!(self);
1152 if self.tcx().sess.verbose() {
1153 p!(write("Const({:?}: {:?})", ct.val(), ct.ty()));
1157 macro_rules! print_underscore {
1160 self = self.typed_value(
1165 |this| this.print_type(ct.ty()),
1175 ty::ConstKind::Unevaluated(ty::Unevaluated {
1178 promoted: Some(promoted),
1180 p!(print_value_path(def.did, substs));
1181 p!(write("::{:?}", promoted));
1183 ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted: None }) => {
1184 match self.tcx().def_kind(def.did) {
1185 DefKind::Static | DefKind::Const | DefKind::AssocConst => {
1186 p!(print_value_path(def.did, substs))
1190 let span = self.tcx().def_span(def.did);
1191 if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span) {
1192 p!(write("{}", snip))
1202 ty::ConstKind::Infer(infer_ct) => {
1204 ty::InferConst::Var(ct_vid)
1205 if let Some(name) = self.const_infer_name(ct_vid) =>
1206 p!(write("{}", name)),
1207 _ => print_underscore!(),
1210 ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)),
1211 ty::ConstKind::Value(value) => {
1212 return self.pretty_print_const_value(value, ct.ty(), print_ty);
1215 ty::ConstKind::Bound(debruijn, bound_var) => {
1216 self.pretty_print_bound_var(debruijn, bound_var)?
1218 ty::ConstKind::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
1219 ty::ConstKind::Error(_) => p!("[const error]"),
1224 fn pretty_print_const_scalar(
1229 ) -> Result<Self::Const, Self::Error> {
1231 Scalar::Ptr(ptr, _size) => self.pretty_print_const_scalar_ptr(ptr, ty, print_ty),
1232 Scalar::Int(int) => self.pretty_print_const_scalar_int(int, ty, print_ty),
1236 fn pretty_print_const_scalar_ptr(
1241 ) -> Result<Self::Const, Self::Error> {
1242 define_scoped_cx!(self);
1244 let (alloc_id, offset) = ptr.into_parts();
1246 // Byte strings (&[u8; N])
1253 Ty(Interned(ty::TyS { kind: ty::Uint(ty::UintTy::U8), .. }, _)),
1256 val: ty::ConstKind::Value(ConstValue::Scalar(int)),
1267 ) => match self.tcx().get_global_alloc(alloc_id) {
1268 Some(GlobalAlloc::Memory(alloc)) => {
1269 let len = int.assert_bits(self.tcx().data_layout.pointer_size);
1270 let range = AllocRange { start: offset, size: Size::from_bytes(len) };
1271 if let Ok(byte_str) = alloc.get_bytes(&self.tcx(), range) {
1272 p!(pretty_print_byte_str(byte_str))
1274 p!("<too short allocation>")
1277 // FIXME: for statics and functions, we could in principle print more detail.
1278 Some(GlobalAlloc::Static(def_id)) => p!(write("<static({:?})>", def_id)),
1279 Some(GlobalAlloc::Function(_)) => p!("<function>"),
1280 None => p!("<dangling pointer>"),
1283 // FIXME: We should probably have a helper method to share code with the "Byte strings"
1284 // printing above (which also has to handle pointers to all sorts of things).
1285 match self.tcx().get_global_alloc(alloc_id) {
1286 Some(GlobalAlloc::Function(instance)) => {
1287 self = self.typed_value(
1288 |this| this.print_value_path(instance.def_id(), instance.substs),
1289 |this| this.print_type(ty),
1293 _ => self = self.pretty_print_const_pointer(ptr, ty, print_ty)?,
1296 // Any pointer values not covered by a branch above
1298 self = self.pretty_print_const_pointer(ptr, ty, print_ty)?;
1304 fn pretty_print_const_scalar_int(
1309 ) -> Result<Self::Const, Self::Error> {
1310 define_scoped_cx!(self);
1314 ty::Bool if int == ScalarInt::FALSE => p!("false"),
1315 ty::Bool if int == ScalarInt::TRUE => p!("true"),
1317 ty::Float(ty::FloatTy::F32) => {
1318 p!(write("{}f32", Single::try_from(int).unwrap()))
1320 ty::Float(ty::FloatTy::F64) => {
1321 p!(write("{}f64", Double::try_from(int).unwrap()))
1324 ty::Uint(_) | ty::Int(_) => {
1326 ConstInt::new(int, matches!(ty.kind(), ty::Int(_)), ty.is_ptr_sized_integral());
1327 if print_ty { p!(write("{:#?}", int)) } else { p!(write("{:?}", int)) }
1330 ty::Char if char::try_from(int).is_ok() => {
1331 p!(write("{:?}", char::try_from(int).unwrap()))
1334 ty::Ref(..) | ty::RawPtr(_) | ty::FnPtr(_) => {
1335 let data = int.assert_bits(self.tcx().data_layout.pointer_size);
1336 self = self.typed_value(
1338 write!(this, "0x{:x}", data)?;
1341 |this| this.print_type(ty),
1345 // For function type zsts just printing the path is enough
1346 ty::FnDef(d, s) if int == ScalarInt::ZST => {
1347 p!(print_value_path(*d, s))
1349 // Nontrivial types with scalar bit representation
1351 let print = |mut this: Self| {
1352 if int.size() == Size::ZERO {
1353 write!(this, "transmute(())")?;
1355 write!(this, "transmute(0x{:x})", int)?;
1359 self = if print_ty {
1360 self.typed_value(print, |this| this.print_type(ty), ": ")?
1369 /// This is overridden for MIR printing because we only want to hide alloc ids from users, not
1370 /// from MIR where it is actually useful.
1371 fn pretty_print_const_pointer<Tag: Provenance>(
1376 ) -> Result<Self::Const, Self::Error> {
1380 this.write_str("&_")?;
1383 |this| this.print_type(ty),
1387 self.write_str("&_")?;
1392 fn pretty_print_byte_str(mut self, byte_str: &'tcx [u8]) -> Result<Self::Const, Self::Error> {
1393 define_scoped_cx!(self);
1395 for &c in byte_str {
1396 for e in std::ascii::escape_default(c) {
1397 self.write_char(e as char)?;
1404 fn pretty_print_const_value(
1406 ct: ConstValue<'tcx>,
1409 ) -> Result<Self::Const, Self::Error> {
1410 define_scoped_cx!(self);
1412 if self.tcx().sess.verbose() {
1413 p!(write("ConstValue({:?}: ", ct), print(ty), ")");
1417 let u8_type = self.tcx().types.u8;
1419 match (ct, ty.kind()) {
1420 // Byte/string slices, printed as (byte) string literals.
1422 ConstValue::Slice { data, start, end },
1423 ty::Ref(_, Ty(Interned(ty::TyS { kind: ty::Slice(t), .. }, _)), _),
1424 ) if *t == u8_type => {
1425 // The `inspect` here is okay since we checked the bounds, and there are
1426 // no relocations (we have an active slice reference here). We don't use
1427 // this result to affect interpreter execution.
1428 let byte_str = data.inspect_with_uninit_and_ptr_outside_interpreter(start..end);
1429 self.pretty_print_byte_str(byte_str)
1432 ConstValue::Slice { data, start, end },
1433 ty::Ref(_, Ty(Interned(ty::TyS { kind: ty::Str, .. }, _)), _),
1435 // The `inspect` here is okay since we checked the bounds, and there are no
1436 // relocations (we have an active `str` reference here). We don't use this
1437 // result to affect interpreter execution.
1438 let slice = data.inspect_with_uninit_and_ptr_outside_interpreter(start..end);
1439 let s = std::str::from_utf8(slice).expect("non utf8 str from miri");
1440 p!(write("{:?}", s));
1443 (ConstValue::ByRef { alloc, offset }, ty::Array(t, n)) if *t == u8_type => {
1444 let n = n.val().try_to_bits(self.tcx().data_layout.pointer_size).unwrap();
1445 // cast is ok because we already checked for pointer size (32 or 64 bit) above
1446 let range = AllocRange { start: offset, size: Size::from_bytes(n) };
1448 let byte_str = alloc.get_bytes(&self.tcx(), range).unwrap();
1450 p!(pretty_print_byte_str(byte_str));
1454 // Aggregates, printed as array/tuple/struct/variant construction syntax.
1456 // NB: the `has_param_types_or_consts` check ensures that we can use
1457 // the `destructure_const` query with an empty `ty::ParamEnv` without
1458 // introducing ICEs (e.g. via `layout_of`) from missing bounds.
1459 // E.g. `transmute([0usize; 2]): (u8, *mut T)` needs to know `T: Sized`
1460 // to be able to destructure the tuple into `(0u8, *mut T)
1462 // FIXME(eddyb) for `--emit=mir`/`-Z dump-mir`, we should provide the
1463 // correct `ty::ParamEnv` to allow printing *all* constant values.
1464 (_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) if !ty.has_param_types_or_consts() => {
1465 let Some(contents) = self.tcx().try_destructure_const(
1466 ty::ParamEnv::reveal_all()
1467 .and(self.tcx().mk_const(ty::ConstS { val: ty::ConstKind::Value(ct), ty })),
1469 // Fall back to debug pretty printing for invalid constants.
1470 p!(write("{:?}", ct));
1472 p!(": ", print(ty));
1477 let fields = contents.fields.iter().copied();
1481 p!("[", comma_sep(fields), "]");
1484 p!("(", comma_sep(fields));
1485 if contents.fields.len() == 1 {
1490 ty::Adt(def, _) if def.variants.is_empty() => {
1491 self = self.typed_value(
1493 write!(this, "unreachable()")?;
1496 |this| this.print_type(ty),
1500 ty::Adt(def, substs) => {
1502 contents.variant.expect("destructed const of adt without variant idx");
1503 let variant_def = &def.variants[variant_idx];
1504 p!(print_value_path(variant_def.def_id, substs));
1506 match variant_def.ctor_kind {
1507 CtorKind::Const => {}
1509 p!("(", comma_sep(fields), ")");
1511 CtorKind::Fictive => {
1513 let mut first = true;
1514 for (field_def, field) in iter::zip(&variant_def.fields, fields) {
1518 p!(write("{}: ", field_def.name), print(field));
1525 _ => unreachable!(),
1531 (ConstValue::Scalar(scalar), _) => self.pretty_print_const_scalar(scalar, ty, print_ty),
1533 // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
1534 // their fields instead of just dumping the memory.
1537 p!(write("{:?}", ct));
1539 p!(": ", print(ty));
1547 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
1548 pub struct FmtPrinter<'a, 'tcx>(Box<FmtPrinterData<'a, 'tcx>>);
1550 pub struct FmtPrinterData<'a, 'tcx> {
1556 pub print_alloc_ids: bool,
1558 used_region_names: FxHashSet<Symbol>,
1559 region_index: usize,
1560 binder_depth: usize,
1561 printed_type_count: usize,
1563 pub region_highlight_mode: RegionHighlightMode<'tcx>,
1565 pub ty_infer_name_resolver: Option<Box<dyn Fn(ty::TyVid) -> Option<String> + 'a>>,
1566 pub const_infer_name_resolver: Option<Box<dyn Fn(ty::ConstVid<'tcx>) -> Option<String> + 'a>>,
1569 impl<'a, 'tcx> Deref for FmtPrinter<'a, 'tcx> {
1570 type Target = FmtPrinterData<'a, 'tcx>;
1571 fn deref(&self) -> &Self::Target {
1576 impl DerefMut for FmtPrinter<'_, '_> {
1577 fn deref_mut(&mut self) -> &mut Self::Target {
1582 impl<'a, 'tcx> FmtPrinter<'a, 'tcx> {
1583 pub fn new(tcx: TyCtxt<'tcx>, ns: Namespace) -> Self {
1584 FmtPrinter(Box::new(FmtPrinterData {
1588 in_value: ns == Namespace::ValueNS,
1589 print_alloc_ids: false,
1590 used_region_names: Default::default(),
1593 printed_type_count: 0,
1594 region_highlight_mode: RegionHighlightMode::new(tcx),
1595 ty_infer_name_resolver: None,
1596 const_infer_name_resolver: None,
1600 pub fn into_buffer(self) -> String {
1605 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1606 // (but also some things just print a `DefId` generally so maybe we need this?)
1607 fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
1608 match tcx.def_key(def_id).disambiguated_data.data {
1609 DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::ImplTrait => {
1613 DefPathData::ValueNs(..)
1614 | DefPathData::AnonConst
1615 | DefPathData::ClosureExpr
1616 | DefPathData::Ctor => Namespace::ValueNS,
1618 DefPathData::MacroNs(..) => Namespace::MacroNS,
1620 _ => Namespace::TypeNS,
1624 impl<'t> TyCtxt<'t> {
1625 /// Returns a string identifying this `DefId`. This string is
1626 /// suitable for user output.
1627 pub fn def_path_str(self, def_id: DefId) -> String {
1628 self.def_path_str_with_substs(def_id, &[])
1631 pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1632 let ns = guess_def_namespace(self, def_id);
1633 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1634 FmtPrinter::new(self, ns).print_def_path(def_id, substs).unwrap().into_buffer()
1638 impl fmt::Write for FmtPrinter<'_, '_> {
1639 fn write_str(&mut self, s: &str) -> fmt::Result {
1640 self.fmt.push_str(s);
1645 impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> {
1646 type Error = fmt::Error;
1651 type DynExistential = Self;
1654 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
1661 substs: &'tcx [GenericArg<'tcx>],
1662 ) -> Result<Self::Path, Self::Error> {
1663 define_scoped_cx!(self);
1665 if substs.is_empty() {
1666 match self.try_print_trimmed_def_path(def_id)? {
1667 (cx, true) => return Ok(cx),
1668 (cx, false) => self = cx,
1671 match self.try_print_visible_def_path(def_id)? {
1672 (cx, true) => return Ok(cx),
1673 (cx, false) => self = cx,
1677 let key = self.tcx.def_key(def_id);
1678 if let DefPathData::Impl = key.disambiguated_data.data {
1679 // Always use types for non-local impls, where types are always
1680 // available, and filename/line-number is mostly uninteresting.
1681 let use_types = !def_id.is_local() || {
1682 // Otherwise, use filename/line-number if forced.
1683 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1688 // If no type info is available, fall back to
1689 // pretty printing some span information. This should
1690 // only occur very early in the compiler pipeline.
1691 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1692 let span = self.tcx.def_span(def_id);
1694 self = self.print_def_path(parent_def_id, &[])?;
1696 // HACK(eddyb) copy of `path_append` to avoid
1697 // constructing a `DisambiguatedDefPathData`.
1698 if !self.empty_path {
1699 write!(self, "::")?;
1704 // This may end up in stderr diagnostics but it may also be emitted
1705 // into MIR. Hence we use the remapped path if available
1706 self.tcx.sess.source_map().span_to_embeddable_string(span)
1708 self.empty_path = false;
1714 self.default_print_def_path(def_id, substs)
1717 fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
1718 self.pretty_print_region(region)
1721 fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1722 let type_length_limit = self.tcx.type_length_limit();
1723 if type_length_limit.value_within_limit(self.printed_type_count) {
1724 self.printed_type_count += 1;
1725 self.pretty_print_type(ty)
1727 write!(self, "...")?;
1732 fn print_dyn_existential(
1734 predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
1735 ) -> Result<Self::DynExistential, Self::Error> {
1736 self.pretty_print_dyn_existential(predicates)
1739 fn print_const(self, ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1740 self.pretty_print_const(ct, true)
1743 fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1744 self.empty_path = true;
1745 if cnum == LOCAL_CRATE {
1746 if self.tcx.sess.rust_2018() {
1747 // We add the `crate::` keyword on Rust 2018, only when desired.
1748 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1749 write!(self, "{}", kw::Crate)?;
1750 self.empty_path = false;
1754 write!(self, "{}", self.tcx.crate_name(cnum))?;
1755 self.empty_path = false;
1763 trait_ref: Option<ty::TraitRef<'tcx>>,
1764 ) -> Result<Self::Path, Self::Error> {
1765 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1766 self.empty_path = false;
1770 fn path_append_impl(
1772 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1773 _disambiguated_data: &DisambiguatedDefPathData,
1775 trait_ref: Option<ty::TraitRef<'tcx>>,
1776 ) -> Result<Self::Path, Self::Error> {
1777 self = self.pretty_path_append_impl(
1779 cx = print_prefix(cx)?;
1789 self.empty_path = false;
1795 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1796 disambiguated_data: &DisambiguatedDefPathData,
1797 ) -> Result<Self::Path, Self::Error> {
1798 self = print_prefix(self)?;
1800 // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
1801 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
1805 let name = disambiguated_data.data.name();
1806 if !self.empty_path {
1807 write!(self, "::")?;
1810 if let DefPathDataName::Named(name) = name {
1811 if Ident::with_dummy_span(name).is_raw_guess() {
1812 write!(self, "r#")?;
1816 let verbose = self.tcx.sess.verbose();
1817 disambiguated_data.fmt_maybe_verbose(&mut self, verbose)?;
1819 self.empty_path = false;
1824 fn path_generic_args(
1826 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1827 args: &[GenericArg<'tcx>],
1828 ) -> Result<Self::Path, Self::Error> {
1829 self = print_prefix(self)?;
1831 // Don't print `'_` if there's no unerased regions.
1832 let print_regions = self.tcx.sess.verbose()
1833 || args.iter().any(|arg| match arg.unpack() {
1834 GenericArgKind::Lifetime(r) => !r.is_erased(),
1837 let args = args.iter().cloned().filter(|arg| match arg.unpack() {
1838 GenericArgKind::Lifetime(_) => print_regions,
1842 if args.clone().next().is_some() {
1844 write!(self, "::")?;
1846 self.generic_delimiters(|cx| cx.comma_sep(args))
1853 impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> {
1854 fn ty_infer_name(&self, id: ty::TyVid) -> Option<String> {
1855 self.0.ty_infer_name_resolver.as_ref().and_then(|func| func(id))
1858 fn const_infer_name(&self, id: ty::ConstVid<'tcx>) -> Option<String> {
1859 self.0.const_infer_name_resolver.as_ref().and_then(|func| func(id))
1862 fn print_value_path(
1865 substs: &'tcx [GenericArg<'tcx>],
1866 ) -> Result<Self::Path, Self::Error> {
1867 let was_in_value = std::mem::replace(&mut self.in_value, true);
1868 self = self.print_def_path(def_id, substs)?;
1869 self.in_value = was_in_value;
1874 fn in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, Self::Error>
1876 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1878 self.pretty_in_binder(value)
1881 fn wrap_binder<T, C: Fn(&T, Self) -> Result<Self, Self::Error>>(
1883 value: &ty::Binder<'tcx, T>,
1885 ) -> Result<Self, Self::Error>
1887 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1889 self.pretty_wrap_binder(value, f)
1894 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1895 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
1897 ) -> Result<Self::Const, Self::Error> {
1898 self.write_str("{")?;
1900 self.write_str(conversion)?;
1901 let was_in_value = std::mem::replace(&mut self.in_value, false);
1903 self.in_value = was_in_value;
1904 self.write_str("}")?;
1908 fn generic_delimiters(
1910 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1911 ) -> Result<Self, Self::Error> {
1914 let was_in_value = std::mem::replace(&mut self.in_value, false);
1915 let mut inner = f(self)?;
1916 inner.in_value = was_in_value;
1918 write!(inner, ">")?;
1922 fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool {
1923 let highlight = self.region_highlight_mode;
1924 if highlight.region_highlighted(region).is_some() {
1928 if self.tcx.sess.verbose() {
1932 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1935 ty::ReEarlyBound(ref data) => {
1936 data.name != kw::Empty && data.name != kw::UnderscoreLifetime
1939 ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
1940 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1941 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1942 if let ty::BrNamed(_, name) = br {
1943 if name != kw::Empty && name != kw::UnderscoreLifetime {
1948 if let Some((region, _)) = highlight.highlight_bound_region {
1957 ty::ReVar(_) if identify_regions => true,
1959 ty::ReVar(_) | ty::ReErased => false,
1961 ty::ReStatic | ty::ReEmpty(_) => true,
1965 fn pretty_print_const_pointer<Tag: Provenance>(
1970 ) -> Result<Self::Const, Self::Error> {
1971 let print = |mut this: Self| {
1972 define_scoped_cx!(this);
1973 if this.print_alloc_ids {
1974 p!(write("{:?}", p));
1981 self.typed_value(print, |this| this.print_type(ty), ": ")
1988 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1989 impl FmtPrinter<'_, '_> {
1990 pub fn pretty_print_region(mut self, region: ty::Region<'_>) -> Result<Self, fmt::Error> {
1991 define_scoped_cx!(self);
1993 // Watch out for region highlights.
1994 let highlight = self.region_highlight_mode;
1995 if let Some(n) = highlight.region_highlighted(region) {
1996 p!(write("'{}", n));
2000 if self.tcx.sess.verbose() {
2001 p!(write("{:?}", region));
2005 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
2007 // These printouts are concise. They do not contain all the information
2008 // the user might want to diagnose an error, but there is basically no way
2009 // to fit that into a short string. Hence the recommendation to use
2010 // `explain_region()` or `note_and_explain_region()`.
2012 ty::ReEarlyBound(ref data) => {
2013 if data.name != kw::Empty {
2014 p!(write("{}", data.name));
2018 ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
2019 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
2020 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
2021 if let ty::BrNamed(_, name) = br {
2022 if name != kw::Empty && name != kw::UnderscoreLifetime {
2023 p!(write("{}", name));
2028 if let Some((region, counter)) = highlight.highlight_bound_region {
2030 p!(write("'{}", counter));
2035 ty::ReVar(region_vid) if identify_regions => {
2036 p!(write("{:?}", region_vid));
2045 ty::ReEmpty(ty::UniverseIndex::ROOT) => {
2049 ty::ReEmpty(ui) => {
2050 p!(write("'<empty:{:?}>", ui));
2061 /// Folds through bound vars and placeholders, naming them
2062 struct RegionFolder<'a, 'tcx> {
2064 current_index: ty::DebruijnIndex,
2065 region_map: BTreeMap<ty::BoundRegion, ty::Region<'tcx>>,
2066 name: &'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a),
2069 impl<'a, 'tcx> ty::TypeFolder<'tcx> for RegionFolder<'a, 'tcx> {
2070 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
2074 fn fold_binder<T: TypeFoldable<'tcx>>(
2076 t: ty::Binder<'tcx, T>,
2077 ) -> ty::Binder<'tcx, T> {
2078 self.current_index.shift_in(1);
2079 let t = t.super_fold_with(self);
2080 self.current_index.shift_out(1);
2084 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
2086 _ if t.has_vars_bound_at_or_above(self.current_index) || t.has_placeholders() => {
2087 return t.super_fold_with(self);
2094 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
2095 let name = &mut self.name;
2096 let region = match *r {
2097 ty::ReLateBound(_, br) => *self.region_map.entry(br).or_insert_with(|| name(br)),
2098 ty::RePlaceholder(ty::PlaceholderRegion { name: kind, .. }) => {
2099 // If this is an anonymous placeholder, don't rename. Otherwise, in some
2100 // async fns, we get a `for<'r> Send` bound
2102 ty::BrAnon(_) | ty::BrEnv => r,
2104 // Index doesn't matter, since this is just for naming and these never get bound
2105 let br = ty::BoundRegion { var: ty::BoundVar::from_u32(0), kind };
2106 *self.region_map.entry(br).or_insert_with(|| name(br))
2112 if let ty::ReLateBound(debruijn1, br) = *region {
2113 assert_eq!(debruijn1, ty::INNERMOST);
2114 self.tcx.mk_region(ty::ReLateBound(self.current_index, br))
2121 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
2122 // `region_index` and `used_region_names`.
2123 impl<'tcx> FmtPrinter<'_, 'tcx> {
2124 pub fn name_all_regions<T>(
2126 value: &ty::Binder<'tcx, T>,
2127 ) -> Result<(Self, T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>), fmt::Error>
2129 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2131 fn name_by_region_index(index: usize) -> Symbol {
2133 0 => Symbol::intern("'r"),
2134 1 => Symbol::intern("'s"),
2135 i => Symbol::intern(&format!("'t{}", i - 2)),
2139 // Replace any anonymous late-bound regions with named
2140 // variants, using new unique identifiers, so that we can
2141 // clearly differentiate between named and unnamed regions in
2142 // the output. We'll probably want to tweak this over time to
2143 // decide just how much information to give.
2144 if self.binder_depth == 0 {
2145 self.prepare_late_bound_region_info(value);
2148 let mut empty = true;
2149 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
2156 let _ = write!(cx, "{}", w);
2158 let do_continue = |cx: &mut Self, cont: Symbol| {
2159 let _ = write!(cx, "{}", cont);
2162 define_scoped_cx!(self);
2164 let mut region_index = self.region_index;
2165 // If we want to print verbosly, then print *all* binders, even if they
2166 // aren't named. Eventually, we might just want this as the default, but
2167 // this is not *quite* right and changes the ordering of some output
2169 let (new_value, map) = if self.tcx().sess.verbose() {
2170 // anon index + 1 (BrEnv takes 0) -> name
2171 let mut region_map: BTreeMap<u32, Symbol> = BTreeMap::default();
2172 let bound_vars = value.bound_vars();
2173 for var in bound_vars {
2175 ty::BoundVariableKind::Region(ty::BrNamed(_, name)) => {
2176 start_or_continue(&mut self, "for<", ", ");
2177 do_continue(&mut self, name);
2179 ty::BoundVariableKind::Region(ty::BrAnon(i)) => {
2180 start_or_continue(&mut self, "for<", ", ");
2182 let name = name_by_region_index(region_index);
2184 if !self.used_region_names.contains(&name) {
2188 do_continue(&mut self, name);
2189 region_map.insert(i + 1, name);
2191 ty::BoundVariableKind::Region(ty::BrEnv) => {
2192 start_or_continue(&mut self, "for<", ", ");
2194 let name = name_by_region_index(region_index);
2196 if !self.used_region_names.contains(&name) {
2200 do_continue(&mut self, name);
2201 region_map.insert(0, name);
2206 start_or_continue(&mut self, "", "> ");
2208 self.tcx.replace_late_bound_regions(value.clone(), |br| {
2209 let kind = match br.kind {
2210 ty::BrNamed(_, _) => br.kind,
2212 let name = region_map[&(i + 1)];
2213 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
2216 let name = region_map[&0];
2217 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
2220 self.tcx.mk_region(ty::ReLateBound(
2222 ty::BoundRegion { var: br.var, kind },
2227 let mut name = |br: ty::BoundRegion| {
2228 start_or_continue(&mut self, "for<", ", ");
2229 let kind = match br.kind {
2230 ty::BrNamed(_, name) => {
2231 do_continue(&mut self, name);
2234 ty::BrAnon(_) | ty::BrEnv => {
2236 let name = name_by_region_index(region_index);
2238 if !self.used_region_names.contains(&name) {
2242 do_continue(&mut self, name);
2243 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
2246 tcx.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BoundRegion { var: br.var, kind }))
2248 let mut folder = RegionFolder {
2250 current_index: ty::INNERMOST,
2252 region_map: BTreeMap::new(),
2254 let new_value = value.clone().skip_binder().fold_with(&mut folder);
2255 let region_map = folder.region_map;
2256 start_or_continue(&mut self, "", "> ");
2257 (new_value, region_map)
2260 self.binder_depth += 1;
2261 self.region_index = region_index;
2262 Ok((self, new_value, map))
2265 pub fn pretty_in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, fmt::Error>
2267 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2269 let old_region_index = self.region_index;
2270 let (new, new_value, _) = self.name_all_regions(value)?;
2271 let mut inner = new_value.print(new)?;
2272 inner.region_index = old_region_index;
2273 inner.binder_depth -= 1;
2277 pub fn pretty_wrap_binder<T, C: Fn(&T, Self) -> Result<Self, fmt::Error>>(
2279 value: &ty::Binder<'tcx, T>,
2281 ) -> Result<Self, fmt::Error>
2283 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2285 let old_region_index = self.region_index;
2286 let (new, new_value, _) = self.name_all_regions(value)?;
2287 let mut inner = f(&new_value, new)?;
2288 inner.region_index = old_region_index;
2289 inner.binder_depth -= 1;
2293 #[instrument(skip(self), level = "debug")]
2294 fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<'tcx, T>)
2296 T: TypeFoldable<'tcx>,
2298 struct LateBoundRegionNameCollector<'a, 'tcx> {
2299 used_region_names: &'a mut FxHashSet<Symbol>,
2300 type_collector: SsoHashSet<Ty<'tcx>>,
2303 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_, 'tcx> {
2306 #[instrument(skip(self), level = "trace")]
2307 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
2308 trace!("address: {:p}", r.0.0);
2309 if let ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name), .. }) = *r {
2310 self.used_region_names.insert(name);
2311 } else if let ty::RePlaceholder(ty::PlaceholderRegion {
2312 name: ty::BrNamed(_, name),
2316 self.used_region_names.insert(name);
2318 r.super_visit_with(self)
2321 // We collect types in order to prevent really large types from compiling for
2322 // a really long time. See issue #83150 for why this is necessary.
2323 #[instrument(skip(self), level = "trace")]
2324 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
2325 let not_previously_inserted = self.type_collector.insert(ty);
2326 if not_previously_inserted {
2327 ty.super_visit_with(self)
2329 ControlFlow::CONTINUE
2334 self.used_region_names.clear();
2335 let mut collector = LateBoundRegionNameCollector {
2336 used_region_names: &mut self.used_region_names,
2337 type_collector: SsoHashSet::new(),
2339 value.visit_with(&mut collector);
2340 self.region_index = 0;
2344 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<'tcx, T>
2346 T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
2349 type Error = P::Error;
2350 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
2355 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
2357 T: Print<'tcx, P, Output = P, Error = P::Error>,
2358 U: Print<'tcx, P, Output = P, Error = P::Error>,
2361 type Error = P::Error;
2362 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
2363 define_scoped_cx!(cx);
2364 p!(print(self.0), ": ", print(self.1));
2369 macro_rules! forward_display_to_print {
2371 // Some of the $ty arguments may not actually use 'tcx
2372 $(#[allow(unused_lifetimes)] impl<'tcx> fmt::Display for $ty {
2373 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2374 ty::tls::with(|tcx| {
2375 let cx = tcx.lift(*self)
2376 .expect("could not lift for printing")
2377 .print(FmtPrinter::new(tcx, Namespace::TypeNS))?;
2378 f.write_str(&cx.into_buffer())?;
2386 macro_rules! define_print_and_forward_display {
2387 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
2388 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
2390 type Error = fmt::Error;
2391 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
2392 #[allow(unused_mut)]
2394 define_scoped_cx!($cx);
2396 #[allow(unreachable_code)]
2401 forward_display_to_print!($($ty),+);
2405 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
2406 impl<'tcx> fmt::Display for ty::Region<'tcx> {
2407 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2408 ty::tls::with(|tcx| {
2409 f.write_str(&self.print(FmtPrinter::new(tcx, Namespace::TypeNS))?.into_buffer())
2414 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2415 /// the trait path. That is, it will print `Trait<U>` instead of
2416 /// `<T as Trait<U>>`.
2417 #[derive(Copy, Clone, TypeFoldable, Lift)]
2418 pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
2420 impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
2421 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2422 fmt::Display::fmt(self, f)
2426 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2427 /// the trait name. That is, it will print `Trait` instead of
2428 /// `<T as Trait<U>>`.
2429 #[derive(Copy, Clone, TypeFoldable, Lift)]
2430 pub struct TraitRefPrintOnlyTraitName<'tcx>(ty::TraitRef<'tcx>);
2432 impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitName<'tcx> {
2433 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2434 fmt::Display::fmt(self, f)
2438 impl<'tcx> ty::TraitRef<'tcx> {
2439 pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
2440 TraitRefPrintOnlyTraitPath(self)
2443 pub fn print_only_trait_name(self) -> TraitRefPrintOnlyTraitName<'tcx> {
2444 TraitRefPrintOnlyTraitName(self)
2448 impl<'tcx> ty::Binder<'tcx, ty::TraitRef<'tcx>> {
2449 pub fn print_only_trait_path(self) -> ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>> {
2450 self.map_bound(|tr| tr.print_only_trait_path())
2454 #[derive(Copy, Clone, TypeFoldable, Lift)]
2455 pub struct TraitPredPrintModifiersAndPath<'tcx>(ty::TraitPredicate<'tcx>);
2457 impl<'tcx> fmt::Debug for TraitPredPrintModifiersAndPath<'tcx> {
2458 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2459 fmt::Display::fmt(self, f)
2463 impl<'tcx> ty::TraitPredicate<'tcx> {
2464 pub fn print_modifiers_and_trait_path(self) -> TraitPredPrintModifiersAndPath<'tcx> {
2465 TraitPredPrintModifiersAndPath(self)
2469 impl<'tcx> ty::PolyTraitPredicate<'tcx> {
2470 pub fn print_modifiers_and_trait_path(
2472 ) -> ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>> {
2473 self.map_bound(TraitPredPrintModifiersAndPath)
2477 forward_display_to_print! {
2479 &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
2482 // HACK(eddyb) these are exhaustive instead of generic,
2483 // because `for<'tcx>` isn't possible yet.
2484 ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>,
2485 ty::Binder<'tcx, ty::TraitRef<'tcx>>,
2486 ty::Binder<'tcx, ty::ExistentialTraitRef<'tcx>>,
2487 ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>>,
2488 ty::Binder<'tcx, TraitRefPrintOnlyTraitName<'tcx>>,
2489 ty::Binder<'tcx, ty::FnSig<'tcx>>,
2490 ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2491 ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>>,
2492 ty::Binder<'tcx, ty::SubtypePredicate<'tcx>>,
2493 ty::Binder<'tcx, ty::ProjectionPredicate<'tcx>>,
2494 ty::Binder<'tcx, ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
2495 ty::Binder<'tcx, ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
2497 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
2498 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
2501 define_print_and_forward_display! {
2504 &'tcx ty::List<Ty<'tcx>> {
2505 p!("{{", comma_sep(self.iter()), "}}")
2508 ty::TypeAndMut<'tcx> {
2509 p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
2512 ty::ExistentialTraitRef<'tcx> {
2513 // Use a type that can't appear in defaults of type parameters.
2514 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
2515 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
2516 p!(print(trait_ref.print_only_trait_path()))
2519 ty::ExistentialProjection<'tcx> {
2520 let name = cx.tcx().associated_item(self.item_def_id).name;
2521 p!(write("{} = ", name), print(self.term))
2524 ty::ExistentialPredicate<'tcx> {
2526 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
2527 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
2528 ty::ExistentialPredicate::AutoTrait(def_id) => {
2529 p!(print_def_path(def_id, &[]));
2535 p!(write("{}", self.unsafety.prefix_str()));
2537 if self.abi != Abi::Rust {
2538 p!(write("extern {} ", self.abi));
2541 p!("fn", pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
2544 ty::TraitRef<'tcx> {
2545 p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
2548 TraitRefPrintOnlyTraitPath<'tcx> {
2549 p!(print_def_path(self.0.def_id, self.0.substs));
2552 TraitRefPrintOnlyTraitName<'tcx> {
2553 p!(print_def_path(self.0.def_id, &[]));
2556 TraitPredPrintModifiersAndPath<'tcx> {
2557 if let ty::BoundConstness::ConstIfConst = self.0.constness {
2561 if let ty::ImplPolarity::Negative = self.0.polarity {
2565 p!(print(self.0.trait_ref.print_only_trait_path()));
2569 p!(write("{}", self.name))
2573 p!(write("{}", self.name))
2576 ty::SubtypePredicate<'tcx> {
2577 p!(print(self.a), " <: ", print(self.b))
2580 ty::CoercePredicate<'tcx> {
2581 p!(print(self.a), " -> ", print(self.b))
2584 ty::TraitPredicate<'tcx> {
2585 p!(print(self.trait_ref.self_ty()), ": ");
2586 if let ty::BoundConstness::ConstIfConst = self.constness {
2589 p!(print(self.trait_ref.print_only_trait_path()))
2592 ty::ProjectionPredicate<'tcx> {
2593 p!(print(self.projection_ty), " == ", print(self.term))
2598 ty::Term::Ty(ty) => p!(print(ty)),
2599 ty::Term::Const(c) => p!(print(c)),
2603 ty::ProjectionTy<'tcx> {
2604 p!(print_def_path(self.item_def_id, self.substs));
2609 ty::ClosureKind::Fn => p!("Fn"),
2610 ty::ClosureKind::FnMut => p!("FnMut"),
2611 ty::ClosureKind::FnOnce => p!("FnOnce"),
2615 ty::Predicate<'tcx> {
2616 let binder = self.kind();
2620 ty::PredicateKind<'tcx> {
2622 ty::PredicateKind::Trait(ref data) => {
2625 ty::PredicateKind::Subtype(predicate) => p!(print(predicate)),
2626 ty::PredicateKind::Coerce(predicate) => p!(print(predicate)),
2627 ty::PredicateKind::RegionOutlives(predicate) => p!(print(predicate)),
2628 ty::PredicateKind::TypeOutlives(predicate) => p!(print(predicate)),
2629 ty::PredicateKind::Projection(predicate) => p!(print(predicate)),
2630 ty::PredicateKind::WellFormed(arg) => p!(print(arg), " well-formed"),
2631 ty::PredicateKind::ObjectSafe(trait_def_id) => {
2632 p!("the trait `", print_def_path(trait_def_id, &[]), "` is object-safe")
2634 ty::PredicateKind::ClosureKind(closure_def_id, _closure_substs, kind) => {
2636 print_value_path(closure_def_id, &[]),
2637 write("` implements the trait `{}`", kind))
2639 ty::PredicateKind::ConstEvaluatable(uv) => {
2640 p!("the constant `", print_value_path(uv.def.did, uv.substs), "` can be evaluated")
2642 ty::PredicateKind::ConstEquate(c1, c2) => {
2643 p!("the constant `", print(c1), "` equals `", print(c2), "`")
2645 ty::PredicateKind::TypeWellFormedFromEnv(ty) => {
2646 p!("the type `", print(ty), "` is found in the environment")
2652 match self.unpack() {
2653 GenericArgKind::Lifetime(lt) => p!(print(lt)),
2654 GenericArgKind::Type(ty) => p!(print(ty)),
2655 GenericArgKind::Const(ct) => p!(print(ct)),
2660 fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
2661 // Iterate all local crate items no matter where they are defined.
2662 let hir = tcx.hir();
2663 for item in hir.items() {
2664 if item.ident.name.as_str().is_empty() || matches!(item.kind, ItemKind::Use(_, _)) {
2668 let def_id = item.def_id.to_def_id();
2669 let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
2670 collect_fn(&item.ident, ns, def_id);
2673 // Now take care of extern crate items.
2674 let queue = &mut Vec::new();
2675 let mut seen_defs: DefIdSet = Default::default();
2677 for &cnum in tcx.crates(()).iter() {
2678 let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
2680 // Ignore crates that are not direct dependencies.
2681 match tcx.extern_crate(def_id) {
2683 Some(extern_crate) => {
2684 if !extern_crate.is_direct() {
2693 // Iterate external crate defs but be mindful about visibility
2694 while let Some(def) = queue.pop() {
2695 for child in tcx.module_children(def).iter() {
2696 if !child.vis.is_public() {
2701 def::Res::Def(DefKind::AssocTy, _) => {}
2702 def::Res::Def(DefKind::TyAlias, _) => {}
2703 def::Res::Def(defkind, def_id) => {
2704 if let Some(ns) = defkind.ns() {
2705 collect_fn(&child.ident, ns, def_id);
2708 if matches!(defkind, DefKind::Mod | DefKind::Enum | DefKind::Trait)
2709 && seen_defs.insert(def_id)
2720 /// The purpose of this function is to collect public symbols names that are unique across all
2721 /// crates in the build. Later, when printing about types we can use those names instead of the
2722 /// full exported path to them.
2724 /// So essentially, if a symbol name can only be imported from one place for a type, and as
2725 /// long as it was not glob-imported anywhere in the current crate, we can trim its printed
2726 /// path and print only the name.
2728 /// This has wide implications on error messages with types, for example, shortening
2729 /// `std::vec::Vec` to just `Vec`, as long as there is no other `Vec` importable anywhere.
2731 /// The implementation uses similar import discovery logic to that of 'use' suggestions.
2732 fn trimmed_def_paths(tcx: TyCtxt<'_>, (): ()) -> FxHashMap<DefId, Symbol> {
2733 let mut map: FxHashMap<DefId, Symbol> = FxHashMap::default();
2735 if let TrimmedDefPaths::GoodPath = tcx.sess.opts.trimmed_def_paths {
2736 // For good paths causing this bug, the `rustc_middle::ty::print::with_no_trimmed_paths`
2737 // wrapper can be used to suppress this query, in exchange for full paths being formatted.
2738 tcx.sess.delay_good_path_bug("trimmed_def_paths constructed");
2741 let unique_symbols_rev: &mut FxHashMap<(Namespace, Symbol), Option<DefId>> =
2742 &mut FxHashMap::default();
2744 for symbol_set in tcx.resolutions(()).glob_map.values() {
2745 for symbol in symbol_set {
2746 unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
2747 unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
2748 unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
2752 for_each_def(tcx, |ident, ns, def_id| {
2753 use std::collections::hash_map::Entry::{Occupied, Vacant};
2755 match unique_symbols_rev.entry((ns, ident.name)) {
2756 Occupied(mut v) => match v.get() {
2759 if *existing != def_id {
2765 v.insert(Some(def_id));
2770 for ((_, symbol), opt_def_id) in unique_symbols_rev.drain() {
2771 use std::collections::hash_map::Entry::{Occupied, Vacant};
2773 if let Some(def_id) = opt_def_id {
2774 match map.entry(def_id) {
2775 Occupied(mut v) => {
2776 // A single DefId can be known under multiple names (e.g.,
2777 // with a `pub use ... as ...;`). We need to ensure that the
2778 // name placed in this map is chosen deterministically, so
2779 // if we find multiple names (`symbol`) resolving to the
2780 // same `def_id`, we prefer the lexicographically smallest
2783 // Any stable ordering would be fine here though.
2784 if *v.get() != symbol {
2785 if v.get().as_str() > symbol.as_str() {
2800 pub fn provide(providers: &mut ty::query::Providers) {
2801 *providers = ty::query::Providers { trimmed_def_paths, ..*providers };
2805 pub struct OpaqueFnEntry<'tcx> {
2806 // The trait ref is already stored as a key, so just track if we have it as a real predicate
2808 fn_mut_trait_ref: Option<ty::PolyTraitRef<'tcx>>,
2809 fn_trait_ref: Option<ty::PolyTraitRef<'tcx>>,
2810 return_ty: Option<ty::Binder<'tcx, Term<'tcx>>>,