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 visible_parent = match visible_parent_map.get(&def_id).cloned() {
412 Some(parent) => parent,
413 None => return Ok((self, false)),
416 let actual_parent = self.tcx().parent(def_id);
418 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
419 visible_parent, actual_parent,
422 let mut data = cur_def_key.disambiguated_data.data;
424 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
425 data, visible_parent, actual_parent,
429 // In order to output a path that could actually be imported (valid and visible),
430 // we need to handle re-exports correctly.
432 // For example, take `std::os::unix::process::CommandExt`, this trait is actually
433 // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
435 // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is
436 // private so the "true" path to `CommandExt` isn't accessible.
438 // In this case, the `visible_parent_map` will look something like this:
440 // (child) -> (parent)
441 // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
442 // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
443 // `std::sys::unix::ext` -> `std::os`
445 // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
448 // When printing the path to `CommandExt` and looking at the `cur_def_key` that
449 // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
450 // to the parent - resulting in a mangled path like
451 // `std::os::ext::process::CommandExt`.
453 // Instead, we must detect that there was a re-export and instead print `unix`
454 // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
455 // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
456 // the visible parent (`std::os`). If these do not match, then we iterate over
457 // the children of the visible parent (as was done when computing
458 // `visible_parent_map`), looking for the specific child we currently have and then
459 // have access to the re-exported name.
460 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
461 // Item might be re-exported several times, but filter for the one
462 // that's public and whose identifier isn't `_`.
465 .module_children(visible_parent)
467 .filter(|child| child.res.opt_def_id() == Some(def_id))
468 .find(|child| child.vis.is_public() && child.ident.name != kw::Underscore)
469 .map(|child| child.ident.name);
471 if let Some(new_name) = reexport {
474 // There is no name that is public and isn't `_`, so bail.
475 return Ok((self, false));
478 // Re-exported `extern crate` (#43189).
479 DefPathData::CrateRoot => {
480 data = DefPathData::TypeNs(self.tcx().crate_name(def_id.krate));
484 debug!("try_print_visible_def_path: data={:?}", data);
486 if callers.contains(&visible_parent) {
487 return Ok((self, false));
489 callers.push(visible_parent);
490 // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
491 // knowing ahead of time whether the entire path will succeed or not.
492 // To support printers that do not implement `PrettyPrinter`, a `Vec` or
493 // linked list on the stack would need to be built, before any printing.
494 match self.try_print_visible_def_path_recur(visible_parent, callers)? {
495 (cx, false) => return Ok((cx, false)),
496 (cx, true) => self = cx,
500 Ok((self.path_append(Ok, &DisambiguatedDefPathData { data, disambiguator: 0 })?, true))
503 fn pretty_path_qualified(
506 trait_ref: Option<ty::TraitRef<'tcx>>,
507 ) -> Result<Self::Path, Self::Error> {
508 if trait_ref.is_none() {
509 // Inherent impls. Try to print `Foo::bar` for an inherent
510 // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
511 // anything other than a simple path.
512 match self_ty.kind() {
521 return self_ty.print(self);
528 self.generic_delimiters(|mut cx| {
529 define_scoped_cx!(cx);
532 if let Some(trait_ref) = trait_ref {
533 p!(" as ", print(trait_ref.print_only_trait_path()));
539 fn pretty_path_append_impl(
541 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
543 trait_ref: Option<ty::TraitRef<'tcx>>,
544 ) -> Result<Self::Path, Self::Error> {
545 self = print_prefix(self)?;
547 self.generic_delimiters(|mut cx| {
548 define_scoped_cx!(cx);
551 if let Some(trait_ref) = trait_ref {
552 p!(print(trait_ref.print_only_trait_path()), " for ");
560 fn pretty_print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
561 define_scoped_cx!(self);
564 ty::Bool => p!("bool"),
565 ty::Char => p!("char"),
566 ty::Int(t) => p!(write("{}", t.name_str())),
567 ty::Uint(t) => p!(write("{}", t.name_str())),
568 ty::Float(t) => p!(write("{}", t.name_str())),
569 ty::RawPtr(ref tm) => {
573 hir::Mutability::Mut => "mut",
574 hir::Mutability::Not => "const",
579 ty::Ref(r, ty, mutbl) => {
581 if self.region_should_not_be_omitted(r) {
584 p!(print(ty::TypeAndMut { ty, mutbl }))
586 ty::Never => p!("!"),
587 ty::Tuple(ref tys) => {
588 p!("(", comma_sep(tys.iter()));
594 ty::FnDef(def_id, substs) => {
595 let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs);
596 p!(print(sig), " {{", print_value_path(def_id, substs), "}}");
598 ty::FnPtr(ref bare_fn) => p!(print(bare_fn)),
599 ty::Infer(infer_ty) => {
600 let verbose = self.tcx().sess.verbose();
601 if let ty::TyVar(ty_vid) = infer_ty {
602 if let Some(name) = self.infer_ty_name(ty_vid) {
603 p!(write("{}", name))
606 p!(write("{:?}", infer_ty))
608 p!(write("{}", infer_ty))
612 if verbose { p!(write("{:?}", infer_ty)) } else { p!(write("{}", infer_ty)) }
615 ty::Error(_) => p!("[type error]"),
616 ty::Param(ref param_ty) => p!(write("{}", param_ty)),
617 ty::Bound(debruijn, bound_ty) => match bound_ty.kind {
618 ty::BoundTyKind::Anon => self.pretty_print_bound_var(debruijn, bound_ty.var)?,
619 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
621 ty::Adt(def, substs) => {
622 p!(print_def_path(def.did, substs));
624 ty::Dynamic(data, r) => {
625 let print_r = self.region_should_not_be_omitted(r);
629 p!("dyn ", print(data));
631 p!(" + ", print(r), ")");
634 ty::Foreign(def_id) => {
635 p!(print_def_path(def_id, &[]));
637 ty::Projection(ref data) => p!(print(data)),
638 ty::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
639 ty::Opaque(def_id, substs) => {
640 // FIXME(eddyb) print this with `print_def_path`.
641 // We use verbose printing in 'NO_QUERIES' mode, to
642 // avoid needing to call `predicates_of`. This should
643 // only affect certain debug messages (e.g. messages printed
644 // from `rustc_middle::ty` during the computation of `tcx.predicates_of`),
645 // and should have no effect on any compiler output.
646 if self.tcx().sess.verbose() || NO_QUERIES.with(|q| q.get()) {
647 p!(write("Opaque({:?}, {:?})", def_id, substs));
651 return with_no_queries!({
652 let def_key = self.tcx().def_key(def_id);
653 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
654 p!(write("{}", name));
655 // FIXME(eddyb) print this with `print_def_path`.
656 if !substs.is_empty() {
658 p!(generic_delimiters(|cx| cx.comma_sep(substs.iter())));
663 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() {
758 p!(write("{}", param));
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().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() {
901 let mut first = true;
907 p!(print(trait_ref.rebind(*ty)));
911 for (assoc_item_def_id, term) in assoc_items {
915 p!(write("{} = ", self.tcx().associated_item(assoc_item_def_id).name));
917 match term.skip_binder() {
919 // Skip printing `<[generator@] as Generator<_>>::Return` from async blocks
921 ty.kind(), ty::Projection(ty::ProjectionTy { item_def_id, .. })
922 if Some(*item_def_id) == self.tcx().lang_items().generator_return()
944 p!(write("{}?Sized", if first { " " } else { " + " }));
952 /// Insert the trait ref and optionally a projection type associated with it into either the
953 /// traits map or fn_traits map, depending on if the trait is in the Fn* family of traits.
954 fn insert_trait_and_projection(
956 trait_ref: ty::PolyTraitRef<'tcx>,
957 proj_ty: Option<(DefId, ty::Binder<'tcx, Term<'tcx>>)>,
958 traits: &mut BTreeMap<
959 ty::PolyTraitRef<'tcx>,
960 BTreeMap<DefId, ty::Binder<'tcx, Term<'tcx>>>,
962 fn_traits: &mut BTreeMap<ty::PolyTraitRef<'tcx>, OpaqueFnEntry<'tcx>>,
964 let trait_def_id = trait_ref.def_id();
966 // If our trait_ref is FnOnce or any of its children, project it onto the parent FnOnce
967 // super-trait ref and record it there.
968 if let Some(fn_once_trait) = self.tcx().lang_items().fn_once_trait() {
969 // If we have a FnOnce, then insert it into
970 if trait_def_id == fn_once_trait {
971 let entry = fn_traits.entry(trait_ref).or_default();
972 // Optionally insert the return_ty as well.
973 if let Some((_, ty)) = proj_ty {
974 entry.return_ty = Some(ty);
976 entry.has_fn_once = true;
978 } else if Some(trait_def_id) == self.tcx().lang_items().fn_mut_trait() {
979 let super_trait_ref = crate::traits::util::supertraits(self.tcx(), trait_ref)
980 .find(|super_trait_ref| super_trait_ref.def_id() == fn_once_trait)
983 fn_traits.entry(super_trait_ref).or_default().fn_mut_trait_ref = Some(trait_ref);
985 } else if Some(trait_def_id) == self.tcx().lang_items().fn_trait() {
986 let super_trait_ref = crate::traits::util::supertraits(self.tcx(), trait_ref)
987 .find(|super_trait_ref| super_trait_ref.def_id() == fn_once_trait)
990 fn_traits.entry(super_trait_ref).or_default().fn_trait_ref = Some(trait_ref);
995 // Otherwise, just group our traits and projection types.
996 traits.entry(trait_ref).or_default().extend(proj_ty);
999 fn pretty_print_bound_var(
1001 debruijn: ty::DebruijnIndex,
1003 ) -> Result<(), Self::Error> {
1004 if debruijn == ty::INNERMOST {
1005 write!(self, "^{}", var.index())
1007 write!(self, "^{}_{}", debruijn.index(), var.index())
1011 fn infer_ty_name(&self, _: ty::TyVid) -> Option<String> {
1015 fn pretty_print_dyn_existential(
1017 predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
1018 ) -> Result<Self::DynExistential, Self::Error> {
1019 // Generate the main trait ref, including associated types.
1020 let mut first = true;
1022 if let Some(principal) = predicates.principal() {
1023 self = self.wrap_binder(&principal, |principal, mut cx| {
1024 define_scoped_cx!(cx);
1025 p!(print_def_path(principal.def_id, &[]));
1027 let mut resugared = false;
1029 // Special-case `Fn(...) -> ...` and resugar it.
1030 let fn_trait_kind = cx.tcx().fn_trait_kind_from_lang_item(principal.def_id);
1031 if !cx.tcx().sess.verbose() && fn_trait_kind.is_some() {
1032 if let ty::Tuple(ref args) = principal.substs.type_at(0).kind() {
1033 let mut projections = predicates.projection_bounds();
1034 if let (Some(proj), None) = (projections.next(), projections.next()) {
1035 let tys: Vec<_> = args.iter().map(|k| k.expect_ty()).collect();
1039 proj.skip_binder().term.ty().expect("Return type was a const")
1046 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
1047 // in order to place the projections inside the `<...>`.
1049 // Use a type that can't appear in defaults of type parameters.
1050 let dummy_cx = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1051 let principal = principal.with_self_ty(cx.tcx(), dummy_cx);
1053 let args = cx.generic_args_to_print(
1054 cx.tcx().generics_of(principal.def_id),
1058 // Don't print `'_` if there's no unerased regions.
1059 let print_regions = args.iter().any(|arg| match arg.unpack() {
1060 GenericArgKind::Lifetime(r) => !r.is_erased(),
1063 let mut args = args.iter().cloned().filter(|arg| match arg.unpack() {
1064 GenericArgKind::Lifetime(_) => print_regions,
1067 let mut projections = predicates.projection_bounds();
1069 let arg0 = args.next();
1070 let projection0 = projections.next();
1071 if arg0.is_some() || projection0.is_some() {
1072 let args = arg0.into_iter().chain(args);
1073 let projections = projection0.into_iter().chain(projections);
1075 p!(generic_delimiters(|mut cx| {
1076 cx = cx.comma_sep(args)?;
1077 if arg0.is_some() && projection0.is_some() {
1080 cx.comma_sep(projections)
1090 define_scoped_cx!(self);
1093 // FIXME(eddyb) avoid printing twice (needed to ensure
1094 // that the auto traits are sorted *and* printed via cx).
1095 let mut auto_traits: Vec<_> =
1096 predicates.auto_traits().map(|did| (self.tcx().def_path_str(did), did)).collect();
1098 // The auto traits come ordered by `DefPathHash`. While
1099 // `DefPathHash` is *stable* in the sense that it depends on
1100 // neither the host nor the phase of the moon, it depends
1101 // "pseudorandomly" on the compiler version and the target.
1103 // To avoid that causing instabilities in compiletest
1104 // output, sort the auto-traits alphabetically.
1107 for (_, def_id) in auto_traits {
1113 p!(print_def_path(def_id, &[]));
1121 inputs: &[Ty<'tcx>],
1124 ) -> Result<Self, Self::Error> {
1125 define_scoped_cx!(self);
1127 p!("(", comma_sep(inputs.iter().copied()));
1129 if !inputs.is_empty() {
1135 if !output.is_unit() {
1136 p!(" -> ", print(output));
1142 fn pretty_print_const(
1144 ct: ty::Const<'tcx>,
1146 ) -> Result<Self::Const, Self::Error> {
1147 define_scoped_cx!(self);
1149 if self.tcx().sess.verbose() {
1150 p!(write("Const({:?}: {:?})", ct.val(), ct.ty()));
1154 macro_rules! print_underscore {
1157 self = self.typed_value(
1162 |this| this.print_type(ct.ty()),
1172 ty::ConstKind::Unevaluated(ty::Unevaluated {
1175 promoted: Some(promoted),
1177 p!(print_value_path(def.did, substs));
1178 p!(write("::{:?}", promoted));
1180 ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted: None }) => {
1181 match self.tcx().def_kind(def.did) {
1182 DefKind::Static | DefKind::Const | DefKind::AssocConst => {
1183 p!(print_value_path(def.did, substs))
1187 let span = self.tcx().def_span(def.did);
1188 if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span) {
1189 p!(write("{}", snip))
1199 ty::ConstKind::Infer(..) => print_underscore!(),
1200 ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)),
1201 ty::ConstKind::Value(value) => {
1202 return self.pretty_print_const_value(value, ct.ty(), print_ty);
1205 ty::ConstKind::Bound(debruijn, bound_var) => {
1206 self.pretty_print_bound_var(debruijn, bound_var)?
1208 ty::ConstKind::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
1209 ty::ConstKind::Error(_) => p!("[const error]"),
1214 fn pretty_print_const_scalar(
1219 ) -> Result<Self::Const, Self::Error> {
1221 Scalar::Ptr(ptr, _size) => self.pretty_print_const_scalar_ptr(ptr, ty, print_ty),
1222 Scalar::Int(int) => self.pretty_print_const_scalar_int(int, ty, print_ty),
1226 fn pretty_print_const_scalar_ptr(
1231 ) -> Result<Self::Const, Self::Error> {
1232 define_scoped_cx!(self);
1234 let (alloc_id, offset) = ptr.into_parts();
1236 // Byte strings (&[u8; N])
1243 Ty(Interned(ty::TyS { kind: ty::Uint(ty::UintTy::U8), .. }, _)),
1246 val: ty::ConstKind::Value(ConstValue::Scalar(int)),
1257 ) => match self.tcx().get_global_alloc(alloc_id) {
1258 Some(GlobalAlloc::Memory(alloc)) => {
1259 let len = int.assert_bits(self.tcx().data_layout.pointer_size);
1260 let range = AllocRange { start: offset, size: Size::from_bytes(len) };
1261 if let Ok(byte_str) = alloc.get_bytes(&self.tcx(), range) {
1262 p!(pretty_print_byte_str(byte_str))
1264 p!("<too short allocation>")
1267 // FIXME: for statics and functions, we could in principle print more detail.
1268 Some(GlobalAlloc::Static(def_id)) => p!(write("<static({:?})>", def_id)),
1269 Some(GlobalAlloc::Function(_)) => p!("<function>"),
1270 None => p!("<dangling pointer>"),
1273 // FIXME: We should probably have a helper method to share code with the "Byte strings"
1274 // printing above (which also has to handle pointers to all sorts of things).
1275 match self.tcx().get_global_alloc(alloc_id) {
1276 Some(GlobalAlloc::Function(instance)) => {
1277 self = self.typed_value(
1278 |this| this.print_value_path(instance.def_id(), instance.substs),
1279 |this| this.print_type(ty),
1283 _ => self = self.pretty_print_const_pointer(ptr, ty, print_ty)?,
1286 // Any pointer values not covered by a branch above
1288 self = self.pretty_print_const_pointer(ptr, ty, print_ty)?;
1294 fn pretty_print_const_scalar_int(
1299 ) -> Result<Self::Const, Self::Error> {
1300 define_scoped_cx!(self);
1304 ty::Bool if int == ScalarInt::FALSE => p!("false"),
1305 ty::Bool if int == ScalarInt::TRUE => p!("true"),
1307 ty::Float(ty::FloatTy::F32) => {
1308 p!(write("{}f32", Single::try_from(int).unwrap()))
1310 ty::Float(ty::FloatTy::F64) => {
1311 p!(write("{}f64", Double::try_from(int).unwrap()))
1314 ty::Uint(_) | ty::Int(_) => {
1316 ConstInt::new(int, matches!(ty.kind(), ty::Int(_)), ty.is_ptr_sized_integral());
1317 if print_ty { p!(write("{:#?}", int)) } else { p!(write("{:?}", int)) }
1320 ty::Char if char::try_from(int).is_ok() => {
1321 p!(write("{:?}", char::try_from(int).unwrap()))
1324 ty::Ref(..) | ty::RawPtr(_) | ty::FnPtr(_) => {
1325 let data = int.assert_bits(self.tcx().data_layout.pointer_size);
1326 self = self.typed_value(
1328 write!(this, "0x{:x}", data)?;
1331 |this| this.print_type(ty),
1335 // For function type zsts just printing the path is enough
1336 ty::FnDef(d, s) if int == ScalarInt::ZST => {
1337 p!(print_value_path(*d, s))
1339 // Nontrivial types with scalar bit representation
1341 let print = |mut this: Self| {
1342 if int.size() == Size::ZERO {
1343 write!(this, "transmute(())")?;
1345 write!(this, "transmute(0x{:x})", int)?;
1349 self = if print_ty {
1350 self.typed_value(print, |this| this.print_type(ty), ": ")?
1359 /// This is overridden for MIR printing because we only want to hide alloc ids from users, not
1360 /// from MIR where it is actually useful.
1361 fn pretty_print_const_pointer<Tag: Provenance>(
1366 ) -> Result<Self::Const, Self::Error> {
1370 this.write_str("&_")?;
1373 |this| this.print_type(ty),
1377 self.write_str("&_")?;
1382 fn pretty_print_byte_str(mut self, byte_str: &'tcx [u8]) -> Result<Self::Const, Self::Error> {
1383 define_scoped_cx!(self);
1385 for &c in byte_str {
1386 for e in std::ascii::escape_default(c) {
1387 self.write_char(e as char)?;
1394 fn pretty_print_const_value(
1396 ct: ConstValue<'tcx>,
1399 ) -> Result<Self::Const, Self::Error> {
1400 define_scoped_cx!(self);
1402 if self.tcx().sess.verbose() {
1403 p!(write("ConstValue({:?}: ", ct), print(ty), ")");
1407 let u8_type = self.tcx().types.u8;
1409 match (ct, ty.kind()) {
1410 // Byte/string slices, printed as (byte) string literals.
1412 ConstValue::Slice { data, start, end },
1413 ty::Ref(_, Ty(Interned(ty::TyS { kind: ty::Slice(t), .. }, _)), _),
1414 ) if *t == u8_type => {
1415 // The `inspect` here is okay since we checked the bounds, and there are
1416 // no relocations (we have an active slice reference here). We don't use
1417 // this result to affect interpreter execution.
1418 let byte_str = data.inspect_with_uninit_and_ptr_outside_interpreter(start..end);
1419 self.pretty_print_byte_str(byte_str)
1422 ConstValue::Slice { data, start, end },
1423 ty::Ref(_, Ty(Interned(ty::TyS { kind: ty::Str, .. }, _)), _),
1425 // The `inspect` here is okay since we checked the bounds, and there are no
1426 // relocations (we have an active `str` reference here). We don't use this
1427 // result to affect interpreter execution.
1428 let slice = data.inspect_with_uninit_and_ptr_outside_interpreter(start..end);
1429 let s = std::str::from_utf8(slice).expect("non utf8 str from miri");
1430 p!(write("{:?}", s));
1433 (ConstValue::ByRef { alloc, offset }, ty::Array(t, n)) if *t == u8_type => {
1434 let n = n.val().try_to_bits(self.tcx().data_layout.pointer_size).unwrap();
1435 // cast is ok because we already checked for pointer size (32 or 64 bit) above
1436 let range = AllocRange { start: offset, size: Size::from_bytes(n) };
1438 let byte_str = alloc.get_bytes(&self.tcx(), range).unwrap();
1440 p!(pretty_print_byte_str(byte_str));
1444 // Aggregates, printed as array/tuple/struct/variant construction syntax.
1446 // NB: the `has_param_types_or_consts` check ensures that we can use
1447 // the `destructure_const` query with an empty `ty::ParamEnv` without
1448 // introducing ICEs (e.g. via `layout_of`) from missing bounds.
1449 // E.g. `transmute([0usize; 2]): (u8, *mut T)` needs to know `T: Sized`
1450 // to be able to destructure the tuple into `(0u8, *mut T)
1452 // FIXME(eddyb) for `--emit=mir`/`-Z dump-mir`, we should provide the
1453 // correct `ty::ParamEnv` to allow printing *all* constant values.
1454 (_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) if !ty.has_param_types_or_consts() => {
1456 self.tcx().destructure_const(ty::ParamEnv::reveal_all().and(
1457 self.tcx().mk_const(ty::ConstS { val: ty::ConstKind::Value(ct), ty }),
1459 let fields = contents.fields.iter().copied();
1463 p!("[", comma_sep(fields), "]");
1466 p!("(", comma_sep(fields));
1467 if contents.fields.len() == 1 {
1472 ty::Adt(def, _) if def.variants.is_empty() => {
1473 self = self.typed_value(
1475 write!(this, "unreachable()")?;
1478 |this| this.print_type(ty),
1482 ty::Adt(def, substs) => {
1484 contents.variant.expect("destructed const of adt without variant idx");
1485 let variant_def = &def.variants[variant_idx];
1486 p!(print_value_path(variant_def.def_id, substs));
1488 match variant_def.ctor_kind {
1489 CtorKind::Const => {}
1491 p!("(", comma_sep(fields), ")");
1493 CtorKind::Fictive => {
1495 let mut first = true;
1496 for (field_def, field) in iter::zip(&variant_def.fields, fields) {
1500 p!(write("{}: ", field_def.name), print(field));
1507 _ => unreachable!(),
1513 (ConstValue::Scalar(scalar), _) => self.pretty_print_const_scalar(scalar, ty, print_ty),
1515 // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
1516 // their fields instead of just dumping the memory.
1519 p!(write("{:?}", ct));
1521 p!(": ", print(ty));
1529 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
1530 pub struct FmtPrinter<'a, 'tcx, F>(Box<FmtPrinterData<'a, 'tcx, F>>);
1532 pub struct FmtPrinterData<'a, 'tcx, F> {
1538 pub print_alloc_ids: bool,
1540 used_region_names: FxHashSet<Symbol>,
1541 region_index: usize,
1542 binder_depth: usize,
1543 printed_type_count: usize,
1545 pub region_highlight_mode: RegionHighlightMode<'tcx>,
1547 pub name_resolver: Option<Box<&'a dyn Fn(ty::TyVid) -> Option<String>>>,
1550 impl<'a, 'tcx, F> Deref for FmtPrinter<'a, 'tcx, F> {
1551 type Target = FmtPrinterData<'a, 'tcx, F>;
1552 fn deref(&self) -> &Self::Target {
1557 impl<F> DerefMut for FmtPrinter<'_, '_, F> {
1558 fn deref_mut(&mut self) -> &mut Self::Target {
1563 impl<'a, 'tcx, F> FmtPrinter<'a, 'tcx, F> {
1564 pub fn new(tcx: TyCtxt<'tcx>, fmt: F, ns: Namespace) -> Self {
1565 FmtPrinter(Box::new(FmtPrinterData {
1569 in_value: ns == Namespace::ValueNS,
1570 print_alloc_ids: false,
1571 used_region_names: Default::default(),
1574 printed_type_count: 0,
1575 region_highlight_mode: RegionHighlightMode::new(tcx),
1576 name_resolver: None,
1581 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1582 // (but also some things just print a `DefId` generally so maybe we need this?)
1583 fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
1584 match tcx.def_key(def_id).disambiguated_data.data {
1585 DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::ImplTrait => {
1589 DefPathData::ValueNs(..)
1590 | DefPathData::AnonConst
1591 | DefPathData::ClosureExpr
1592 | DefPathData::Ctor => Namespace::ValueNS,
1594 DefPathData::MacroNs(..) => Namespace::MacroNS,
1596 _ => Namespace::TypeNS,
1600 impl<'t> TyCtxt<'t> {
1601 /// Returns a string identifying this `DefId`. This string is
1602 /// suitable for user output.
1603 pub fn def_path_str(self, def_id: DefId) -> String {
1604 self.def_path_str_with_substs(def_id, &[])
1607 pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1608 let ns = guess_def_namespace(self, def_id);
1609 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1610 let mut s = String::new();
1611 let _ = FmtPrinter::new(self, &mut s, ns).print_def_path(def_id, substs);
1616 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, F> {
1617 fn write_str(&mut self, s: &str) -> fmt::Result {
1618 self.fmt.write_str(s)
1622 impl<'tcx, F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
1623 type Error = fmt::Error;
1628 type DynExistential = Self;
1631 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
1638 substs: &'tcx [GenericArg<'tcx>],
1639 ) -> Result<Self::Path, Self::Error> {
1640 define_scoped_cx!(self);
1642 if substs.is_empty() {
1643 match self.try_print_trimmed_def_path(def_id)? {
1644 (cx, true) => return Ok(cx),
1645 (cx, false) => self = cx,
1648 match self.try_print_visible_def_path(def_id)? {
1649 (cx, true) => return Ok(cx),
1650 (cx, false) => self = cx,
1654 let key = self.tcx.def_key(def_id);
1655 if let DefPathData::Impl = key.disambiguated_data.data {
1656 // Always use types for non-local impls, where types are always
1657 // available, and filename/line-number is mostly uninteresting.
1658 let use_types = !def_id.is_local() || {
1659 // Otherwise, use filename/line-number if forced.
1660 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1665 // If no type info is available, fall back to
1666 // pretty printing some span information. This should
1667 // only occur very early in the compiler pipeline.
1668 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1669 let span = self.tcx.def_span(def_id);
1671 self = self.print_def_path(parent_def_id, &[])?;
1673 // HACK(eddyb) copy of `path_append` to avoid
1674 // constructing a `DisambiguatedDefPathData`.
1675 if !self.empty_path {
1676 write!(self, "::")?;
1681 // This may end up in stderr diagnostics but it may also be emitted
1682 // into MIR. Hence we use the remapped path if available
1683 self.tcx.sess.source_map().span_to_embeddable_string(span)
1685 self.empty_path = false;
1691 self.default_print_def_path(def_id, substs)
1694 fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
1695 self.pretty_print_region(region)
1698 fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1699 let type_length_limit = self.tcx.type_length_limit();
1700 if type_length_limit.value_within_limit(self.printed_type_count) {
1701 self.printed_type_count += 1;
1702 self.pretty_print_type(ty)
1704 write!(self, "...")?;
1709 fn print_dyn_existential(
1711 predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
1712 ) -> Result<Self::DynExistential, Self::Error> {
1713 self.pretty_print_dyn_existential(predicates)
1716 fn print_const(self, ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1717 self.pretty_print_const(ct, true)
1720 fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1721 self.empty_path = true;
1722 if cnum == LOCAL_CRATE {
1723 if self.tcx.sess.rust_2018() {
1724 // We add the `crate::` keyword on Rust 2018, only when desired.
1725 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1726 write!(self, "{}", kw::Crate)?;
1727 self.empty_path = false;
1731 write!(self, "{}", self.tcx.crate_name(cnum))?;
1732 self.empty_path = false;
1740 trait_ref: Option<ty::TraitRef<'tcx>>,
1741 ) -> Result<Self::Path, Self::Error> {
1742 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1743 self.empty_path = false;
1747 fn path_append_impl(
1749 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1750 _disambiguated_data: &DisambiguatedDefPathData,
1752 trait_ref: Option<ty::TraitRef<'tcx>>,
1753 ) -> Result<Self::Path, Self::Error> {
1754 self = self.pretty_path_append_impl(
1756 cx = print_prefix(cx)?;
1766 self.empty_path = false;
1772 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1773 disambiguated_data: &DisambiguatedDefPathData,
1774 ) -> Result<Self::Path, Self::Error> {
1775 self = print_prefix(self)?;
1777 // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
1778 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
1782 let name = disambiguated_data.data.name();
1783 if !self.empty_path {
1784 write!(self, "::")?;
1787 if let DefPathDataName::Named(name) = name {
1788 if Ident::with_dummy_span(name).is_raw_guess() {
1789 write!(self, "r#")?;
1793 let verbose = self.tcx.sess.verbose();
1794 disambiguated_data.fmt_maybe_verbose(&mut self, verbose)?;
1796 self.empty_path = false;
1801 fn path_generic_args(
1803 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1804 args: &[GenericArg<'tcx>],
1805 ) -> Result<Self::Path, Self::Error> {
1806 self = print_prefix(self)?;
1808 // Don't print `'_` if there's no unerased regions.
1809 let print_regions = self.tcx.sess.verbose()
1810 || args.iter().any(|arg| match arg.unpack() {
1811 GenericArgKind::Lifetime(r) => !r.is_erased(),
1814 let args = args.iter().cloned().filter(|arg| match arg.unpack() {
1815 GenericArgKind::Lifetime(_) => print_regions,
1819 if args.clone().next().is_some() {
1821 write!(self, "::")?;
1823 self.generic_delimiters(|cx| cx.comma_sep(args))
1830 impl<'tcx, F: fmt::Write> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx, F> {
1831 fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> {
1832 self.0.name_resolver.as_ref().and_then(|func| func(id))
1835 fn print_value_path(
1838 substs: &'tcx [GenericArg<'tcx>],
1839 ) -> Result<Self::Path, Self::Error> {
1840 let was_in_value = std::mem::replace(&mut self.in_value, true);
1841 self = self.print_def_path(def_id, substs)?;
1842 self.in_value = was_in_value;
1847 fn in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, Self::Error>
1849 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1851 self.pretty_in_binder(value)
1854 fn wrap_binder<T, C: Fn(&T, Self) -> Result<Self, Self::Error>>(
1856 value: &ty::Binder<'tcx, T>,
1858 ) -> Result<Self, Self::Error>
1860 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1862 self.pretty_wrap_binder(value, f)
1867 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1868 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
1870 ) -> Result<Self::Const, Self::Error> {
1871 self.write_str("{")?;
1873 self.write_str(conversion)?;
1874 let was_in_value = std::mem::replace(&mut self.in_value, false);
1876 self.in_value = was_in_value;
1877 self.write_str("}")?;
1881 fn generic_delimiters(
1883 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1884 ) -> Result<Self, Self::Error> {
1887 let was_in_value = std::mem::replace(&mut self.in_value, false);
1888 let mut inner = f(self)?;
1889 inner.in_value = was_in_value;
1891 write!(inner, ">")?;
1895 fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool {
1896 let highlight = self.region_highlight_mode;
1897 if highlight.region_highlighted(region).is_some() {
1901 if self.tcx.sess.verbose() {
1905 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1908 ty::ReEarlyBound(ref data) => {
1909 data.name != kw::Empty && data.name != kw::UnderscoreLifetime
1912 ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
1913 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1914 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1915 if let ty::BrNamed(_, name) = br {
1916 if name != kw::Empty && name != kw::UnderscoreLifetime {
1921 if let Some((region, _)) = highlight.highlight_bound_region {
1930 ty::ReVar(_) if identify_regions => true,
1932 ty::ReVar(_) | ty::ReErased => false,
1934 ty::ReStatic | ty::ReEmpty(_) => true,
1938 fn pretty_print_const_pointer<Tag: Provenance>(
1943 ) -> Result<Self::Const, Self::Error> {
1944 let print = |mut this: Self| {
1945 define_scoped_cx!(this);
1946 if this.print_alloc_ids {
1947 p!(write("{:?}", p));
1954 self.typed_value(print, |this| this.print_type(ty), ": ")
1961 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1962 impl<F: fmt::Write> FmtPrinter<'_, '_, F> {
1963 pub fn pretty_print_region(mut self, region: ty::Region<'_>) -> Result<Self, fmt::Error> {
1964 define_scoped_cx!(self);
1966 // Watch out for region highlights.
1967 let highlight = self.region_highlight_mode;
1968 if let Some(n) = highlight.region_highlighted(region) {
1969 p!(write("'{}", n));
1973 if self.tcx.sess.verbose() {
1974 p!(write("{:?}", region));
1978 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1980 // These printouts are concise. They do not contain all the information
1981 // the user might want to diagnose an error, but there is basically no way
1982 // to fit that into a short string. Hence the recommendation to use
1983 // `explain_region()` or `note_and_explain_region()`.
1985 ty::ReEarlyBound(ref data) => {
1986 if data.name != kw::Empty {
1987 p!(write("{}", data.name));
1991 ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
1992 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1993 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1994 if let ty::BrNamed(_, name) = br {
1995 if name != kw::Empty && name != kw::UnderscoreLifetime {
1996 p!(write("{}", name));
2001 if let Some((region, counter)) = highlight.highlight_bound_region {
2003 p!(write("'{}", counter));
2008 ty::ReVar(region_vid) if identify_regions => {
2009 p!(write("{:?}", region_vid));
2018 ty::ReEmpty(ty::UniverseIndex::ROOT) => {
2022 ty::ReEmpty(ui) => {
2023 p!(write("'<empty:{:?}>", ui));
2034 /// Folds through bound vars and placeholders, naming them
2035 struct RegionFolder<'a, 'tcx> {
2037 current_index: ty::DebruijnIndex,
2038 region_map: BTreeMap<ty::BoundRegion, ty::Region<'tcx>>,
2039 name: &'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a),
2042 impl<'a, 'tcx> ty::TypeFolder<'tcx> for RegionFolder<'a, 'tcx> {
2043 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
2047 fn fold_binder<T: TypeFoldable<'tcx>>(
2049 t: ty::Binder<'tcx, T>,
2050 ) -> ty::Binder<'tcx, T> {
2051 self.current_index.shift_in(1);
2052 let t = t.super_fold_with(self);
2053 self.current_index.shift_out(1);
2057 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
2059 _ if t.has_vars_bound_at_or_above(self.current_index) || t.has_placeholders() => {
2060 return t.super_fold_with(self);
2067 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
2068 let name = &mut self.name;
2069 let region = match *r {
2070 ty::ReLateBound(_, br) => *self.region_map.entry(br).or_insert_with(|| name(br)),
2071 ty::RePlaceholder(ty::PlaceholderRegion { name: kind, .. }) => {
2072 // If this is an anonymous placeholder, don't rename. Otherwise, in some
2073 // async fns, we get a `for<'r> Send` bound
2075 ty::BrAnon(_) | ty::BrEnv => r,
2077 // Index doesn't matter, since this is just for naming and these never get bound
2078 let br = ty::BoundRegion { var: ty::BoundVar::from_u32(0), kind };
2079 *self.region_map.entry(br).or_insert_with(|| name(br))
2085 if let ty::ReLateBound(debruijn1, br) = *region {
2086 assert_eq!(debruijn1, ty::INNERMOST);
2087 self.tcx.mk_region(ty::ReLateBound(self.current_index, br))
2094 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
2095 // `region_index` and `used_region_names`.
2096 impl<'tcx, F: fmt::Write> FmtPrinter<'_, 'tcx, F> {
2097 pub fn name_all_regions<T>(
2099 value: &ty::Binder<'tcx, T>,
2100 ) -> Result<(Self, T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>), fmt::Error>
2102 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2104 fn name_by_region_index(index: usize) -> Symbol {
2106 0 => Symbol::intern("'r"),
2107 1 => Symbol::intern("'s"),
2108 i => Symbol::intern(&format!("'t{}", i - 2)),
2112 // Replace any anonymous late-bound regions with named
2113 // variants, using new unique identifiers, so that we can
2114 // clearly differentiate between named and unnamed regions in
2115 // the output. We'll probably want to tweak this over time to
2116 // decide just how much information to give.
2117 if self.binder_depth == 0 {
2118 self.prepare_late_bound_region_info(value);
2121 let mut empty = true;
2122 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
2129 let _ = write!(cx, "{}", w);
2131 let do_continue = |cx: &mut Self, cont: Symbol| {
2132 let _ = write!(cx, "{}", cont);
2135 define_scoped_cx!(self);
2137 let mut region_index = self.region_index;
2138 // If we want to print verbosly, then print *all* binders, even if they
2139 // aren't named. Eventually, we might just want this as the default, but
2140 // this is not *quite* right and changes the ordering of some output
2142 let (new_value, map) = if self.tcx().sess.verbose() {
2143 // anon index + 1 (BrEnv takes 0) -> name
2144 let mut region_map: BTreeMap<u32, Symbol> = BTreeMap::default();
2145 let bound_vars = value.bound_vars();
2146 for var in bound_vars {
2148 ty::BoundVariableKind::Region(ty::BrNamed(_, name)) => {
2149 start_or_continue(&mut self, "for<", ", ");
2150 do_continue(&mut self, name);
2152 ty::BoundVariableKind::Region(ty::BrAnon(i)) => {
2153 start_or_continue(&mut self, "for<", ", ");
2155 let name = name_by_region_index(region_index);
2157 if !self.used_region_names.contains(&name) {
2161 do_continue(&mut self, name);
2162 region_map.insert(i + 1, name);
2164 ty::BoundVariableKind::Region(ty::BrEnv) => {
2165 start_or_continue(&mut self, "for<", ", ");
2167 let name = name_by_region_index(region_index);
2169 if !self.used_region_names.contains(&name) {
2173 do_continue(&mut self, name);
2174 region_map.insert(0, name);
2179 start_or_continue(&mut self, "", "> ");
2181 self.tcx.replace_late_bound_regions(value.clone(), |br| {
2182 let kind = match br.kind {
2183 ty::BrNamed(_, _) => br.kind,
2185 let name = region_map[&(i + 1)];
2186 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
2189 let name = region_map[&0];
2190 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
2193 self.tcx.mk_region(ty::ReLateBound(
2195 ty::BoundRegion { var: br.var, kind },
2200 let mut name = |br: ty::BoundRegion| {
2201 start_or_continue(&mut self, "for<", ", ");
2202 let kind = match br.kind {
2203 ty::BrNamed(_, name) => {
2204 do_continue(&mut self, name);
2207 ty::BrAnon(_) | ty::BrEnv => {
2209 let name = name_by_region_index(region_index);
2211 if !self.used_region_names.contains(&name) {
2215 do_continue(&mut self, name);
2216 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
2219 tcx.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BoundRegion { var: br.var, kind }))
2221 let mut folder = RegionFolder {
2223 current_index: ty::INNERMOST,
2225 region_map: BTreeMap::new(),
2227 let new_value = value.clone().skip_binder().fold_with(&mut folder);
2228 let region_map = folder.region_map;
2229 start_or_continue(&mut self, "", "> ");
2230 (new_value, region_map)
2233 self.binder_depth += 1;
2234 self.region_index = region_index;
2235 Ok((self, new_value, map))
2238 pub fn pretty_in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, fmt::Error>
2240 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2242 let old_region_index = self.region_index;
2243 let (new, new_value, _) = self.name_all_regions(value)?;
2244 let mut inner = new_value.print(new)?;
2245 inner.region_index = old_region_index;
2246 inner.binder_depth -= 1;
2250 pub fn pretty_wrap_binder<T, C: Fn(&T, Self) -> Result<Self, fmt::Error>>(
2252 value: &ty::Binder<'tcx, T>,
2254 ) -> Result<Self, fmt::Error>
2256 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2258 let old_region_index = self.region_index;
2259 let (new, new_value, _) = self.name_all_regions(value)?;
2260 let mut inner = f(&new_value, new)?;
2261 inner.region_index = old_region_index;
2262 inner.binder_depth -= 1;
2266 #[instrument(skip(self), level = "debug")]
2267 fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<'tcx, T>)
2269 T: TypeFoldable<'tcx>,
2271 struct LateBoundRegionNameCollector<'a, 'tcx> {
2272 used_region_names: &'a mut FxHashSet<Symbol>,
2273 type_collector: SsoHashSet<Ty<'tcx>>,
2276 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_, 'tcx> {
2279 #[instrument(skip(self), level = "trace")]
2280 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
2281 trace!("address: {:p}", r.0.0);
2282 if let ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name), .. }) = *r {
2283 self.used_region_names.insert(name);
2284 } else if let ty::RePlaceholder(ty::PlaceholderRegion {
2285 name: ty::BrNamed(_, name),
2289 self.used_region_names.insert(name);
2291 r.super_visit_with(self)
2294 // We collect types in order to prevent really large types from compiling for
2295 // a really long time. See issue #83150 for why this is necessary.
2296 #[instrument(skip(self), level = "trace")]
2297 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
2298 let not_previously_inserted = self.type_collector.insert(ty);
2299 if not_previously_inserted {
2300 ty.super_visit_with(self)
2302 ControlFlow::CONTINUE
2307 self.used_region_names.clear();
2308 let mut collector = LateBoundRegionNameCollector {
2309 used_region_names: &mut self.used_region_names,
2310 type_collector: SsoHashSet::new(),
2312 value.visit_with(&mut collector);
2313 self.region_index = 0;
2317 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<'tcx, T>
2319 T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
2322 type Error = P::Error;
2323 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
2328 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
2330 T: Print<'tcx, P, Output = P, Error = P::Error>,
2331 U: Print<'tcx, P, Output = P, Error = P::Error>,
2334 type Error = P::Error;
2335 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
2336 define_scoped_cx!(cx);
2337 p!(print(self.0), ": ", print(self.1));
2342 macro_rules! forward_display_to_print {
2344 // Some of the $ty arguments may not actually use 'tcx
2345 $(#[allow(unused_lifetimes)] impl<'tcx> fmt::Display for $ty {
2346 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2347 ty::tls::with(|tcx| {
2349 .expect("could not lift for printing")
2350 .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
2358 macro_rules! define_print_and_forward_display {
2359 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
2360 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
2362 type Error = fmt::Error;
2363 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
2364 #[allow(unused_mut)]
2366 define_scoped_cx!($cx);
2368 #[allow(unreachable_code)]
2373 forward_display_to_print!($($ty),+);
2377 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
2378 impl<'tcx> fmt::Display for ty::Region<'tcx> {
2379 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2380 ty::tls::with(|tcx| {
2381 self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
2387 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2388 /// the trait path. That is, it will print `Trait<U>` instead of
2389 /// `<T as Trait<U>>`.
2390 #[derive(Copy, Clone, TypeFoldable, Lift)]
2391 pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
2393 impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
2394 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2395 fmt::Display::fmt(self, f)
2399 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2400 /// the trait name. That is, it will print `Trait` instead of
2401 /// `<T as Trait<U>>`.
2402 #[derive(Copy, Clone, TypeFoldable, Lift)]
2403 pub struct TraitRefPrintOnlyTraitName<'tcx>(ty::TraitRef<'tcx>);
2405 impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitName<'tcx> {
2406 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2407 fmt::Display::fmt(self, f)
2411 impl<'tcx> ty::TraitRef<'tcx> {
2412 pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
2413 TraitRefPrintOnlyTraitPath(self)
2416 pub fn print_only_trait_name(self) -> TraitRefPrintOnlyTraitName<'tcx> {
2417 TraitRefPrintOnlyTraitName(self)
2421 impl<'tcx> ty::Binder<'tcx, ty::TraitRef<'tcx>> {
2422 pub fn print_only_trait_path(self) -> ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>> {
2423 self.map_bound(|tr| tr.print_only_trait_path())
2427 #[derive(Copy, Clone, TypeFoldable, Lift)]
2428 pub struct TraitPredPrintModifiersAndPath<'tcx>(ty::TraitPredicate<'tcx>);
2430 impl<'tcx> fmt::Debug for TraitPredPrintModifiersAndPath<'tcx> {
2431 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2432 fmt::Display::fmt(self, f)
2436 impl<'tcx> ty::TraitPredicate<'tcx> {
2437 pub fn print_modifiers_and_trait_path(self) -> TraitPredPrintModifiersAndPath<'tcx> {
2438 TraitPredPrintModifiersAndPath(self)
2442 impl<'tcx> ty::PolyTraitPredicate<'tcx> {
2443 pub fn print_modifiers_and_trait_path(
2445 ) -> ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>> {
2446 self.map_bound(TraitPredPrintModifiersAndPath)
2450 forward_display_to_print! {
2452 &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
2455 // HACK(eddyb) these are exhaustive instead of generic,
2456 // because `for<'tcx>` isn't possible yet.
2457 ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>,
2458 ty::Binder<'tcx, ty::TraitRef<'tcx>>,
2459 ty::Binder<'tcx, ty::ExistentialTraitRef<'tcx>>,
2460 ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>>,
2461 ty::Binder<'tcx, TraitRefPrintOnlyTraitName<'tcx>>,
2462 ty::Binder<'tcx, ty::FnSig<'tcx>>,
2463 ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2464 ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>>,
2465 ty::Binder<'tcx, ty::SubtypePredicate<'tcx>>,
2466 ty::Binder<'tcx, ty::ProjectionPredicate<'tcx>>,
2467 ty::Binder<'tcx, ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
2468 ty::Binder<'tcx, ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
2470 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
2471 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
2474 define_print_and_forward_display! {
2477 &'tcx ty::List<Ty<'tcx>> {
2478 p!("{{", comma_sep(self.iter()), "}}")
2481 ty::TypeAndMut<'tcx> {
2482 p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
2485 ty::ExistentialTraitRef<'tcx> {
2486 // Use a type that can't appear in defaults of type parameters.
2487 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
2488 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
2489 p!(print(trait_ref.print_only_trait_path()))
2492 ty::ExistentialProjection<'tcx> {
2493 let name = cx.tcx().associated_item(self.item_def_id).name;
2494 p!(write("{} = ", name), print(self.term))
2497 ty::ExistentialPredicate<'tcx> {
2499 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
2500 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
2501 ty::ExistentialPredicate::AutoTrait(def_id) => {
2502 p!(print_def_path(def_id, &[]));
2508 p!(write("{}", self.unsafety.prefix_str()));
2510 if self.abi != Abi::Rust {
2511 p!(write("extern {} ", self.abi));
2514 p!("fn", pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
2517 ty::TraitRef<'tcx> {
2518 p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
2521 TraitRefPrintOnlyTraitPath<'tcx> {
2522 p!(print_def_path(self.0.def_id, self.0.substs));
2525 TraitRefPrintOnlyTraitName<'tcx> {
2526 p!(print_def_path(self.0.def_id, &[]));
2529 TraitPredPrintModifiersAndPath<'tcx> {
2530 if let ty::BoundConstness::ConstIfConst = self.0.constness {
2534 if let ty::ImplPolarity::Negative = self.0.polarity {
2538 p!(print(self.0.trait_ref.print_only_trait_path()));
2542 p!(write("{}", self.name))
2546 p!(write("{}", self.name))
2549 ty::SubtypePredicate<'tcx> {
2550 p!(print(self.a), " <: ", print(self.b))
2553 ty::CoercePredicate<'tcx> {
2554 p!(print(self.a), " -> ", print(self.b))
2557 ty::TraitPredicate<'tcx> {
2558 p!(print(self.trait_ref.self_ty()), ": ");
2559 if let ty::BoundConstness::ConstIfConst = self.constness {
2562 p!(print(self.trait_ref.print_only_trait_path()))
2565 ty::ProjectionPredicate<'tcx> {
2566 p!(print(self.projection_ty), " == ", print(self.term))
2571 ty::Term::Ty(ty) => p!(print(ty)),
2572 ty::Term::Const(c) => p!(print(c)),
2576 ty::ProjectionTy<'tcx> {
2577 p!(print_def_path(self.item_def_id, self.substs));
2582 ty::ClosureKind::Fn => p!("Fn"),
2583 ty::ClosureKind::FnMut => p!("FnMut"),
2584 ty::ClosureKind::FnOnce => p!("FnOnce"),
2588 ty::Predicate<'tcx> {
2589 let binder = self.kind();
2593 ty::PredicateKind<'tcx> {
2595 ty::PredicateKind::Trait(ref data) => {
2598 ty::PredicateKind::Subtype(predicate) => p!(print(predicate)),
2599 ty::PredicateKind::Coerce(predicate) => p!(print(predicate)),
2600 ty::PredicateKind::RegionOutlives(predicate) => p!(print(predicate)),
2601 ty::PredicateKind::TypeOutlives(predicate) => p!(print(predicate)),
2602 ty::PredicateKind::Projection(predicate) => p!(print(predicate)),
2603 ty::PredicateKind::WellFormed(arg) => p!(print(arg), " well-formed"),
2604 ty::PredicateKind::ObjectSafe(trait_def_id) => {
2605 p!("the trait `", print_def_path(trait_def_id, &[]), "` is object-safe")
2607 ty::PredicateKind::ClosureKind(closure_def_id, _closure_substs, kind) => {
2609 print_value_path(closure_def_id, &[]),
2610 write("` implements the trait `{}`", kind))
2612 ty::PredicateKind::ConstEvaluatable(uv) => {
2613 p!("the constant `", print_value_path(uv.def.did, uv.substs), "` can be evaluated")
2615 ty::PredicateKind::ConstEquate(c1, c2) => {
2616 p!("the constant `", print(c1), "` equals `", print(c2), "`")
2618 ty::PredicateKind::TypeWellFormedFromEnv(ty) => {
2619 p!("the type `", print(ty), "` is found in the environment")
2625 match self.unpack() {
2626 GenericArgKind::Lifetime(lt) => p!(print(lt)),
2627 GenericArgKind::Type(ty) => p!(print(ty)),
2628 GenericArgKind::Const(ct) => p!(print(ct)),
2633 fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
2634 // Iterate all local crate items no matter where they are defined.
2635 let hir = tcx.hir();
2636 for item in hir.items() {
2637 if item.ident.name.as_str().is_empty() || matches!(item.kind, ItemKind::Use(_, _)) {
2641 let def_id = item.def_id.to_def_id();
2642 let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
2643 collect_fn(&item.ident, ns, def_id);
2646 // Now take care of extern crate items.
2647 let queue = &mut Vec::new();
2648 let mut seen_defs: DefIdSet = Default::default();
2650 for &cnum in tcx.crates(()).iter() {
2651 let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
2653 // Ignore crates that are not direct dependencies.
2654 match tcx.extern_crate(def_id) {
2656 Some(extern_crate) => {
2657 if !extern_crate.is_direct() {
2666 // Iterate external crate defs but be mindful about visibility
2667 while let Some(def) = queue.pop() {
2668 for child in tcx.module_children(def).iter() {
2669 if !child.vis.is_public() {
2674 def::Res::Def(DefKind::AssocTy, _) => {}
2675 def::Res::Def(DefKind::TyAlias, _) => {}
2676 def::Res::Def(defkind, def_id) => {
2677 if let Some(ns) = defkind.ns() {
2678 collect_fn(&child.ident, ns, def_id);
2681 if matches!(defkind, DefKind::Mod | DefKind::Enum | DefKind::Trait)
2682 && seen_defs.insert(def_id)
2693 /// The purpose of this function is to collect public symbols names that are unique across all
2694 /// crates in the build. Later, when printing about types we can use those names instead of the
2695 /// full exported path to them.
2697 /// So essentially, if a symbol name can only be imported from one place for a type, and as
2698 /// long as it was not glob-imported anywhere in the current crate, we can trim its printed
2699 /// path and print only the name.
2701 /// This has wide implications on error messages with types, for example, shortening
2702 /// `std::vec::Vec` to just `Vec`, as long as there is no other `Vec` importable anywhere.
2704 /// The implementation uses similar import discovery logic to that of 'use' suggestions.
2705 fn trimmed_def_paths(tcx: TyCtxt<'_>, (): ()) -> FxHashMap<DefId, Symbol> {
2706 let mut map: FxHashMap<DefId, Symbol> = FxHashMap::default();
2708 if let TrimmedDefPaths::GoodPath = tcx.sess.opts.trimmed_def_paths {
2709 // For good paths causing this bug, the `rustc_middle::ty::print::with_no_trimmed_paths`
2710 // wrapper can be used to suppress this query, in exchange for full paths being formatted.
2711 tcx.sess.delay_good_path_bug("trimmed_def_paths constructed");
2714 let unique_symbols_rev: &mut FxHashMap<(Namespace, Symbol), Option<DefId>> =
2715 &mut FxHashMap::default();
2717 for symbol_set in tcx.resolutions(()).glob_map.values() {
2718 for symbol in symbol_set {
2719 unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
2720 unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
2721 unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
2725 for_each_def(tcx, |ident, ns, def_id| {
2726 use std::collections::hash_map::Entry::{Occupied, Vacant};
2728 match unique_symbols_rev.entry((ns, ident.name)) {
2729 Occupied(mut v) => match v.get() {
2732 if *existing != def_id {
2738 v.insert(Some(def_id));
2743 for ((_, symbol), opt_def_id) in unique_symbols_rev.drain() {
2744 use std::collections::hash_map::Entry::{Occupied, Vacant};
2746 if let Some(def_id) = opt_def_id {
2747 match map.entry(def_id) {
2748 Occupied(mut v) => {
2749 // A single DefId can be known under multiple names (e.g.,
2750 // with a `pub use ... as ...;`). We need to ensure that the
2751 // name placed in this map is chosen deterministically, so
2752 // if we find multiple names (`symbol`) resolving to the
2753 // same `def_id`, we prefer the lexicographically smallest
2756 // Any stable ordering would be fine here though.
2757 if *v.get() != symbol {
2758 if v.get().as_str() > symbol.as_str() {
2773 pub fn provide(providers: &mut ty::query::Providers) {
2774 *providers = ty::query::Providers { trimmed_def_paths, ..*providers };
2778 pub struct OpaqueFnEntry<'tcx> {
2779 // The trait ref is already stored as a key, so just track if we have it as a real predicate
2781 fn_mut_trait_ref: Option<ty::PolyTraitRef<'tcx>>,
2782 fn_trait_ref: Option<ty::PolyTraitRef<'tcx>>,
2783 return_ty: Option<ty::Binder<'tcx, Term<'tcx>>>,