1 use crate::mir::interpret::{AllocRange, GlobalAlloc, Pointer, Provenance, Scalar};
3 self, ConstInt, DefIdTree, ParamConst, ScalarInt, Term, TermKind, Ty, TyCtxt, TypeFoldable,
4 TypeSuperFoldable, TypeSuperVisitable, TypeVisitable,
6 use crate::ty::{GenericArg, GenericArgKind};
7 use rustc_apfloat::ieee::{Double, Single};
8 use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
9 use rustc_data_structures::sso::SsoHashSet;
11 use rustc_hir::def::{self, CtorKind, DefKind, Namespace};
12 use rustc_hir::def_id::{DefId, DefIdSet, CRATE_DEF_ID, LOCAL_CRATE};
13 use rustc_hir::definitions::{DefPathData, DefPathDataName, DisambiguatedDefPathData};
14 use rustc_session::config::TrimmedDefPaths;
15 use rustc_session::cstore::{ExternCrate, ExternCrateSource};
16 use rustc_session::Limit;
17 use rustc_span::symbol::{kw, Ident, Symbol};
18 use rustc_target::abi::Size;
19 use rustc_target::spec::abi::Abi;
20 use smallvec::SmallVec;
24 use std::collections::BTreeMap;
25 use std::convert::TryFrom;
26 use std::fmt::{self, Write as _};
28 use std::ops::{ControlFlow, Deref, DerefMut};
30 // `pretty` is a separate module only for organization.
35 write!(scoped_cx!(), $lit)?
37 (@write($($data:expr),+)) => {
38 write!(scoped_cx!(), $($data),+)?
40 (@print($x:expr)) => {
41 scoped_cx!() = $x.print(scoped_cx!())?
43 (@$method:ident($($arg:expr),*)) => {
44 scoped_cx!() = scoped_cx!().$method($($arg),*)?
46 ($($elem:tt $(($($args:tt)*))?),+) => {{
47 $(p!(@ $elem $(($($args)*))?);)+
50 macro_rules! define_scoped_cx {
52 #[allow(unused_macros)]
53 macro_rules! scoped_cx {
62 static FORCE_IMPL_FILENAME_LINE: Cell<bool> = const { Cell::new(false) };
63 static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = const { Cell::new(false) };
64 static NO_TRIMMED_PATH: Cell<bool> = const { Cell::new(false) };
65 static NO_QUERIES: Cell<bool> = const { Cell::new(false) };
66 static NO_VISIBLE_PATH: Cell<bool> = const { Cell::new(false) };
69 macro_rules! define_helper {
70 ($($(#[$a:meta])* fn $name:ident($helper:ident, $tl:ident);)+) => {
73 pub struct $helper(bool);
76 pub fn new() -> $helper {
77 $helper($tl.with(|c| c.replace(true)))
82 pub macro $name($e:expr) {
84 let _guard = $helper::new();
89 impl Drop for $helper {
91 $tl.with(|c| c.set(self.0))
99 /// Avoids running any queries during any prints that occur
100 /// during the closure. This may alter the appearance of some
101 /// types (e.g. forcing verbose printing for opaque types).
102 /// This method is used during some queries (e.g. `explicit_item_bounds`
103 /// for opaque types), to ensure that any debug printing that
104 /// occurs during the query computation does not end up recursively
105 /// calling the same query.
106 fn with_no_queries(NoQueriesGuard, NO_QUERIES);
107 /// Force us to name impls with just the filename/line number. We
108 /// normally try to use types. But at some points, notably while printing
109 /// cycle errors, this can result in extra or suboptimal error output,
110 /// so this variable disables that check.
111 fn with_forced_impl_filename_line(ForcedImplGuard, FORCE_IMPL_FILENAME_LINE);
112 /// Adds the `crate::` prefix to paths where appropriate.
113 fn with_crate_prefix(CratePrefixGuard, SHOULD_PREFIX_WITH_CRATE);
114 /// Prevent path trimming if it is turned on. Path trimming affects `Display` impl
115 /// of various rustc types, for example `std::vec::Vec` would be trimmed to `Vec`,
116 /// if no other `Vec` is found.
117 fn with_no_trimmed_paths(NoTrimmedGuard, NO_TRIMMED_PATH);
118 /// Prevent selection of visible paths. `Display` impl of DefId will prefer
119 /// visible (public) reexports of types as paths.
120 fn with_no_visible_paths(NoVisibleGuard, NO_VISIBLE_PATH);
123 /// The "region highlights" are used to control region printing during
124 /// specific error messages. When a "region highlight" is enabled, it
125 /// gives an alternate way to print specific regions. For now, we
126 /// always print those regions using a number, so something like "`'0`".
128 /// Regions not selected by the region highlight mode are presently
130 #[derive(Copy, Clone)]
131 pub struct RegionHighlightMode<'tcx> {
134 /// If enabled, when we see the selected region, use "`'N`"
135 /// instead of the ordinary behavior.
136 highlight_regions: [Option<(ty::Region<'tcx>, usize)>; 3],
138 /// If enabled, when printing a "free region" that originated from
139 /// the given `ty::BoundRegionKind`, print it as "`'1`". Free regions that would ordinarily
140 /// have names print as normal.
142 /// This is used when you have a signature like `fn foo(x: &u32,
143 /// y: &'a u32)` and we want to give a name to the region of the
145 highlight_bound_region: Option<(ty::BoundRegionKind, usize)>,
148 impl<'tcx> RegionHighlightMode<'tcx> {
149 pub fn new(tcx: TyCtxt<'tcx>) -> Self {
152 highlight_regions: Default::default(),
153 highlight_bound_region: Default::default(),
157 /// If `region` and `number` are both `Some`, invokes
158 /// `highlighting_region`.
159 pub fn maybe_highlighting_region(
161 region: Option<ty::Region<'tcx>>,
162 number: Option<usize>,
164 if let Some(k) = region {
165 if let Some(n) = number {
166 self.highlighting_region(k, n);
171 /// Highlights the region inference variable `vid` as `'N`.
172 pub fn highlighting_region(&mut self, region: ty::Region<'tcx>, number: usize) {
173 let num_slots = self.highlight_regions.len();
174 let first_avail_slot =
175 self.highlight_regions.iter_mut().find(|s| s.is_none()).unwrap_or_else(|| {
176 bug!("can only highlight {} placeholders at a time", num_slots,)
178 *first_avail_slot = Some((region, number));
181 /// Convenience wrapper for `highlighting_region`.
182 pub fn highlighting_region_vid(&mut self, vid: ty::RegionVid, number: usize) {
183 self.highlighting_region(self.tcx.mk_region(ty::ReVar(vid)), number)
186 /// Returns `Some(n)` with the number to use for the given region, if any.
187 fn region_highlighted(&self, region: ty::Region<'tcx>) -> Option<usize> {
188 self.highlight_regions.iter().find_map(|h| match h {
189 Some((r, n)) if *r == region => Some(*n),
194 /// Highlight the given bound region.
195 /// We can only highlight one bound region at a time. See
196 /// the field `highlight_bound_region` for more detailed notes.
197 pub fn highlighting_bound_region(&mut self, br: ty::BoundRegionKind, number: usize) {
198 assert!(self.highlight_bound_region.is_none());
199 self.highlight_bound_region = Some((br, number));
203 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
204 pub trait PrettyPrinter<'tcx>:
211 DynExistential = Self,
215 /// Like `print_def_path` but for value paths.
219 substs: &'tcx [GenericArg<'tcx>],
220 ) -> Result<Self::Path, Self::Error> {
221 self.print_def_path(def_id, substs)
224 fn in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, Self::Error>
226 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
228 value.as_ref().skip_binder().print(self)
231 fn wrap_binder<T, F: FnOnce(&T, Self) -> Result<Self, fmt::Error>>(
233 value: &ty::Binder<'tcx, T>,
235 ) -> Result<Self, Self::Error>
237 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
239 f(value.as_ref().skip_binder(), self)
242 /// Prints comma-separated elements.
243 fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
245 T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
247 if let Some(first) = elems.next() {
248 self = first.print(self)?;
250 self.write_str(", ")?;
251 self = elem.print(self)?;
257 /// Prints `{f: t}` or `{f as t}` depending on the `cast` argument
260 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
261 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
263 ) -> Result<Self::Const, Self::Error> {
264 self.write_str("{")?;
266 self.write_str(conversion)?;
268 self.write_str("}")?;
272 /// Prints `<...>` around what `f` prints.
273 fn generic_delimiters(
275 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
276 ) -> Result<Self, Self::Error>;
278 /// Returns `true` if the region should be printed in
279 /// optional positions, e.g., `&'a T` or `dyn Tr + 'b`.
280 /// This is typically the case for all non-`'_` regions.
281 fn should_print_region(&self, region: ty::Region<'tcx>) -> bool;
283 // Defaults (should not be overridden):
285 /// If possible, this returns a global path resolving to `def_id` that is visible
286 /// from at least one local module, and returns `true`. If the crate defining `def_id` is
287 /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
288 fn try_print_visible_def_path(self, def_id: DefId) -> Result<(Self, bool), Self::Error> {
289 if NO_VISIBLE_PATH.with(|flag| flag.get()) {
290 return Ok((self, false));
293 let mut callers = Vec::new();
294 self.try_print_visible_def_path_recur(def_id, &mut callers)
297 /// Try to see if this path can be trimmed to a unique symbol name.
298 fn try_print_trimmed_def_path(
301 ) -> Result<(Self::Path, bool), Self::Error> {
302 if !self.tcx().sess.opts.unstable_opts.trim_diagnostic_paths
303 || matches!(self.tcx().sess.opts.trimmed_def_paths, TrimmedDefPaths::Never)
304 || NO_TRIMMED_PATH.with(|flag| flag.get())
305 || SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get())
307 return Ok((self, false));
310 match self.tcx().trimmed_def_paths(()).get(&def_id) {
311 None => Ok((self, false)),
313 self.write_str(symbol.as_str())?;
319 /// Does the work of `try_print_visible_def_path`, building the
320 /// full definition path recursively before attempting to
321 /// post-process it into the valid and visible version that
322 /// accounts for re-exports.
324 /// This method should only be called by itself or
325 /// `try_print_visible_def_path`.
327 /// `callers` is a chain of visible_parent's leading to `def_id`,
328 /// to support cycle detection during recursion.
330 /// This method returns false if we can't print the visible path, so
331 /// `print_def_path` can fall back on the item's real definition path.
332 fn try_print_visible_def_path_recur(
335 callers: &mut Vec<DefId>,
336 ) -> Result<(Self, bool), Self::Error> {
337 define_scoped_cx!(self);
339 debug!("try_print_visible_def_path: def_id={:?}", def_id);
341 // If `def_id` is a direct or injected extern crate, return the
342 // path to the crate followed by the path to the item within the crate.
343 if let Some(cnum) = def_id.as_crate_root() {
344 if cnum == LOCAL_CRATE {
345 return Ok((self.path_crate(cnum)?, true));
348 // In local mode, when we encounter a crate other than
349 // LOCAL_CRATE, execution proceeds in one of two ways:
351 // 1. For a direct dependency, where user added an
352 // `extern crate` manually, we put the `extern
353 // crate` as the parent. So you wind up with
354 // something relative to the current crate.
355 // 2. For an extern inferred from a path or an indirect crate,
356 // where there is no explicit `extern crate`, we just prepend
358 match self.tcx().extern_crate(def_id) {
359 Some(&ExternCrate { src, dependency_of, span, .. }) => match (src, dependency_of) {
360 (ExternCrateSource::Extern(def_id), LOCAL_CRATE) => {
361 // NOTE(eddyb) the only reason `span` might be dummy,
362 // that we're aware of, is that it's the `std`/`core`
363 // `extern crate` injected by default.
364 // FIXME(eddyb) find something better to key this on,
365 // or avoid ending up with `ExternCrateSource::Extern`,
366 // for the injected `std`/`core`.
368 return Ok((self.path_crate(cnum)?, true));
371 // Disable `try_print_trimmed_def_path` behavior within
372 // the `print_def_path` call, to avoid infinite recursion
373 // in cases where the `extern crate foo` has non-trivial
374 // parents, e.g. it's nested in `impl foo::Trait for Bar`
375 // (see also issues #55779 and #87932).
376 self = with_no_visible_paths!(self.print_def_path(def_id, &[])?);
378 return Ok((self, true));
380 (ExternCrateSource::Path, LOCAL_CRATE) => {
381 return Ok((self.path_crate(cnum)?, true));
386 return Ok((self.path_crate(cnum)?, true));
391 if def_id.is_local() {
392 return Ok((self, false));
395 let visible_parent_map = self.tcx().visible_parent_map(());
397 let mut cur_def_key = self.tcx().def_key(def_id);
398 debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
400 // For a constructor, we want the name of its parent rather than <unnamed>.
401 if let DefPathData::Ctor = cur_def_key.disambiguated_data.data {
406 .expect("`DefPathData::Ctor` / `VariantData` missing a parent"),
409 cur_def_key = self.tcx().def_key(parent);
412 let Some(visible_parent) = visible_parent_map.get(&def_id).cloned() else {
413 return Ok((self, false));
416 let actual_parent = self.tcx().opt_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` reexports 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.should_print_region(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().bound_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.should_print_verbose();
601 if let ty::TyVar(ty_vid) = infer_ty {
602 if let Some(name) = self.ty_infer_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!(print(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, repr) => {
625 let print_r = self.should_print_region(r);
630 ty::Dyn => p!("dyn "),
631 ty::DynStar => p!("dyn* "),
635 p!(" + ", print(r), ")");
638 ty::Foreign(def_id) => {
639 p!(print_def_path(def_id, &[]));
641 ty::Projection(ref data) => {
642 if !(self.should_print_verbose() || NO_QUERIES.with(|q| q.get()))
643 && self.tcx().def_kind(data.item_def_id) == DefKind::ImplTraitPlaceholder
645 return self.pretty_print_opaque_impl_type(data.item_def_id, data.substs);
650 ty::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
651 ty::Opaque(def_id, substs) => {
652 // FIXME(eddyb) print this with `print_def_path`.
653 // We use verbose printing in 'NO_QUERIES' mode, to
654 // avoid needing to call `predicates_of`. This should
655 // only affect certain debug messages (e.g. messages printed
656 // from `rustc_middle::ty` during the computation of `tcx.predicates_of`),
657 // and should have no effect on any compiler output.
658 if self.should_print_verbose() || NO_QUERIES.with(|q| q.get()) {
659 p!(write("Opaque({:?}, {:?})", def_id, substs));
663 let parent = self.tcx().parent(def_id);
664 match self.tcx().def_kind(parent) {
665 DefKind::TyAlias | DefKind::AssocTy => {
666 if let ty::Opaque(d, _) = *self.tcx().type_of(parent).kind() {
668 // If the type alias directly starts with the `impl` of the
669 // opaque type we're printing, then skip the `::{opaque#1}`.
670 p!(print_def_path(parent, substs));
674 // Complex opaque type, e.g. `type Foo = (i32, impl Debug);`
675 p!(print_def_path(def_id, substs));
678 _ => return self.pretty_print_opaque_impl_type(def_id, substs),
681 ty::Str => p!("str"),
682 ty::Generator(did, substs, movability) => {
685 hir::Movability::Movable => {}
686 hir::Movability::Static => p!("static "),
689 if !self.should_print_verbose() {
691 // FIXME(eddyb) should use `def_span`.
692 if let Some(did) = did.as_local() {
693 let span = self.tcx().def_span(did);
696 // This may end up in stderr diagnostics but it may also be emitted
697 // into MIR. Hence we use the remapped path if available
698 self.tcx().sess.source_map().span_to_embeddable_string(span)
701 p!(write("@"), print_def_path(did, substs));
704 p!(print_def_path(did, substs));
706 if !substs.as_generator().is_valid() {
709 self = self.comma_sep(substs.as_generator().upvar_tys())?;
713 if substs.as_generator().is_valid() {
714 p!(" ", print(substs.as_generator().witness()));
720 ty::GeneratorWitness(types) => {
721 p!(in_binder(&types));
723 ty::Closure(did, substs) => {
725 if !self.should_print_verbose() {
726 p!(write("closure"));
727 // FIXME(eddyb) should use `def_span`.
728 if let Some(did) = did.as_local() {
729 if self.tcx().sess.opts.unstable_opts.span_free_formats {
730 p!("@", print_def_path(did.to_def_id(), substs));
732 let span = self.tcx().def_span(did);
735 // This may end up in stderr diagnostics but it may also be emitted
736 // into MIR. Hence we use the remapped path if available
737 self.tcx().sess.source_map().span_to_embeddable_string(span)
741 p!(write("@"), print_def_path(did, substs));
744 p!(print_def_path(did, substs));
745 if !substs.as_closure().is_valid() {
746 p!(" closure_substs=(unavailable)");
747 p!(write(" substs={:?}", substs));
749 p!(" closure_kind_ty=", print(substs.as_closure().kind_ty()));
751 " closure_sig_as_fn_ptr_ty=",
752 print(substs.as_closure().sig_as_fn_ptr_ty())
755 self = self.comma_sep(substs.as_closure().upvar_tys())?;
761 ty::Array(ty, sz) => {
762 p!("[", print(ty), "; ");
763 if self.should_print_verbose() {
764 p!(write("{:?}", sz));
765 } else if let ty::ConstKind::Unevaluated(..) = sz.kind() {
766 // Do not try to evaluate unevaluated constants. If we are const evaluating an
767 // array length anon const, rustc will (with debug assertions) print the
768 // constant's path. Which will end up here again.
770 } else if let Some(n) = sz.kind().try_to_bits(self.tcx().data_layout.pointer_size) {
772 } else if let ty::ConstKind::Param(param) = sz.kind() {
779 ty::Slice(ty) => p!("[", print(ty), "]"),
785 fn pretty_print_opaque_impl_type(
788 substs: &'tcx ty::List<ty::GenericArg<'tcx>>,
789 ) -> Result<Self::Type, Self::Error> {
790 let tcx = self.tcx();
792 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
793 // by looking up the projections associated with the def_id.
794 let bounds = tcx.bound_explicit_item_bounds(def_id);
796 let mut traits = FxIndexMap::default();
797 let mut fn_traits = FxIndexMap::default();
798 let mut is_sized = false;
799 let mut lifetimes = SmallVec::<[ty::Region<'tcx>; 1]>::new();
801 for (predicate, _) in bounds.subst_iter_copied(tcx, substs) {
802 let bound_predicate = predicate.kind();
804 match bound_predicate.skip_binder() {
805 ty::PredicateKind::Trait(pred) => {
806 let trait_ref = bound_predicate.rebind(pred.trait_ref);
808 // Don't print + Sized, but rather + ?Sized if absent.
809 if Some(trait_ref.def_id()) == tcx.lang_items().sized_trait() {
814 self.insert_trait_and_projection(trait_ref, None, &mut traits, &mut fn_traits);
816 ty::PredicateKind::Projection(pred) => {
817 let proj_ref = bound_predicate.rebind(pred);
818 let trait_ref = proj_ref.required_poly_trait_ref(tcx);
820 // Projection type entry -- the def-id for naming, and the ty.
821 let proj_ty = (proj_ref.projection_def_id(), proj_ref.term());
823 self.insert_trait_and_projection(
830 ty::PredicateKind::TypeOutlives(outlives) => {
831 lifetimes.push(outlives.1);
837 write!(self, "impl ")?;
839 let mut first = true;
840 // Insert parenthesis around (Fn(A, B) -> C) if the opaque ty has more than one other trait
841 let paren_needed = fn_traits.len() > 1 || traits.len() > 0 || !is_sized;
843 for (fn_once_trait_ref, entry) in fn_traits {
844 write!(self, "{}", if first { "" } else { " + " })?;
845 write!(self, "{}", if paren_needed { "(" } else { "" })?;
847 self = self.wrap_binder(&fn_once_trait_ref, |trait_ref, mut cx| {
848 define_scoped_cx!(cx);
849 // Get the (single) generic ty (the args) of this FnOnce trait ref.
850 let generics = tcx.generics_of(trait_ref.def_id);
851 let args = generics.own_substs_no_defaults(tcx, trait_ref.substs);
853 match (entry.return_ty, args[0].expect_ty()) {
854 // We can only print `impl Fn() -> ()` if we have a tuple of args and we recorded
856 (Some(return_ty), arg_tys) if matches!(arg_tys.kind(), ty::Tuple(_)) => {
857 let name = if entry.fn_trait_ref.is_some() {
859 } else if entry.fn_mut_trait_ref.is_some() {
865 p!(write("{}(", name));
867 for (idx, ty) in arg_tys.tuple_fields().iter().enumerate() {
875 if let Some(ty) = return_ty.skip_binder().ty() {
877 p!(" -> ", print(return_ty));
880 p!(write("{}", if paren_needed { ")" } else { "" }));
884 // If we got here, we can't print as a `impl Fn(A, B) -> C`. Just record the
885 // trait_refs we collected in the OpaqueFnEntry as normal trait refs.
887 if entry.has_fn_once {
888 traits.entry(fn_once_trait_ref).or_default().extend(
889 // Group the return ty with its def id, if we had one.
892 .map(|ty| (tcx.lang_items().fn_once_output().unwrap(), ty)),
895 if let Some(trait_ref) = entry.fn_mut_trait_ref {
896 traits.entry(trait_ref).or_default();
898 if let Some(trait_ref) = entry.fn_trait_ref {
899 traits.entry(trait_ref).or_default();
908 // Print the rest of the trait types (that aren't Fn* family of traits)
909 for (trait_ref, assoc_items) in traits {
910 write!(self, "{}", if first { "" } else { " + " })?;
912 self = self.wrap_binder(&trait_ref, |trait_ref, mut cx| {
913 define_scoped_cx!(cx);
914 p!(print(trait_ref.print_only_trait_name()));
916 let generics = tcx.generics_of(trait_ref.def_id);
917 let args = generics.own_substs_no_defaults(tcx, trait_ref.substs);
919 if !args.is_empty() || !assoc_items.is_empty() {
920 let mut first = true;
932 for (assoc_item_def_id, term) in assoc_items {
933 // Skip printing `<[generator@] as Generator<_>>::Return` from async blocks,
934 // unless we can find out what generator return type it comes from.
935 let term = if let Some(ty) = term.skip_binder().ty()
936 && let ty::Projection(proj) = ty.kind()
937 && let Some(assoc) = tcx.opt_associated_item(proj.item_def_id)
938 && assoc.trait_container(tcx) == tcx.lang_items().gen_trait()
939 && assoc.name == rustc_span::sym::Return
941 if let ty::Generator(_, substs, _) = substs.type_at(0).kind() {
942 let return_ty = substs.as_generator().return_ty();
943 if !return_ty.is_ty_var() {
962 p!(write("{} = ", tcx.associated_item(assoc_item_def_id).name));
964 match term.unpack() {
965 TermKind::Ty(ty) => p!(print(ty)),
966 TermKind::Const(c) => p!(print(c)),
981 write!(self, "{}?Sized", if first { "" } else { " + " })?;
983 write!(self, "Sized")?;
986 for re in lifetimes {
987 write!(self, " + ")?;
988 self = self.print_region(re)?;
994 /// Insert the trait ref and optionally a projection type associated with it into either the
995 /// traits map or fn_traits map, depending on if the trait is in the Fn* family of traits.
996 fn insert_trait_and_projection(
998 trait_ref: ty::PolyTraitRef<'tcx>,
999 proj_ty: Option<(DefId, ty::Binder<'tcx, Term<'tcx>>)>,
1000 traits: &mut FxIndexMap<
1001 ty::PolyTraitRef<'tcx>,
1002 FxIndexMap<DefId, ty::Binder<'tcx, Term<'tcx>>>,
1004 fn_traits: &mut FxIndexMap<ty::PolyTraitRef<'tcx>, OpaqueFnEntry<'tcx>>,
1006 let trait_def_id = trait_ref.def_id();
1008 // If our trait_ref is FnOnce or any of its children, project it onto the parent FnOnce
1009 // super-trait ref and record it there.
1010 if let Some(fn_once_trait) = self.tcx().lang_items().fn_once_trait() {
1011 // If we have a FnOnce, then insert it into
1012 if trait_def_id == fn_once_trait {
1013 let entry = fn_traits.entry(trait_ref).or_default();
1014 // Optionally insert the return_ty as well.
1015 if let Some((_, ty)) = proj_ty {
1016 entry.return_ty = Some(ty);
1018 entry.has_fn_once = true;
1020 } else if Some(trait_def_id) == self.tcx().lang_items().fn_mut_trait() {
1021 let super_trait_ref = crate::traits::util::supertraits(self.tcx(), trait_ref)
1022 .find(|super_trait_ref| super_trait_ref.def_id() == fn_once_trait)
1025 fn_traits.entry(super_trait_ref).or_default().fn_mut_trait_ref = Some(trait_ref);
1027 } else if Some(trait_def_id) == self.tcx().lang_items().fn_trait() {
1028 let super_trait_ref = crate::traits::util::supertraits(self.tcx(), trait_ref)
1029 .find(|super_trait_ref| super_trait_ref.def_id() == fn_once_trait)
1032 fn_traits.entry(super_trait_ref).or_default().fn_trait_ref = Some(trait_ref);
1037 // Otherwise, just group our traits and projection types.
1038 traits.entry(trait_ref).or_default().extend(proj_ty);
1041 fn pretty_print_bound_var(
1043 debruijn: ty::DebruijnIndex,
1045 ) -> Result<(), Self::Error> {
1046 if debruijn == ty::INNERMOST {
1047 write!(self, "^{}", var.index())
1049 write!(self, "^{}_{}", debruijn.index(), var.index())
1053 fn ty_infer_name(&self, _: ty::TyVid) -> Option<Symbol> {
1057 fn const_infer_name(&self, _: ty::ConstVid<'tcx>) -> Option<Symbol> {
1061 fn pretty_print_dyn_existential(
1063 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1064 ) -> Result<Self::DynExistential, Self::Error> {
1065 // Generate the main trait ref, including associated types.
1066 let mut first = true;
1068 if let Some(principal) = predicates.principal() {
1069 self = self.wrap_binder(&principal, |principal, mut cx| {
1070 define_scoped_cx!(cx);
1071 p!(print_def_path(principal.def_id, &[]));
1073 let mut resugared = false;
1075 // Special-case `Fn(...) -> ...` and re-sugar it.
1076 let fn_trait_kind = cx.tcx().fn_trait_kind_from_lang_item(principal.def_id);
1077 if !cx.should_print_verbose() && fn_trait_kind.is_some() {
1078 if let ty::Tuple(tys) = principal.substs.type_at(0).kind() {
1079 let mut projections = predicates.projection_bounds();
1080 if let (Some(proj), None) = (projections.next(), projections.next()) {
1084 proj.skip_binder().term.ty().expect("Return type was a const")
1091 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
1092 // in order to place the projections inside the `<...>`.
1094 // Use a type that can't appear in defaults of type parameters.
1095 let dummy_cx = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1096 let principal = principal.with_self_ty(cx.tcx(), dummy_cx);
1100 .generics_of(principal.def_id)
1101 .own_substs_no_defaults(cx.tcx(), principal.substs);
1103 let mut projections = predicates.projection_bounds();
1105 let mut args = args.iter().cloned();
1106 let arg0 = args.next();
1107 let projection0 = projections.next();
1108 if arg0.is_some() || projection0.is_some() {
1109 let args = arg0.into_iter().chain(args);
1110 let projections = projection0.into_iter().chain(projections);
1112 p!(generic_delimiters(|mut cx| {
1113 cx = cx.comma_sep(args)?;
1114 if arg0.is_some() && projection0.is_some() {
1117 cx.comma_sep(projections)
1127 define_scoped_cx!(self);
1130 // FIXME(eddyb) avoid printing twice (needed to ensure
1131 // that the auto traits are sorted *and* printed via cx).
1132 let mut auto_traits: Vec<_> = predicates.auto_traits().collect();
1134 // The auto traits come ordered by `DefPathHash`. While
1135 // `DefPathHash` is *stable* in the sense that it depends on
1136 // neither the host nor the phase of the moon, it depends
1137 // "pseudorandomly" on the compiler version and the target.
1139 // To avoid causing instabilities in compiletest
1140 // output, sort the auto-traits alphabetically.
1141 auto_traits.sort_by_cached_key(|did| with_no_trimmed_paths!(self.tcx().def_path_str(*did)));
1143 for def_id in auto_traits {
1149 p!(print_def_path(def_id, &[]));
1157 inputs: &[Ty<'tcx>],
1160 ) -> Result<Self, Self::Error> {
1161 define_scoped_cx!(self);
1163 p!("(", comma_sep(inputs.iter().copied()));
1165 if !inputs.is_empty() {
1171 if !output.is_unit() {
1172 p!(" -> ", print(output));
1178 fn pretty_print_const(
1180 ct: ty::Const<'tcx>,
1182 ) -> Result<Self::Const, Self::Error> {
1183 define_scoped_cx!(self);
1185 if self.should_print_verbose() {
1186 p!(write("Const({:?}: {:?})", ct.kind(), ct.ty()));
1190 macro_rules! print_underscore {
1193 self = self.typed_value(
1198 |this| this.print_type(ct.ty()),
1208 ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, substs }) => {
1209 match self.tcx().def_kind(def.did) {
1210 DefKind::Static(..) | DefKind::Const | DefKind::AssocConst => {
1211 p!(print_value_path(def.did, substs))
1215 let span = self.tcx().def_span(def.did);
1216 if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span) {
1217 p!(write("{}", snip))
1227 ty::ConstKind::Infer(infer_ct) => {
1229 ty::InferConst::Var(ct_vid)
1230 if let Some(name) = self.const_infer_name(ct_vid) =>
1231 p!(write("{}", name)),
1232 _ => print_underscore!(),
1235 ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)),
1236 ty::ConstKind::Value(value) => {
1237 return self.pretty_print_const_valtree(value, ct.ty(), print_ty);
1240 ty::ConstKind::Bound(debruijn, bound_var) => {
1241 self.pretty_print_bound_var(debruijn, bound_var)?
1243 ty::ConstKind::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
1244 ty::ConstKind::Error(_) => p!("[const error]"),
1249 fn pretty_print_const_scalar(
1254 ) -> Result<Self::Const, Self::Error> {
1256 Scalar::Ptr(ptr, _size) => self.pretty_print_const_scalar_ptr(ptr, ty, print_ty),
1257 Scalar::Int(int) => self.pretty_print_const_scalar_int(int, ty, print_ty),
1261 fn pretty_print_const_scalar_ptr(
1266 ) -> Result<Self::Const, Self::Error> {
1267 define_scoped_cx!(self);
1269 let (alloc_id, offset) = ptr.into_parts();
1271 // Byte strings (&[u8; N])
1272 ty::Ref(_, inner, _) => {
1273 if let ty::Array(elem, len) = inner.kind() {
1274 if let ty::Uint(ty::UintTy::U8) = elem.kind() {
1275 if let ty::ConstKind::Value(ty::ValTree::Leaf(int)) = len.kind() {
1276 match self.tcx().try_get_global_alloc(alloc_id) {
1277 Some(GlobalAlloc::Memory(alloc)) => {
1278 let len = int.assert_bits(self.tcx().data_layout.pointer_size);
1280 AllocRange { start: offset, size: Size::from_bytes(len) };
1281 if let Ok(byte_str) =
1282 alloc.inner().get_bytes_strip_provenance(&self.tcx(), range)
1284 p!(pretty_print_byte_str(byte_str))
1286 p!("<too short allocation>")
1289 // FIXME: for statics, vtables, and functions, we could in principle print more detail.
1290 Some(GlobalAlloc::Static(def_id)) => {
1291 p!(write("<static({:?})>", def_id))
1293 Some(GlobalAlloc::Function(_)) => p!("<function>"),
1294 Some(GlobalAlloc::VTable(..)) => p!("<vtable>"),
1295 None => p!("<dangling pointer>"),
1303 // FIXME: We should probably have a helper method to share code with the "Byte strings"
1304 // printing above (which also has to handle pointers to all sorts of things).
1305 if let Some(GlobalAlloc::Function(instance)) =
1306 self.tcx().try_get_global_alloc(alloc_id)
1308 self = self.typed_value(
1309 |this| this.print_value_path(instance.def_id(), instance.substs),
1310 |this| this.print_type(ty),
1318 // Any pointer values not covered by a branch above
1319 self = self.pretty_print_const_pointer(ptr, ty, print_ty)?;
1323 fn pretty_print_const_scalar_int(
1328 ) -> Result<Self::Const, Self::Error> {
1329 define_scoped_cx!(self);
1333 ty::Bool if int == ScalarInt::FALSE => p!("false"),
1334 ty::Bool if int == ScalarInt::TRUE => p!("true"),
1336 ty::Float(ty::FloatTy::F32) => {
1337 p!(write("{}f32", Single::try_from(int).unwrap()))
1339 ty::Float(ty::FloatTy::F64) => {
1340 p!(write("{}f64", Double::try_from(int).unwrap()))
1343 ty::Uint(_) | ty::Int(_) => {
1345 ConstInt::new(int, matches!(ty.kind(), ty::Int(_)), ty.is_ptr_sized_integral());
1346 if print_ty { p!(write("{:#?}", int)) } else { p!(write("{:?}", int)) }
1349 ty::Char if char::try_from(int).is_ok() => {
1350 p!(write("{:?}", char::try_from(int).unwrap()))
1353 ty::Ref(..) | ty::RawPtr(_) | ty::FnPtr(_) => {
1354 let data = int.assert_bits(self.tcx().data_layout.pointer_size);
1355 self = self.typed_value(
1357 write!(this, "0x{:x}", data)?;
1360 |this| this.print_type(ty),
1364 // Nontrivial types with scalar bit representation
1366 let print = |mut this: Self| {
1367 if int.size() == Size::ZERO {
1368 write!(this, "transmute(())")?;
1370 write!(this, "transmute(0x{:x})", int)?;
1374 self = if print_ty {
1375 self.typed_value(print, |this| this.print_type(ty), ": ")?
1384 /// This is overridden for MIR printing because we only want to hide alloc ids from users, not
1385 /// from MIR where it is actually useful.
1386 fn pretty_print_const_pointer<Prov: Provenance>(
1391 ) -> Result<Self::Const, Self::Error> {
1395 this.write_str("&_")?;
1398 |this| this.print_type(ty),
1402 self.write_str("&_")?;
1407 fn pretty_print_byte_str(mut self, byte_str: &'tcx [u8]) -> Result<Self::Const, Self::Error> {
1408 write!(self, "b\"{}\"", byte_str.escape_ascii())?;
1412 fn pretty_print_const_valtree(
1414 valtree: ty::ValTree<'tcx>,
1417 ) -> Result<Self::Const, Self::Error> {
1418 define_scoped_cx!(self);
1420 if self.should_print_verbose() {
1421 p!(write("ValTree({:?}: ", valtree), print(ty), ")");
1425 let u8_type = self.tcx().types.u8;
1426 match (valtree, ty.kind()) {
1427 (ty::ValTree::Branch(_), ty::Ref(_, inner_ty, _)) => match inner_ty.kind() {
1428 ty::Slice(t) if *t == u8_type => {
1429 let bytes = valtree.try_to_raw_bytes(self.tcx(), ty).unwrap_or_else(|| {
1431 "expected to convert valtree {:?} to raw bytes for type {:?}",
1436 return self.pretty_print_byte_str(bytes);
1439 let bytes = valtree.try_to_raw_bytes(self.tcx(), ty).unwrap_or_else(|| {
1440 bug!("expected to convert valtree to raw bytes for type {:?}", ty)
1442 p!(write("{:?}", String::from_utf8_lossy(bytes)));
1447 p!(pretty_print_const_valtree(valtree, *inner_ty, print_ty));
1451 (ty::ValTree::Branch(_), ty::Array(t, _)) if *t == u8_type => {
1452 let bytes = valtree.try_to_raw_bytes(self.tcx(), ty).unwrap_or_else(|| {
1453 bug!("expected to convert valtree to raw bytes for type {:?}", t)
1456 p!(pretty_print_byte_str(bytes));
1459 // Aggregates, printed as array/tuple/struct/variant construction syntax.
1460 (ty::ValTree::Branch(_), ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) => {
1462 self.tcx().destructure_const(ty::Const::from_value(self.tcx(), valtree, ty));
1463 let fields = contents.fields.iter().copied();
1466 p!("[", comma_sep(fields), "]");
1469 p!("(", comma_sep(fields));
1470 if contents.fields.len() == 1 {
1475 ty::Adt(def, _) if def.variants().is_empty() => {
1476 self = self.typed_value(
1478 write!(this, "unreachable()")?;
1481 |this| this.print_type(ty),
1485 ty::Adt(def, substs) => {
1487 contents.variant.expect("destructed const of adt without variant idx");
1488 let variant_def = &def.variant(variant_idx);
1489 p!(print_value_path(variant_def.def_id, substs));
1490 match variant_def.ctor_kind() {
1491 Some(CtorKind::Const) => {}
1492 Some(CtorKind::Fn) => {
1493 p!("(", comma_sep(fields), ")");
1497 let mut first = true;
1498 for (field_def, field) in iter::zip(&variant_def.fields, fields) {
1502 p!(write("{}: ", field_def.name), print(field));
1509 _ => unreachable!(),
1513 (ty::ValTree::Leaf(leaf), ty::Ref(_, inner_ty, _)) => {
1515 return self.pretty_print_const_scalar_int(leaf, *inner_ty, print_ty);
1517 (ty::ValTree::Leaf(leaf), _) => {
1518 return self.pretty_print_const_scalar_int(leaf, ty, print_ty);
1520 // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
1521 // their fields instead of just dumping the memory.
1526 if valtree == ty::ValTree::zst() {
1529 p!(write("{:?}", valtree));
1532 p!(": ", print(ty));
1537 fn pretty_closure_as_impl(
1539 closure: ty::ClosureSubsts<'tcx>,
1540 ) -> Result<Self::Const, Self::Error> {
1541 let sig = closure.sig();
1542 let kind = closure.kind_ty().to_opt_closure_kind().unwrap_or(ty::ClosureKind::Fn);
1544 write!(self, "impl ")?;
1545 self.wrap_binder(&sig, |sig, mut cx| {
1546 define_scoped_cx!(cx);
1548 p!(print(kind), "(");
1549 for (i, arg) in sig.inputs()[0].tuple_fields().iter().enumerate() {
1557 if !sig.output().is_unit() {
1558 p!(" -> ", print(sig.output()));
1565 fn should_print_verbose(&self) -> bool {
1566 self.tcx().sess.verbose()
1570 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
1571 pub struct FmtPrinter<'a, 'tcx>(Box<FmtPrinterData<'a, 'tcx>>);
1573 pub struct FmtPrinterData<'a, 'tcx> {
1579 pub print_alloc_ids: bool,
1581 // set of all named (non-anonymous) region names
1582 used_region_names: FxHashSet<Symbol>,
1584 region_index: usize,
1585 binder_depth: usize,
1586 printed_type_count: usize,
1587 type_length_limit: Limit,
1590 pub region_highlight_mode: RegionHighlightMode<'tcx>,
1592 pub ty_infer_name_resolver: Option<Box<dyn Fn(ty::TyVid) -> Option<Symbol> + 'a>>,
1593 pub const_infer_name_resolver: Option<Box<dyn Fn(ty::ConstVid<'tcx>) -> Option<Symbol> + 'a>>,
1596 impl<'a, 'tcx> Deref for FmtPrinter<'a, 'tcx> {
1597 type Target = FmtPrinterData<'a, 'tcx>;
1598 fn deref(&self) -> &Self::Target {
1603 impl DerefMut for FmtPrinter<'_, '_> {
1604 fn deref_mut(&mut self) -> &mut Self::Target {
1609 impl<'a, 'tcx> FmtPrinter<'a, 'tcx> {
1610 pub fn new(tcx: TyCtxt<'tcx>, ns: Namespace) -> Self {
1611 Self::new_with_limit(tcx, ns, tcx.type_length_limit())
1614 pub fn new_with_limit(tcx: TyCtxt<'tcx>, ns: Namespace, type_length_limit: Limit) -> Self {
1615 FmtPrinter(Box::new(FmtPrinterData {
1617 // Estimated reasonable capacity to allocate upfront based on a few
1619 fmt: String::with_capacity(64),
1621 in_value: ns == Namespace::ValueNS,
1622 print_alloc_ids: false,
1623 used_region_names: Default::default(),
1626 printed_type_count: 0,
1629 region_highlight_mode: RegionHighlightMode::new(tcx),
1630 ty_infer_name_resolver: None,
1631 const_infer_name_resolver: None,
1635 pub fn into_buffer(self) -> String {
1640 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1641 // (but also some things just print a `DefId` generally so maybe we need this?)
1642 fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
1643 match tcx.def_key(def_id).disambiguated_data.data {
1644 DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::ImplTrait => {
1648 DefPathData::ValueNs(..)
1649 | DefPathData::AnonConst
1650 | DefPathData::ClosureExpr
1651 | DefPathData::Ctor => Namespace::ValueNS,
1653 DefPathData::MacroNs(..) => Namespace::MacroNS,
1655 _ => Namespace::TypeNS,
1659 impl<'t> TyCtxt<'t> {
1660 /// Returns a string identifying this `DefId`. This string is
1661 /// suitable for user output.
1662 pub fn def_path_str(self, def_id: DefId) -> String {
1663 self.def_path_str_with_substs(def_id, &[])
1666 pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1667 let ns = guess_def_namespace(self, def_id);
1668 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1669 FmtPrinter::new(self, ns).print_def_path(def_id, substs).unwrap().into_buffer()
1672 pub fn value_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1673 let ns = guess_def_namespace(self, def_id);
1674 debug!("value_path_str: def_id={:?}, ns={:?}", def_id, ns);
1675 FmtPrinter::new(self, ns).print_value_path(def_id, substs).unwrap().into_buffer()
1679 impl fmt::Write for FmtPrinter<'_, '_> {
1680 fn write_str(&mut self, s: &str) -> fmt::Result {
1681 self.fmt.push_str(s);
1686 impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> {
1687 type Error = fmt::Error;
1692 type DynExistential = Self;
1695 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
1702 substs: &'tcx [GenericArg<'tcx>],
1703 ) -> Result<Self::Path, Self::Error> {
1704 define_scoped_cx!(self);
1706 if substs.is_empty() {
1707 match self.try_print_trimmed_def_path(def_id)? {
1708 (cx, true) => return Ok(cx),
1709 (cx, false) => self = cx,
1712 match self.try_print_visible_def_path(def_id)? {
1713 (cx, true) => return Ok(cx),
1714 (cx, false) => self = cx,
1718 let key = self.tcx.def_key(def_id);
1719 if let DefPathData::Impl = key.disambiguated_data.data {
1720 // Always use types for non-local impls, where types are always
1721 // available, and filename/line-number is mostly uninteresting.
1722 let use_types = !def_id.is_local() || {
1723 // Otherwise, use filename/line-number if forced.
1724 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1729 // If no type info is available, fall back to
1730 // pretty printing some span information. This should
1731 // only occur very early in the compiler pipeline.
1732 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1733 let span = self.tcx.def_span(def_id);
1735 self = self.print_def_path(parent_def_id, &[])?;
1737 // HACK(eddyb) copy of `path_append` to avoid
1738 // constructing a `DisambiguatedDefPathData`.
1739 if !self.empty_path {
1740 write!(self, "::")?;
1745 // This may end up in stderr diagnostics but it may also be emitted
1746 // into MIR. Hence we use the remapped path if available
1747 self.tcx.sess.source_map().span_to_embeddable_string(span)
1749 self.empty_path = false;
1755 self.default_print_def_path(def_id, substs)
1758 fn print_region(self, region: ty::Region<'tcx>) -> Result<Self::Region, Self::Error> {
1759 self.pretty_print_region(region)
1762 fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1763 if self.type_length_limit.value_within_limit(self.printed_type_count) {
1764 self.printed_type_count += 1;
1765 self.pretty_print_type(ty)
1767 self.truncated = true;
1768 write!(self, "...")?;
1773 fn print_dyn_existential(
1775 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1776 ) -> Result<Self::DynExistential, Self::Error> {
1777 self.pretty_print_dyn_existential(predicates)
1780 fn print_const(self, ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1781 self.pretty_print_const(ct, false)
1784 fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1785 self.empty_path = true;
1786 if cnum == LOCAL_CRATE {
1787 if self.tcx.sess.rust_2018() {
1788 // We add the `crate::` keyword on Rust 2018, only when desired.
1789 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1790 write!(self, "{}", kw::Crate)?;
1791 self.empty_path = false;
1795 write!(self, "{}", self.tcx.crate_name(cnum))?;
1796 self.empty_path = false;
1804 trait_ref: Option<ty::TraitRef<'tcx>>,
1805 ) -> Result<Self::Path, Self::Error> {
1806 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1807 self.empty_path = false;
1811 fn path_append_impl(
1813 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1814 _disambiguated_data: &DisambiguatedDefPathData,
1816 trait_ref: Option<ty::TraitRef<'tcx>>,
1817 ) -> Result<Self::Path, Self::Error> {
1818 self = self.pretty_path_append_impl(
1820 cx = print_prefix(cx)?;
1830 self.empty_path = false;
1836 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1837 disambiguated_data: &DisambiguatedDefPathData,
1838 ) -> Result<Self::Path, Self::Error> {
1839 self = print_prefix(self)?;
1841 // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
1842 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
1846 let name = disambiguated_data.data.name();
1847 if !self.empty_path {
1848 write!(self, "::")?;
1851 if let DefPathDataName::Named(name) = name {
1852 if Ident::with_dummy_span(name).is_raw_guess() {
1853 write!(self, "r#")?;
1857 let verbose = self.should_print_verbose();
1858 disambiguated_data.fmt_maybe_verbose(&mut self, verbose)?;
1860 self.empty_path = false;
1865 fn path_generic_args(
1867 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1868 args: &[GenericArg<'tcx>],
1869 ) -> Result<Self::Path, Self::Error> {
1870 self = print_prefix(self)?;
1872 if args.first().is_some() {
1874 write!(self, "::")?;
1876 self.generic_delimiters(|cx| cx.comma_sep(args.iter().cloned()))
1883 impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> {
1884 fn ty_infer_name(&self, id: ty::TyVid) -> Option<Symbol> {
1885 self.0.ty_infer_name_resolver.as_ref().and_then(|func| func(id))
1888 fn const_infer_name(&self, id: ty::ConstVid<'tcx>) -> Option<Symbol> {
1889 self.0.const_infer_name_resolver.as_ref().and_then(|func| func(id))
1892 fn print_value_path(
1895 substs: &'tcx [GenericArg<'tcx>],
1896 ) -> Result<Self::Path, Self::Error> {
1897 let was_in_value = std::mem::replace(&mut self.in_value, true);
1898 self = self.print_def_path(def_id, substs)?;
1899 self.in_value = was_in_value;
1904 fn in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, Self::Error>
1906 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1908 self.pretty_in_binder(value)
1911 fn wrap_binder<T, C: FnOnce(&T, Self) -> Result<Self, Self::Error>>(
1913 value: &ty::Binder<'tcx, T>,
1915 ) -> Result<Self, Self::Error>
1917 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1919 self.pretty_wrap_binder(value, f)
1924 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1925 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
1927 ) -> Result<Self::Const, Self::Error> {
1928 self.write_str("{")?;
1930 self.write_str(conversion)?;
1931 let was_in_value = std::mem::replace(&mut self.in_value, false);
1933 self.in_value = was_in_value;
1934 self.write_str("}")?;
1938 fn generic_delimiters(
1940 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1941 ) -> Result<Self, Self::Error> {
1944 let was_in_value = std::mem::replace(&mut self.in_value, false);
1945 let mut inner = f(self)?;
1946 inner.in_value = was_in_value;
1948 write!(inner, ">")?;
1952 fn should_print_region(&self, region: ty::Region<'tcx>) -> bool {
1953 let highlight = self.region_highlight_mode;
1954 if highlight.region_highlighted(region).is_some() {
1958 if self.should_print_verbose() {
1962 let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
1965 ty::ReEarlyBound(ref data) => {
1966 data.name != kw::Empty && data.name != kw::UnderscoreLifetime
1969 ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
1970 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1971 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1972 if let ty::BrNamed(_, name) = br {
1973 if name != kw::Empty && name != kw::UnderscoreLifetime {
1978 if let Some((region, _)) = highlight.highlight_bound_region {
1987 ty::ReVar(_) if identify_regions => true,
1989 ty::ReVar(_) | ty::ReErased => false,
1991 ty::ReStatic => true,
1995 fn pretty_print_const_pointer<Prov: Provenance>(
2000 ) -> Result<Self::Const, Self::Error> {
2001 let print = |mut this: Self| {
2002 define_scoped_cx!(this);
2003 if this.print_alloc_ids {
2004 p!(write("{:?}", p));
2011 self.typed_value(print, |this| this.print_type(ty), ": ")
2018 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
2019 impl<'tcx> FmtPrinter<'_, 'tcx> {
2020 pub fn pretty_print_region(mut self, region: ty::Region<'tcx>) -> Result<Self, fmt::Error> {
2021 define_scoped_cx!(self);
2023 // Watch out for region highlights.
2024 let highlight = self.region_highlight_mode;
2025 if let Some(n) = highlight.region_highlighted(region) {
2026 p!(write("'{}", n));
2030 if self.should_print_verbose() {
2031 p!(write("{:?}", region));
2035 let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
2037 // These printouts are concise. They do not contain all the information
2038 // the user might want to diagnose an error, but there is basically no way
2039 // to fit that into a short string. Hence the recommendation to use
2040 // `explain_region()` or `note_and_explain_region()`.
2042 ty::ReEarlyBound(ref data) => {
2043 if data.name != kw::Empty {
2044 p!(write("{}", data.name));
2048 ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
2049 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
2050 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
2051 if let ty::BrNamed(_, name) = br {
2052 if name != kw::Empty && name != kw::UnderscoreLifetime {
2053 p!(write("{}", name));
2058 if let Some((region, counter)) = highlight.highlight_bound_region {
2060 p!(write("'{}", counter));
2065 ty::ReVar(region_vid) if identify_regions => {
2066 p!(write("{:?}", region_vid));
2083 /// Folds through bound vars and placeholders, naming them
2084 struct RegionFolder<'a, 'tcx> {
2086 current_index: ty::DebruijnIndex,
2087 region_map: BTreeMap<ty::BoundRegion, ty::Region<'tcx>>,
2090 Option<ty::DebruijnIndex>, // Debruijn index of the folded late-bound region
2091 ty::DebruijnIndex, // Index corresponding to binder level
2093 ) -> ty::Region<'tcx>
2098 impl<'a, 'tcx> ty::TypeFolder<'tcx> for RegionFolder<'a, 'tcx> {
2099 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
2103 fn fold_binder<T: TypeFoldable<'tcx>>(
2105 t: ty::Binder<'tcx, T>,
2106 ) -> ty::Binder<'tcx, T> {
2107 self.current_index.shift_in(1);
2108 let t = t.super_fold_with(self);
2109 self.current_index.shift_out(1);
2113 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
2115 _ if t.has_vars_bound_at_or_above(self.current_index) || t.has_placeholders() => {
2116 return t.super_fold_with(self);
2123 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
2124 let name = &mut self.name;
2125 let region = match *r {
2126 ty::ReLateBound(db, br) if db >= self.current_index => {
2127 *self.region_map.entry(br).or_insert_with(|| name(Some(db), self.current_index, br))
2129 ty::RePlaceholder(ty::PlaceholderRegion { name: kind, .. }) => {
2130 // If this is an anonymous placeholder, don't rename. Otherwise, in some
2131 // async fns, we get a `for<'r> Send` bound
2133 ty::BrAnon(..) | ty::BrEnv => r,
2135 // Index doesn't matter, since this is just for naming and these never get bound
2136 let br = ty::BoundRegion { var: ty::BoundVar::from_u32(0), kind };
2140 .or_insert_with(|| name(None, self.current_index, br))
2146 if let ty::ReLateBound(debruijn1, br) = *region {
2147 assert_eq!(debruijn1, ty::INNERMOST);
2148 self.tcx.mk_region(ty::ReLateBound(self.current_index, br))
2155 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
2156 // `region_index` and `used_region_names`.
2157 impl<'tcx> FmtPrinter<'_, 'tcx> {
2158 pub fn name_all_regions<T>(
2160 value: &ty::Binder<'tcx, T>,
2161 ) -> Result<(Self, T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>), fmt::Error>
2163 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2165 fn name_by_region_index(
2167 available_names: &mut Vec<Symbol>,
2168 num_available: usize,
2170 if let Some(name) = available_names.pop() {
2173 Symbol::intern(&format!("'z{}", index - num_available))
2177 debug!("name_all_regions");
2179 // Replace any anonymous late-bound regions with named
2180 // variants, using new unique identifiers, so that we can
2181 // clearly differentiate between named and unnamed regions in
2182 // the output. We'll probably want to tweak this over time to
2183 // decide just how much information to give.
2184 if self.binder_depth == 0 {
2185 self.prepare_region_info(value);
2188 debug!("self.used_region_names: {:?}", &self.used_region_names);
2190 let mut empty = true;
2191 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
2198 let _ = write!(cx, "{}", w);
2200 let do_continue = |cx: &mut Self, cont: Symbol| {
2201 let _ = write!(cx, "{}", cont);
2204 define_scoped_cx!(self);
2206 let possible_names = ('a'..='z').rev().map(|s| Symbol::intern(&format!("'{s}")));
2208 let mut available_names = possible_names
2209 .filter(|name| !self.used_region_names.contains(&name))
2210 .collect::<Vec<_>>();
2211 debug!(?available_names);
2212 let num_available = available_names.len();
2214 let mut region_index = self.region_index;
2215 let mut next_name = |this: &Self| {
2219 name = name_by_region_index(region_index, &mut available_names, num_available);
2222 if !this.used_region_names.contains(&name) {
2230 // If we want to print verbosely, then print *all* binders, even if they
2231 // aren't named. Eventually, we might just want this as the default, but
2232 // this is not *quite* right and changes the ordering of some output
2234 let (new_value, map) = if self.should_print_verbose() {
2235 for var in value.bound_vars().iter() {
2236 start_or_continue(&mut self, "for<", ", ");
2237 write!(self, "{:?}", var)?;
2239 start_or_continue(&mut self, "", "> ");
2240 (value.clone().skip_binder(), BTreeMap::default())
2244 // Closure used in `RegionFolder` to create names for anonymous late-bound
2245 // regions. We use two `DebruijnIndex`es (one for the currently folded
2246 // late-bound region and the other for the binder level) to determine
2247 // whether a name has already been created for the currently folded region,
2248 // see issue #102392.
2249 let mut name = |lifetime_idx: Option<ty::DebruijnIndex>,
2250 binder_level_idx: ty::DebruijnIndex,
2251 br: ty::BoundRegion| {
2252 let (name, kind) = match br.kind {
2253 ty::BrAnon(..) | ty::BrEnv => {
2254 let name = next_name(&self);
2256 if let Some(lt_idx) = lifetime_idx {
2257 if lt_idx > binder_level_idx {
2258 let kind = ty::BrNamed(CRATE_DEF_ID.to_def_id(), name);
2259 return tcx.mk_region(ty::ReLateBound(
2261 ty::BoundRegion { var: br.var, kind },
2266 (name, ty::BrNamed(CRATE_DEF_ID.to_def_id(), name))
2268 ty::BrNamed(def_id, kw::UnderscoreLifetime) => {
2269 let name = next_name(&self);
2271 if let Some(lt_idx) = lifetime_idx {
2272 if lt_idx > binder_level_idx {
2273 let kind = ty::BrNamed(def_id, name);
2274 return tcx.mk_region(ty::ReLateBound(
2276 ty::BoundRegion { var: br.var, kind },
2281 (name, ty::BrNamed(def_id, name))
2283 ty::BrNamed(_, name) => {
2284 if let Some(lt_idx) = lifetime_idx {
2285 if lt_idx > binder_level_idx {
2287 return tcx.mk_region(ty::ReLateBound(
2289 ty::BoundRegion { var: br.var, kind },
2298 start_or_continue(&mut self, "for<", ", ");
2299 do_continue(&mut self, name);
2300 tcx.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BoundRegion { var: br.var, kind }))
2302 let mut folder = RegionFolder {
2304 current_index: ty::INNERMOST,
2306 region_map: BTreeMap::new(),
2308 let new_value = value.clone().skip_binder().fold_with(&mut folder);
2309 let region_map = folder.region_map;
2310 start_or_continue(&mut self, "", "> ");
2311 (new_value, region_map)
2314 self.binder_depth += 1;
2315 self.region_index = region_index;
2316 Ok((self, new_value, map))
2319 pub fn pretty_in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, fmt::Error>
2321 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2323 let old_region_index = self.region_index;
2324 let (new, new_value, _) = self.name_all_regions(value)?;
2325 let mut inner = new_value.print(new)?;
2326 inner.region_index = old_region_index;
2327 inner.binder_depth -= 1;
2331 pub fn pretty_wrap_binder<T, C: FnOnce(&T, Self) -> Result<Self, fmt::Error>>(
2333 value: &ty::Binder<'tcx, T>,
2335 ) -> Result<Self, fmt::Error>
2337 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2339 let old_region_index = self.region_index;
2340 let (new, new_value, _) = self.name_all_regions(value)?;
2341 let mut inner = f(&new_value, new)?;
2342 inner.region_index = old_region_index;
2343 inner.binder_depth -= 1;
2347 fn prepare_region_info<T>(&mut self, value: &ty::Binder<'tcx, T>)
2349 T: TypeVisitable<'tcx>,
2351 struct RegionNameCollector<'tcx> {
2352 used_region_names: FxHashSet<Symbol>,
2353 type_collector: SsoHashSet<Ty<'tcx>>,
2356 impl<'tcx> RegionNameCollector<'tcx> {
2358 RegionNameCollector {
2359 used_region_names: Default::default(),
2360 type_collector: SsoHashSet::new(),
2365 impl<'tcx> ty::visit::TypeVisitor<'tcx> for RegionNameCollector<'tcx> {
2368 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
2369 trace!("address: {:p}", r.0.0);
2371 // Collect all named lifetimes. These allow us to prevent duplication
2372 // of already existing lifetime names when introducing names for
2373 // anonymous late-bound regions.
2374 if let Some(name) = r.get_name() {
2375 self.used_region_names.insert(name);
2378 r.super_visit_with(self)
2381 // We collect types in order to prevent really large types from compiling for
2382 // a really long time. See issue #83150 for why this is necessary.
2383 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
2384 let not_previously_inserted = self.type_collector.insert(ty);
2385 if not_previously_inserted {
2386 ty.super_visit_with(self)
2388 ControlFlow::CONTINUE
2393 let mut collector = RegionNameCollector::new();
2394 value.visit_with(&mut collector);
2395 self.used_region_names = collector.used_region_names;
2396 self.region_index = 0;
2400 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<'tcx, T>
2402 T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
2405 type Error = P::Error;
2407 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
2412 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
2414 T: Print<'tcx, P, Output = P, Error = P::Error>,
2415 U: Print<'tcx, P, Output = P, Error = P::Error>,
2418 type Error = P::Error;
2419 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
2420 define_scoped_cx!(cx);
2421 p!(print(self.0), ": ", print(self.1));
2426 macro_rules! forward_display_to_print {
2428 // Some of the $ty arguments may not actually use 'tcx
2429 $(#[allow(unused_lifetimes)] impl<'tcx> fmt::Display for $ty {
2430 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2431 ty::tls::with(|tcx| {
2432 let cx = tcx.lift(*self)
2433 .expect("could not lift for printing")
2434 .print(FmtPrinter::new(tcx, Namespace::TypeNS))?;
2435 f.write_str(&cx.into_buffer())?;
2443 macro_rules! define_print_and_forward_display {
2444 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
2445 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
2447 type Error = fmt::Error;
2448 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
2449 #[allow(unused_mut)]
2451 define_scoped_cx!($cx);
2453 #[allow(unreachable_code)]
2458 forward_display_to_print!($($ty),+);
2462 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2463 /// the trait path. That is, it will print `Trait<U>` instead of
2464 /// `<T as Trait<U>>`.
2465 #[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
2466 pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
2468 impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
2469 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2470 fmt::Display::fmt(self, f)
2474 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2475 /// the trait name. That is, it will print `Trait` instead of
2476 /// `<T as Trait<U>>`.
2477 #[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
2478 pub struct TraitRefPrintOnlyTraitName<'tcx>(ty::TraitRef<'tcx>);
2480 impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitName<'tcx> {
2481 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2482 fmt::Display::fmt(self, f)
2486 impl<'tcx> ty::TraitRef<'tcx> {
2487 pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
2488 TraitRefPrintOnlyTraitPath(self)
2491 pub fn print_only_trait_name(self) -> TraitRefPrintOnlyTraitName<'tcx> {
2492 TraitRefPrintOnlyTraitName(self)
2496 impl<'tcx> ty::Binder<'tcx, ty::TraitRef<'tcx>> {
2497 pub fn print_only_trait_path(self) -> ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>> {
2498 self.map_bound(|tr| tr.print_only_trait_path())
2502 #[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
2503 pub struct TraitPredPrintModifiersAndPath<'tcx>(ty::TraitPredicate<'tcx>);
2505 impl<'tcx> fmt::Debug for TraitPredPrintModifiersAndPath<'tcx> {
2506 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2507 fmt::Display::fmt(self, f)
2511 impl<'tcx> ty::TraitPredicate<'tcx> {
2512 pub fn print_modifiers_and_trait_path(self) -> TraitPredPrintModifiersAndPath<'tcx> {
2513 TraitPredPrintModifiersAndPath(self)
2517 impl<'tcx> ty::PolyTraitPredicate<'tcx> {
2518 pub fn print_modifiers_and_trait_path(
2520 ) -> ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>> {
2521 self.map_bound(TraitPredPrintModifiersAndPath)
2525 #[derive(Debug, Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
2526 pub struct PrintClosureAsImpl<'tcx> {
2527 pub closure: ty::ClosureSubsts<'tcx>,
2530 forward_display_to_print! {
2533 &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2536 // HACK(eddyb) these are exhaustive instead of generic,
2537 // because `for<'tcx>` isn't possible yet.
2538 ty::PolyExistentialPredicate<'tcx>,
2539 ty::Binder<'tcx, ty::TraitRef<'tcx>>,
2540 ty::Binder<'tcx, ty::ExistentialTraitRef<'tcx>>,
2541 ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>>,
2542 ty::Binder<'tcx, TraitRefPrintOnlyTraitName<'tcx>>,
2543 ty::Binder<'tcx, ty::FnSig<'tcx>>,
2544 ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2545 ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>>,
2546 ty::Binder<'tcx, ty::SubtypePredicate<'tcx>>,
2547 ty::Binder<'tcx, ty::ProjectionPredicate<'tcx>>,
2548 ty::Binder<'tcx, ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
2549 ty::Binder<'tcx, ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
2551 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
2552 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
2555 define_print_and_forward_display! {
2558 &'tcx ty::List<Ty<'tcx>> {
2559 p!("{{", comma_sep(self.iter()), "}}")
2562 ty::TypeAndMut<'tcx> {
2563 p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
2566 ty::ExistentialTraitRef<'tcx> {
2567 // Use a type that can't appear in defaults of type parameters.
2568 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
2569 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
2570 p!(print(trait_ref.print_only_trait_path()))
2573 ty::ExistentialProjection<'tcx> {
2574 let name = cx.tcx().associated_item(self.item_def_id).name;
2575 p!(write("{} = ", name), print(self.term))
2578 ty::ExistentialPredicate<'tcx> {
2580 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
2581 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
2582 ty::ExistentialPredicate::AutoTrait(def_id) => {
2583 p!(print_def_path(def_id, &[]));
2589 p!(write("{}", self.unsafety.prefix_str()));
2591 if self.abi != Abi::Rust {
2592 p!(write("extern {} ", self.abi));
2595 p!("fn", pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
2598 ty::TraitRef<'tcx> {
2599 p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
2602 TraitRefPrintOnlyTraitPath<'tcx> {
2603 p!(print_def_path(self.0.def_id, self.0.substs));
2606 TraitRefPrintOnlyTraitName<'tcx> {
2607 p!(print_def_path(self.0.def_id, &[]));
2610 TraitPredPrintModifiersAndPath<'tcx> {
2611 if let ty::BoundConstness::ConstIfConst = self.0.constness {
2615 if let ty::ImplPolarity::Negative = self.0.polarity {
2619 p!(print(self.0.trait_ref.print_only_trait_path()));
2622 PrintClosureAsImpl<'tcx> {
2623 p!(pretty_closure_as_impl(self.closure))
2627 p!(write("{}", self.name))
2631 p!(write("{}", self.name))
2634 ty::SubtypePredicate<'tcx> {
2635 p!(print(self.a), " <: ", print(self.b))
2638 ty::CoercePredicate<'tcx> {
2639 p!(print(self.a), " -> ", print(self.b))
2642 ty::TraitPredicate<'tcx> {
2643 p!(print(self.trait_ref.self_ty()), ": ");
2644 if let ty::BoundConstness::ConstIfConst = self.constness && cx.tcx().features().const_trait_impl {
2647 p!(print(self.trait_ref.print_only_trait_path()))
2650 ty::ProjectionPredicate<'tcx> {
2651 p!(print(self.projection_ty), " == ", print(self.term))
2655 match self.unpack() {
2656 ty::TermKind::Ty(ty) => p!(print(ty)),
2657 ty::TermKind::Const(c) => p!(print(c)),
2661 ty::ProjectionTy<'tcx> {
2662 p!(print_def_path(self.item_def_id, self.substs));
2667 ty::ClosureKind::Fn => p!("Fn"),
2668 ty::ClosureKind::FnMut => p!("FnMut"),
2669 ty::ClosureKind::FnOnce => p!("FnOnce"),
2673 ty::Predicate<'tcx> {
2674 let binder = self.kind();
2678 ty::PredicateKind<'tcx> {
2680 ty::PredicateKind::Trait(ref data) => {
2683 ty::PredicateKind::Subtype(predicate) => p!(print(predicate)),
2684 ty::PredicateKind::Coerce(predicate) => p!(print(predicate)),
2685 ty::PredicateKind::RegionOutlives(predicate) => p!(print(predicate)),
2686 ty::PredicateKind::TypeOutlives(predicate) => p!(print(predicate)),
2687 ty::PredicateKind::Projection(predicate) => p!(print(predicate)),
2688 ty::PredicateKind::WellFormed(arg) => p!(print(arg), " well-formed"),
2689 ty::PredicateKind::ObjectSafe(trait_def_id) => {
2690 p!("the trait `", print_def_path(trait_def_id, &[]), "` is object-safe")
2692 ty::PredicateKind::ClosureKind(closure_def_id, _closure_substs, kind) => {
2694 print_value_path(closure_def_id, &[]),
2695 write("` implements the trait `{}`", kind))
2697 ty::PredicateKind::ConstEvaluatable(ct) => {
2698 p!("the constant `", print(ct), "` can be evaluated")
2700 ty::PredicateKind::ConstEquate(c1, c2) => {
2701 p!("the constant `", print(c1), "` equals `", print(c2), "`")
2703 ty::PredicateKind::TypeWellFormedFromEnv(ty) => {
2704 p!("the type `", print(ty), "` is found in the environment")
2710 match self.unpack() {
2711 GenericArgKind::Lifetime(lt) => p!(print(lt)),
2712 GenericArgKind::Type(ty) => p!(print(ty)),
2713 GenericArgKind::Const(ct) => p!(print(ct)),
2718 fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
2719 // Iterate all local crate items no matter where they are defined.
2720 let hir = tcx.hir();
2721 for id in hir.items() {
2722 if matches!(tcx.def_kind(id.owner_id), DefKind::Use) {
2726 let item = hir.item(id);
2727 if item.ident.name == kw::Empty {
2731 let def_id = item.owner_id.to_def_id();
2732 let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
2733 collect_fn(&item.ident, ns, def_id);
2736 // Now take care of extern crate items.
2737 let queue = &mut Vec::new();
2738 let mut seen_defs: DefIdSet = Default::default();
2740 for &cnum in tcx.crates(()).iter() {
2741 let def_id = cnum.as_def_id();
2743 // Ignore crates that are not direct dependencies.
2744 match tcx.extern_crate(def_id) {
2746 Some(extern_crate) => {
2747 if !extern_crate.is_direct() {
2756 // Iterate external crate defs but be mindful about visibility
2757 while let Some(def) = queue.pop() {
2758 for child in tcx.module_children(def).iter() {
2759 if !child.vis.is_public() {
2764 def::Res::Def(DefKind::AssocTy, _) => {}
2765 def::Res::Def(DefKind::TyAlias, _) => {}
2766 def::Res::Def(defkind, def_id) => {
2767 if let Some(ns) = defkind.ns() {
2768 collect_fn(&child.ident, ns, def_id);
2771 if matches!(defkind, DefKind::Mod | DefKind::Enum | DefKind::Trait)
2772 && seen_defs.insert(def_id)
2783 /// The purpose of this function is to collect public symbols names that are unique across all
2784 /// crates in the build. Later, when printing about types we can use those names instead of the
2785 /// full exported path to them.
2787 /// So essentially, if a symbol name can only be imported from one place for a type, and as
2788 /// long as it was not glob-imported anywhere in the current crate, we can trim its printed
2789 /// path and print only the name.
2791 /// This has wide implications on error messages with types, for example, shortening
2792 /// `std::vec::Vec` to just `Vec`, as long as there is no other `Vec` importable anywhere.
2794 /// The implementation uses similar import discovery logic to that of 'use' suggestions.
2795 fn trimmed_def_paths(tcx: TyCtxt<'_>, (): ()) -> FxHashMap<DefId, Symbol> {
2796 let mut map: FxHashMap<DefId, Symbol> = FxHashMap::default();
2798 if let TrimmedDefPaths::GoodPath = tcx.sess.opts.trimmed_def_paths {
2799 // For good paths causing this bug, the `rustc_middle::ty::print::with_no_trimmed_paths`
2800 // wrapper can be used to suppress this query, in exchange for full paths being formatted.
2801 tcx.sess.delay_good_path_bug("trimmed_def_paths constructed");
2804 let unique_symbols_rev: &mut FxHashMap<(Namespace, Symbol), Option<DefId>> =
2805 &mut FxHashMap::default();
2807 for symbol_set in tcx.resolutions(()).glob_map.values() {
2808 for symbol in symbol_set {
2809 unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
2810 unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
2811 unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
2815 for_each_def(tcx, |ident, ns, def_id| {
2816 use std::collections::hash_map::Entry::{Occupied, Vacant};
2818 match unique_symbols_rev.entry((ns, ident.name)) {
2819 Occupied(mut v) => match v.get() {
2822 if *existing != def_id {
2828 v.insert(Some(def_id));
2833 for ((_, symbol), opt_def_id) in unique_symbols_rev.drain() {
2834 use std::collections::hash_map::Entry::{Occupied, Vacant};
2836 if let Some(def_id) = opt_def_id {
2837 match map.entry(def_id) {
2838 Occupied(mut v) => {
2839 // A single DefId can be known under multiple names (e.g.,
2840 // with a `pub use ... as ...;`). We need to ensure that the
2841 // name placed in this map is chosen deterministically, so
2842 // if we find multiple names (`symbol`) resolving to the
2843 // same `def_id`, we prefer the lexicographically smallest
2846 // Any stable ordering would be fine here though.
2847 if *v.get() != symbol {
2848 if v.get().as_str() > symbol.as_str() {
2863 pub fn provide(providers: &mut ty::query::Providers) {
2864 *providers = ty::query::Providers { trimmed_def_paths, ..*providers };
2868 pub struct OpaqueFnEntry<'tcx> {
2869 // The trait ref is already stored as a key, so just track if we have it as a real predicate
2871 fn_mut_trait_ref: Option<ty::PolyTraitRef<'tcx>>,
2872 fn_trait_ref: Option<ty::PolyTraitRef<'tcx>>,
2873 return_ty: Option<ty::Binder<'tcx, Term<'tcx>>>,