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_hir::LangItem;
15 use rustc_session::config::TrimmedDefPaths;
16 use rustc_session::cstore::{ExternCrate, ExternCrateSource};
17 use rustc_session::Limit;
18 use rustc_span::symbol::{kw, Ident, Symbol};
19 use rustc_target::abi::Size;
20 use rustc_target::spec::abi::Abi;
21 use smallvec::SmallVec;
25 use std::collections::BTreeMap;
26 use std::convert::TryFrom;
27 use std::fmt::{self, Write as _};
29 use std::ops::{ControlFlow, Deref, DerefMut};
31 // `pretty` is a separate module only for organization.
36 write!(scoped_cx!(), $lit)?
38 (@write($($data:expr),+)) => {
39 write!(scoped_cx!(), $($data),+)?
41 (@print($x:expr)) => {
42 scoped_cx!() = $x.print(scoped_cx!())?
44 (@$method:ident($($arg:expr),*)) => {
45 scoped_cx!() = scoped_cx!().$method($($arg),*)?
47 ($($elem:tt $(($($args:tt)*))?),+) => {{
48 $(p!(@ $elem $(($($args)*))?);)+
51 macro_rules! define_scoped_cx {
53 #[allow(unused_macros)]
54 macro_rules! scoped_cx {
63 static FORCE_IMPL_FILENAME_LINE: Cell<bool> = const { Cell::new(false) };
64 static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = const { Cell::new(false) };
65 static NO_TRIMMED_PATH: Cell<bool> = const { Cell::new(false) };
66 static NO_QUERIES: Cell<bool> = const { Cell::new(false) };
67 static NO_VISIBLE_PATH: Cell<bool> = const { Cell::new(false) };
70 macro_rules! define_helper {
71 ($($(#[$a:meta])* fn $name:ident($helper:ident, $tl:ident);)+) => {
74 pub struct $helper(bool);
77 pub fn new() -> $helper {
78 $helper($tl.with(|c| c.replace(true)))
83 pub macro $name($e:expr) {
85 let _guard = $helper::new();
90 impl Drop for $helper {
92 $tl.with(|c| c.set(self.0))
100 /// Avoids running any queries during any prints that occur
101 /// during the closure. This may alter the appearance of some
102 /// types (e.g. forcing verbose printing for opaque types).
103 /// This method is used during some queries (e.g. `explicit_item_bounds`
104 /// for opaque types), to ensure that any debug printing that
105 /// occurs during the query computation does not end up recursively
106 /// calling the same query.
107 fn with_no_queries(NoQueriesGuard, NO_QUERIES);
108 /// Force us to name impls with just the filename/line number. We
109 /// normally try to use types. But at some points, notably while printing
110 /// cycle errors, this can result in extra or suboptimal error output,
111 /// so this variable disables that check.
112 fn with_forced_impl_filename_line(ForcedImplGuard, FORCE_IMPL_FILENAME_LINE);
113 /// Adds the `crate::` prefix to paths where appropriate.
114 fn with_crate_prefix(CratePrefixGuard, SHOULD_PREFIX_WITH_CRATE);
115 /// Prevent path trimming if it is turned on. Path trimming affects `Display` impl
116 /// of various rustc types, for example `std::vec::Vec` would be trimmed to `Vec`,
117 /// if no other `Vec` is found.
118 fn with_no_trimmed_paths(NoTrimmedGuard, NO_TRIMMED_PATH);
119 /// Prevent selection of visible paths. `Display` impl of DefId will prefer
120 /// visible (public) reexports of types as paths.
121 fn with_no_visible_paths(NoVisibleGuard, NO_VISIBLE_PATH);
124 /// The "region highlights" are used to control region printing during
125 /// specific error messages. When a "region highlight" is enabled, it
126 /// gives an alternate way to print specific regions. For now, we
127 /// always print those regions using a number, so something like "`'0`".
129 /// Regions not selected by the region highlight mode are presently
131 #[derive(Copy, Clone)]
132 pub struct RegionHighlightMode<'tcx> {
135 /// If enabled, when we see the selected region, use "`'N`"
136 /// instead of the ordinary behavior.
137 highlight_regions: [Option<(ty::Region<'tcx>, usize)>; 3],
139 /// If enabled, when printing a "free region" that originated from
140 /// the given `ty::BoundRegionKind`, print it as "`'1`". Free regions that would ordinarily
141 /// have names print as normal.
143 /// This is used when you have a signature like `fn foo(x: &u32,
144 /// y: &'a u32)` and we want to give a name to the region of the
146 highlight_bound_region: Option<(ty::BoundRegionKind, usize)>,
149 impl<'tcx> RegionHighlightMode<'tcx> {
150 pub fn new(tcx: TyCtxt<'tcx>) -> Self {
153 highlight_regions: Default::default(),
154 highlight_bound_region: Default::default(),
158 /// If `region` and `number` are both `Some`, invokes
159 /// `highlighting_region`.
160 pub fn maybe_highlighting_region(
162 region: Option<ty::Region<'tcx>>,
163 number: Option<usize>,
165 if let Some(k) = region {
166 if let Some(n) = number {
167 self.highlighting_region(k, n);
172 /// Highlights the region inference variable `vid` as `'N`.
173 pub fn highlighting_region(&mut self, region: ty::Region<'tcx>, number: usize) {
174 let num_slots = self.highlight_regions.len();
175 let first_avail_slot =
176 self.highlight_regions.iter_mut().find(|s| s.is_none()).unwrap_or_else(|| {
177 bug!("can only highlight {} placeholders at a time", num_slots,)
179 *first_avail_slot = Some((region, number));
182 /// Convenience wrapper for `highlighting_region`.
183 pub fn highlighting_region_vid(&mut self, vid: ty::RegionVid, number: usize) {
184 self.highlighting_region(self.tcx.mk_region(ty::ReVar(vid)), number)
187 /// Returns `Some(n)` with the number to use for the given region, if any.
188 fn region_highlighted(&self, region: ty::Region<'tcx>) -> Option<usize> {
189 self.highlight_regions.iter().find_map(|h| match h {
190 Some((r, n)) if *r == region => Some(*n),
195 /// Highlight the given bound region.
196 /// We can only highlight one bound region at a time. See
197 /// the field `highlight_bound_region` for more detailed notes.
198 pub fn highlighting_bound_region(&mut self, br: ty::BoundRegionKind, number: usize) {
199 assert!(self.highlight_bound_region.is_none());
200 self.highlight_bound_region = Some((br, number));
204 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
205 pub trait PrettyPrinter<'tcx>:
212 DynExistential = Self,
216 /// Like `print_def_path` but for value paths.
220 substs: &'tcx [GenericArg<'tcx>],
221 ) -> Result<Self::Path, Self::Error> {
222 self.print_def_path(def_id, substs)
225 fn in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, Self::Error>
227 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
229 value.as_ref().skip_binder().print(self)
232 fn wrap_binder<T, F: FnOnce(&T, Self) -> Result<Self, fmt::Error>>(
234 value: &ty::Binder<'tcx, T>,
236 ) -> Result<Self, Self::Error>
238 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
240 f(value.as_ref().skip_binder(), self)
243 /// Prints comma-separated elements.
244 fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
246 T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
248 if let Some(first) = elems.next() {
249 self = first.print(self)?;
251 self.write_str(", ")?;
252 self = elem.print(self)?;
258 /// Prints `{f: t}` or `{f as t}` depending on the `cast` argument
261 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
262 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
264 ) -> Result<Self::Const, Self::Error> {
265 self.write_str("{")?;
267 self.write_str(conversion)?;
269 self.write_str("}")?;
273 /// Prints `<...>` around what `f` prints.
274 fn generic_delimiters(
276 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
277 ) -> Result<Self, Self::Error>;
279 /// Returns `true` if the region should be printed in
280 /// optional positions, e.g., `&'a T` or `dyn Tr + 'b`.
281 /// This is typically the case for all non-`'_` regions.
282 fn should_print_region(&self, region: ty::Region<'tcx>) -> bool;
284 // Defaults (should not be overridden):
286 /// If possible, this returns a global path resolving to `def_id` that is visible
287 /// from at least one local module, and returns `true`. If the crate defining `def_id` is
288 /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
289 fn try_print_visible_def_path(self, def_id: DefId) -> Result<(Self, bool), Self::Error> {
290 if NO_VISIBLE_PATH.with(|flag| flag.get()) {
291 return Ok((self, false));
294 let mut callers = Vec::new();
295 self.try_print_visible_def_path_recur(def_id, &mut callers)
298 /// Try to see if this path can be trimmed to a unique symbol name.
299 fn try_print_trimmed_def_path(
302 ) -> Result<(Self::Path, bool), Self::Error> {
303 if !self.tcx().sess.opts.unstable_opts.trim_diagnostic_paths
304 || matches!(self.tcx().sess.opts.trimmed_def_paths, TrimmedDefPaths::Never)
305 || NO_TRIMMED_PATH.with(|flag| flag.get())
306 || SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get())
308 return Ok((self, false));
311 match self.tcx().trimmed_def_paths(()).get(&def_id) {
312 None => Ok((self, false)),
314 self.write_str(symbol.as_str())?;
320 /// Does the work of `try_print_visible_def_path`, building the
321 /// full definition path recursively before attempting to
322 /// post-process it into the valid and visible version that
323 /// accounts for re-exports.
325 /// This method should only be called by itself or
326 /// `try_print_visible_def_path`.
328 /// `callers` is a chain of visible_parent's leading to `def_id`,
329 /// to support cycle detection during recursion.
331 /// This method returns false if we can't print the visible path, so
332 /// `print_def_path` can fall back on the item's real definition path.
333 fn try_print_visible_def_path_recur(
336 callers: &mut Vec<DefId>,
337 ) -> Result<(Self, bool), Self::Error> {
338 define_scoped_cx!(self);
340 debug!("try_print_visible_def_path: def_id={:?}", def_id);
342 // If `def_id` is a direct or injected extern crate, return the
343 // path to the crate followed by the path to the item within the crate.
344 if let Some(cnum) = def_id.as_crate_root() {
345 if cnum == LOCAL_CRATE {
346 return Ok((self.path_crate(cnum)?, true));
349 // In local mode, when we encounter a crate other than
350 // LOCAL_CRATE, execution proceeds in one of two ways:
352 // 1. For a direct dependency, where user added an
353 // `extern crate` manually, we put the `extern
354 // crate` as the parent. So you wind up with
355 // something relative to the current crate.
356 // 2. For an extern inferred from a path or an indirect crate,
357 // where there is no explicit `extern crate`, we just prepend
359 match self.tcx().extern_crate(def_id) {
360 Some(&ExternCrate { src, dependency_of, span, .. }) => match (src, dependency_of) {
361 (ExternCrateSource::Extern(def_id), LOCAL_CRATE) => {
362 // NOTE(eddyb) the only reason `span` might be dummy,
363 // that we're aware of, is that it's the `std`/`core`
364 // `extern crate` injected by default.
365 // FIXME(eddyb) find something better to key this on,
366 // or avoid ending up with `ExternCrateSource::Extern`,
367 // for the injected `std`/`core`.
369 return Ok((self.path_crate(cnum)?, true));
372 // Disable `try_print_trimmed_def_path` behavior within
373 // the `print_def_path` call, to avoid infinite recursion
374 // in cases where the `extern crate foo` has non-trivial
375 // parents, e.g. it's nested in `impl foo::Trait for Bar`
376 // (see also issues #55779 and #87932).
377 self = with_no_visible_paths!(self.print_def_path(def_id, &[])?);
379 return Ok((self, true));
381 (ExternCrateSource::Path, LOCAL_CRATE) => {
382 return Ok((self.path_crate(cnum)?, true));
387 return Ok((self.path_crate(cnum)?, true));
392 if def_id.is_local() {
393 return Ok((self, false));
396 let visible_parent_map = self.tcx().visible_parent_map(());
398 let mut cur_def_key = self.tcx().def_key(def_id);
399 debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
401 // For a constructor, we want the name of its parent rather than <unnamed>.
402 if let DefPathData::Ctor = cur_def_key.disambiguated_data.data {
407 .expect("`DefPathData::Ctor` / `VariantData` missing a parent"),
410 cur_def_key = self.tcx().def_key(parent);
413 let Some(visible_parent) = visible_parent_map.get(&def_id).cloned() else {
414 return Ok((self, false));
417 let actual_parent = self.tcx().opt_parent(def_id);
419 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
420 visible_parent, actual_parent,
423 let mut data = cur_def_key.disambiguated_data.data;
425 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
426 data, visible_parent, actual_parent,
430 // In order to output a path that could actually be imported (valid and visible),
431 // we need to handle re-exports correctly.
433 // For example, take `std::os::unix::process::CommandExt`, this trait is actually
434 // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
436 // `std::os::unix` reexports the contents of `std::sys::unix::ext`. `std::sys` is
437 // private so the "true" path to `CommandExt` isn't accessible.
439 // In this case, the `visible_parent_map` will look something like this:
441 // (child) -> (parent)
442 // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
443 // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
444 // `std::sys::unix::ext` -> `std::os`
446 // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
449 // When printing the path to `CommandExt` and looking at the `cur_def_key` that
450 // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
451 // to the parent - resulting in a mangled path like
452 // `std::os::ext::process::CommandExt`.
454 // Instead, we must detect that there was a re-export and instead print `unix`
455 // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
456 // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
457 // the visible parent (`std::os`). If these do not match, then we iterate over
458 // the children of the visible parent (as was done when computing
459 // `visible_parent_map`), looking for the specific child we currently have and then
460 // have access to the re-exported name.
461 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
462 // Item might be re-exported several times, but filter for the one
463 // that's public and whose identifier isn't `_`.
466 .module_children(visible_parent)
468 .filter(|child| child.res.opt_def_id() == Some(def_id))
469 .find(|child| child.vis.is_public() && child.ident.name != kw::Underscore)
470 .map(|child| child.ident.name);
472 if let Some(new_name) = reexport {
475 // There is no name that is public and isn't `_`, so bail.
476 return Ok((self, false));
479 // Re-exported `extern crate` (#43189).
480 DefPathData::CrateRoot => {
481 data = DefPathData::TypeNs(self.tcx().crate_name(def_id.krate));
485 debug!("try_print_visible_def_path: data={:?}", data);
487 if callers.contains(&visible_parent) {
488 return Ok((self, false));
490 callers.push(visible_parent);
491 // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
492 // knowing ahead of time whether the entire path will succeed or not.
493 // To support printers that do not implement `PrettyPrinter`, a `Vec` or
494 // linked list on the stack would need to be built, before any printing.
495 match self.try_print_visible_def_path_recur(visible_parent, callers)? {
496 (cx, false) => return Ok((cx, false)),
497 (cx, true) => self = cx,
501 Ok((self.path_append(Ok, &DisambiguatedDefPathData { data, disambiguator: 0 })?, true))
504 fn pretty_path_qualified(
507 trait_ref: Option<ty::TraitRef<'tcx>>,
508 ) -> Result<Self::Path, Self::Error> {
509 if trait_ref.is_none() {
510 // Inherent impls. Try to print `Foo::bar` for an inherent
511 // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
512 // anything other than a simple path.
513 match self_ty.kind() {
522 return self_ty.print(self);
529 self.generic_delimiters(|mut cx| {
530 define_scoped_cx!(cx);
533 if let Some(trait_ref) = trait_ref {
534 p!(" as ", print(trait_ref.print_only_trait_path()));
540 fn pretty_path_append_impl(
542 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
544 trait_ref: Option<ty::TraitRef<'tcx>>,
545 ) -> Result<Self::Path, Self::Error> {
546 self = print_prefix(self)?;
548 self.generic_delimiters(|mut cx| {
549 define_scoped_cx!(cx);
552 if let Some(trait_ref) = trait_ref {
553 p!(print(trait_ref.print_only_trait_path()), " for ");
561 fn pretty_print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
562 define_scoped_cx!(self);
565 ty::Bool => p!("bool"),
566 ty::Char => p!("char"),
567 ty::Int(t) => p!(write("{}", t.name_str())),
568 ty::Uint(t) => p!(write("{}", t.name_str())),
569 ty::Float(t) => p!(write("{}", t.name_str())),
570 ty::RawPtr(ref tm) => {
574 hir::Mutability::Mut => "mut",
575 hir::Mutability::Not => "const",
580 ty::Ref(r, ty, mutbl) => {
582 if self.should_print_region(r) {
585 p!(print(ty::TypeAndMut { ty, mutbl }))
587 ty::Never => p!("!"),
588 ty::Tuple(ref tys) => {
589 p!("(", comma_sep(tys.iter()));
595 ty::FnDef(def_id, substs) => {
596 let sig = self.tcx().bound_fn_sig(def_id).subst(self.tcx(), substs);
597 p!(print(sig), " {{", print_value_path(def_id, substs), "}}");
599 ty::FnPtr(ref bare_fn) => p!(print(bare_fn)),
600 ty::Infer(infer_ty) => {
601 let verbose = self.should_print_verbose();
602 if let ty::TyVar(ty_vid) = infer_ty {
603 if let Some(name) = self.ty_infer_name(ty_vid) {
604 p!(write("{}", name))
607 p!(write("{:?}", infer_ty))
609 p!(write("{}", infer_ty))
613 if verbose { p!(write("{:?}", infer_ty)) } else { p!(write("{}", infer_ty)) }
616 ty::Error(_) => p!("[type error]"),
617 ty::Param(ref param_ty) => p!(print(param_ty)),
618 ty::Bound(debruijn, bound_ty) => match bound_ty.kind {
619 ty::BoundTyKind::Anon => self.pretty_print_bound_var(debruijn, bound_ty.var)?,
620 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
622 ty::Adt(def, substs) => {
623 p!(print_def_path(def.did(), substs));
625 ty::Dynamic(data, r, repr) => {
626 let print_r = self.should_print_region(r);
631 ty::Dyn => p!("dyn "),
632 ty::DynStar => p!("dyn* "),
636 p!(" + ", print(r), ")");
639 ty::Foreign(def_id) => {
640 p!(print_def_path(def_id, &[]));
642 ty::Projection(ref data) => {
643 if !(self.should_print_verbose() || NO_QUERIES.with(|q| q.get()))
644 && self.tcx().def_kind(data.item_def_id) == DefKind::ImplTraitPlaceholder
646 return self.pretty_print_opaque_impl_type(data.item_def_id, data.substs);
651 ty::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
652 ty::Opaque(def_id, substs) => {
653 // FIXME(eddyb) print this with `print_def_path`.
654 // We use verbose printing in 'NO_QUERIES' mode, to
655 // avoid needing to call `predicates_of`. This should
656 // only affect certain debug messages (e.g. messages printed
657 // from `rustc_middle::ty` during the computation of `tcx.predicates_of`),
658 // and should have no effect on any compiler output.
659 if self.should_print_verbose() || NO_QUERIES.with(|q| q.get()) {
660 p!(write("Opaque({:?}, {:?})", def_id, substs));
664 let parent = self.tcx().parent(def_id);
665 match self.tcx().def_kind(parent) {
666 DefKind::TyAlias | DefKind::AssocTy => {
667 if let ty::Opaque(d, _) = *self.tcx().type_of(parent).kind() {
669 // If the type alias directly starts with the `impl` of the
670 // opaque type we're printing, then skip the `::{opaque#1}`.
671 p!(print_def_path(parent, substs));
675 // Complex opaque type, e.g. `type Foo = (i32, impl Debug);`
676 p!(print_def_path(def_id, substs));
679 _ => return self.pretty_print_opaque_impl_type(def_id, substs),
682 ty::Str => p!("str"),
683 ty::Generator(did, substs, movability) => {
685 let generator_kind = self.tcx().generator_kind(did).unwrap();
686 let should_print_movability =
687 self.should_print_verbose() || generator_kind == hir::GeneratorKind::Gen;
689 if should_print_movability {
691 hir::Movability::Movable => {}
692 hir::Movability::Static => p!("static "),
696 if !self.should_print_verbose() {
697 p!(write("{}", generator_kind));
698 // FIXME(eddyb) should use `def_span`.
699 if let Some(did) = did.as_local() {
700 let span = self.tcx().def_span(did);
703 // This may end up in stderr diagnostics but it may also be emitted
704 // into MIR. Hence we use the remapped path if available
705 self.tcx().sess.source_map().span_to_embeddable_string(span)
708 p!(write("@"), print_def_path(did, substs));
711 p!(print_def_path(did, substs));
713 if !substs.as_generator().is_valid() {
716 self = self.comma_sep(substs.as_generator().upvar_tys())?;
720 if substs.as_generator().is_valid() {
721 p!(" ", print(substs.as_generator().witness()));
727 ty::GeneratorWitness(types) => {
728 p!(in_binder(&types));
730 ty::Closure(did, substs) => {
732 if !self.should_print_verbose() {
733 p!(write("closure"));
734 // FIXME(eddyb) should use `def_span`.
735 if let Some(did) = did.as_local() {
736 if self.tcx().sess.opts.unstable_opts.span_free_formats {
737 p!("@", print_def_path(did.to_def_id(), substs));
739 let span = self.tcx().def_span(did);
742 // This may end up in stderr diagnostics but it may also be emitted
743 // into MIR. Hence we use the remapped path if available
744 self.tcx().sess.source_map().span_to_embeddable_string(span)
748 p!(write("@"), print_def_path(did, substs));
751 p!(print_def_path(did, substs));
752 if !substs.as_closure().is_valid() {
753 p!(" closure_substs=(unavailable)");
754 p!(write(" substs={:?}", substs));
756 p!(" closure_kind_ty=", print(substs.as_closure().kind_ty()));
758 " closure_sig_as_fn_ptr_ty=",
759 print(substs.as_closure().sig_as_fn_ptr_ty())
762 self = self.comma_sep(substs.as_closure().upvar_tys())?;
768 ty::Array(ty, sz) => {
769 p!("[", print(ty), "; ");
770 if self.should_print_verbose() {
771 p!(write("{:?}", sz));
772 } else if let ty::ConstKind::Unevaluated(..) = sz.kind() {
773 // Do not try to evaluate unevaluated constants. If we are const evaluating an
774 // array length anon const, rustc will (with debug assertions) print the
775 // constant's path. Which will end up here again.
777 } else if let Some(n) = sz.kind().try_to_bits(self.tcx().data_layout.pointer_size) {
779 } else if let ty::ConstKind::Param(param) = sz.kind() {
786 ty::Slice(ty) => p!("[", print(ty), "]"),
792 fn pretty_print_opaque_impl_type(
795 substs: &'tcx ty::List<ty::GenericArg<'tcx>>,
796 ) -> Result<Self::Type, Self::Error> {
797 let tcx = self.tcx();
799 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
800 // by looking up the projections associated with the def_id.
801 let bounds = tcx.bound_explicit_item_bounds(def_id);
803 let mut traits = FxIndexMap::default();
804 let mut fn_traits = FxIndexMap::default();
805 let mut is_sized = false;
806 let mut lifetimes = SmallVec::<[ty::Region<'tcx>; 1]>::new();
808 for (predicate, _) in bounds.subst_iter_copied(tcx, substs) {
809 let bound_predicate = predicate.kind();
811 match bound_predicate.skip_binder() {
812 ty::PredicateKind::Clause(ty::Clause::Trait(pred)) => {
813 let trait_ref = bound_predicate.rebind(pred.trait_ref);
815 // Don't print + Sized, but rather + ?Sized if absent.
816 if Some(trait_ref.def_id()) == tcx.lang_items().sized_trait() {
821 self.insert_trait_and_projection(trait_ref, None, &mut traits, &mut fn_traits);
823 ty::PredicateKind::Clause(ty::Clause::Projection(pred)) => {
824 let proj_ref = bound_predicate.rebind(pred);
825 let trait_ref = proj_ref.required_poly_trait_ref(tcx);
827 // Projection type entry -- the def-id for naming, and the ty.
828 let proj_ty = (proj_ref.projection_def_id(), proj_ref.term());
830 self.insert_trait_and_projection(
837 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(outlives)) => {
838 lifetimes.push(outlives.1);
844 write!(self, "impl ")?;
846 let mut first = true;
847 // Insert parenthesis around (Fn(A, B) -> C) if the opaque ty has more than one other trait
848 let paren_needed = fn_traits.len() > 1 || traits.len() > 0 || !is_sized;
850 for (fn_once_trait_ref, entry) in fn_traits {
851 write!(self, "{}", if first { "" } else { " + " })?;
852 write!(self, "{}", if paren_needed { "(" } else { "" })?;
854 self = self.wrap_binder(&fn_once_trait_ref, |trait_ref, mut cx| {
855 define_scoped_cx!(cx);
856 // Get the (single) generic ty (the args) of this FnOnce trait ref.
857 let generics = tcx.generics_of(trait_ref.def_id);
858 let args = generics.own_substs_no_defaults(tcx, trait_ref.substs);
860 match (entry.return_ty, args[0].expect_ty()) {
861 // We can only print `impl Fn() -> ()` if we have a tuple of args and we recorded
863 (Some(return_ty), arg_tys) if matches!(arg_tys.kind(), ty::Tuple(_)) => {
864 let name = if entry.fn_trait_ref.is_some() {
866 } else if entry.fn_mut_trait_ref.is_some() {
872 p!(write("{}(", name));
874 for (idx, ty) in arg_tys.tuple_fields().iter().enumerate() {
882 if let Some(ty) = return_ty.skip_binder().ty() {
884 p!(" -> ", print(return_ty));
887 p!(write("{}", if paren_needed { ")" } else { "" }));
891 // If we got here, we can't print as a `impl Fn(A, B) -> C`. Just record the
892 // trait_refs we collected in the OpaqueFnEntry as normal trait refs.
894 if entry.has_fn_once {
895 traits.entry(fn_once_trait_ref).or_default().extend(
896 // Group the return ty with its def id, if we had one.
899 .map(|ty| (tcx.require_lang_item(LangItem::FnOnce, None), ty)),
902 if let Some(trait_ref) = entry.fn_mut_trait_ref {
903 traits.entry(trait_ref).or_default();
905 if let Some(trait_ref) = entry.fn_trait_ref {
906 traits.entry(trait_ref).or_default();
915 // Print the rest of the trait types (that aren't Fn* family of traits)
916 for (trait_ref, assoc_items) in traits {
917 write!(self, "{}", if first { "" } else { " + " })?;
919 self = self.wrap_binder(&trait_ref, |trait_ref, mut cx| {
920 define_scoped_cx!(cx);
921 p!(print(trait_ref.print_only_trait_name()));
923 let generics = tcx.generics_of(trait_ref.def_id);
924 let args = generics.own_substs_no_defaults(tcx, trait_ref.substs);
926 if !args.is_empty() || !assoc_items.is_empty() {
927 let mut first = true;
939 for (assoc_item_def_id, term) in assoc_items {
940 // Skip printing `<[generator@] as Generator<_>>::Return` from async blocks,
941 // unless we can find out what generator return type it comes from.
942 let term = if let Some(ty) = term.skip_binder().ty()
943 && let ty::Projection(proj) = ty.kind()
944 && let Some(assoc) = tcx.opt_associated_item(proj.item_def_id)
945 && assoc.trait_container(tcx) == tcx.lang_items().gen_trait()
946 && assoc.name == rustc_span::sym::Return
948 if let ty::Generator(_, substs, _) = substs.type_at(0).kind() {
949 let return_ty = substs.as_generator().return_ty();
950 if !return_ty.is_ty_var() {
969 p!(write("{} = ", tcx.associated_item(assoc_item_def_id).name));
971 match term.unpack() {
972 TermKind::Ty(ty) => p!(print(ty)),
973 TermKind::Const(c) => p!(print(c)),
988 write!(self, "{}?Sized", if first { "" } else { " + " })?;
990 write!(self, "Sized")?;
993 for re in lifetimes {
994 write!(self, " + ")?;
995 self = self.print_region(re)?;
1001 /// Insert the trait ref and optionally a projection type associated with it into either the
1002 /// traits map or fn_traits map, depending on if the trait is in the Fn* family of traits.
1003 fn insert_trait_and_projection(
1005 trait_ref: ty::PolyTraitRef<'tcx>,
1006 proj_ty: Option<(DefId, ty::Binder<'tcx, Term<'tcx>>)>,
1007 traits: &mut FxIndexMap<
1008 ty::PolyTraitRef<'tcx>,
1009 FxIndexMap<DefId, ty::Binder<'tcx, Term<'tcx>>>,
1011 fn_traits: &mut FxIndexMap<ty::PolyTraitRef<'tcx>, OpaqueFnEntry<'tcx>>,
1013 let trait_def_id = trait_ref.def_id();
1015 // If our trait_ref is FnOnce or any of its children, project it onto the parent FnOnce
1016 // super-trait ref and record it there.
1017 if let Some(fn_once_trait) = self.tcx().lang_items().fn_once_trait() {
1018 // If we have a FnOnce, then insert it into
1019 if trait_def_id == fn_once_trait {
1020 let entry = fn_traits.entry(trait_ref).or_default();
1021 // Optionally insert the return_ty as well.
1022 if let Some((_, ty)) = proj_ty {
1023 entry.return_ty = Some(ty);
1025 entry.has_fn_once = true;
1027 } else if Some(trait_def_id) == self.tcx().lang_items().fn_mut_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_mut_trait_ref = Some(trait_ref);
1034 } else if Some(trait_def_id) == self.tcx().lang_items().fn_trait() {
1035 let super_trait_ref = crate::traits::util::supertraits(self.tcx(), trait_ref)
1036 .find(|super_trait_ref| super_trait_ref.def_id() == fn_once_trait)
1039 fn_traits.entry(super_trait_ref).or_default().fn_trait_ref = Some(trait_ref);
1044 // Otherwise, just group our traits and projection types.
1045 traits.entry(trait_ref).or_default().extend(proj_ty);
1048 fn pretty_print_bound_var(
1050 debruijn: ty::DebruijnIndex,
1052 ) -> Result<(), Self::Error> {
1053 if debruijn == ty::INNERMOST {
1054 write!(self, "^{}", var.index())
1056 write!(self, "^{}_{}", debruijn.index(), var.index())
1060 fn ty_infer_name(&self, _: ty::TyVid) -> Option<Symbol> {
1064 fn const_infer_name(&self, _: ty::ConstVid<'tcx>) -> Option<Symbol> {
1068 fn pretty_print_dyn_existential(
1070 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1071 ) -> Result<Self::DynExistential, Self::Error> {
1072 // Generate the main trait ref, including associated types.
1073 let mut first = true;
1075 if let Some(principal) = predicates.principal() {
1076 self = self.wrap_binder(&principal, |principal, mut cx| {
1077 define_scoped_cx!(cx);
1078 p!(print_def_path(principal.def_id, &[]));
1080 let mut resugared = false;
1082 // Special-case `Fn(...) -> ...` and re-sugar it.
1083 let fn_trait_kind = cx.tcx().fn_trait_kind_from_lang_item(principal.def_id);
1084 if !cx.should_print_verbose() && fn_trait_kind.is_some() {
1085 if let ty::Tuple(tys) = principal.substs.type_at(0).kind() {
1086 let mut projections = predicates.projection_bounds();
1087 if let (Some(proj), None) = (projections.next(), projections.next()) {
1091 proj.skip_binder().term.ty().expect("Return type was a const")
1098 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
1099 // in order to place the projections inside the `<...>`.
1101 // Use a type that can't appear in defaults of type parameters.
1102 let dummy_cx = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1103 let principal = principal.with_self_ty(cx.tcx(), dummy_cx);
1107 .generics_of(principal.def_id)
1108 .own_substs_no_defaults(cx.tcx(), principal.substs);
1110 let mut projections = predicates.projection_bounds();
1112 let mut args = args.iter().cloned();
1113 let arg0 = args.next();
1114 let projection0 = projections.next();
1115 if arg0.is_some() || projection0.is_some() {
1116 let args = arg0.into_iter().chain(args);
1117 let projections = projection0.into_iter().chain(projections);
1119 p!(generic_delimiters(|mut cx| {
1120 cx = cx.comma_sep(args)?;
1121 if arg0.is_some() && projection0.is_some() {
1124 cx.comma_sep(projections)
1134 define_scoped_cx!(self);
1137 // FIXME(eddyb) avoid printing twice (needed to ensure
1138 // that the auto traits are sorted *and* printed via cx).
1139 let mut auto_traits: Vec<_> = predicates.auto_traits().collect();
1141 // The auto traits come ordered by `DefPathHash`. While
1142 // `DefPathHash` is *stable* in the sense that it depends on
1143 // neither the host nor the phase of the moon, it depends
1144 // "pseudorandomly" on the compiler version and the target.
1146 // To avoid causing instabilities in compiletest
1147 // output, sort the auto-traits alphabetically.
1148 auto_traits.sort_by_cached_key(|did| with_no_trimmed_paths!(self.tcx().def_path_str(*did)));
1150 for def_id in auto_traits {
1156 p!(print_def_path(def_id, &[]));
1164 inputs: &[Ty<'tcx>],
1167 ) -> Result<Self, Self::Error> {
1168 define_scoped_cx!(self);
1170 p!("(", comma_sep(inputs.iter().copied()));
1172 if !inputs.is_empty() {
1178 if !output.is_unit() {
1179 p!(" -> ", print(output));
1185 fn pretty_print_const(
1187 ct: ty::Const<'tcx>,
1189 ) -> Result<Self::Const, Self::Error> {
1190 define_scoped_cx!(self);
1192 if self.should_print_verbose() {
1193 p!(write("Const({:?}: {:?})", ct.kind(), ct.ty()));
1197 macro_rules! print_underscore {
1200 self = self.typed_value(
1205 |this| this.print_type(ct.ty()),
1215 ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, substs }) => {
1216 match self.tcx().def_kind(def.did) {
1217 DefKind::Static(..) | DefKind::Const | DefKind::AssocConst => {
1218 p!(print_value_path(def.did, substs))
1222 let span = self.tcx().def_span(def.did);
1223 if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span) {
1224 p!(write("{}", snip))
1234 ty::ConstKind::Infer(infer_ct) => {
1236 ty::InferConst::Var(ct_vid)
1237 if let Some(name) = self.const_infer_name(ct_vid) =>
1238 p!(write("{}", name)),
1239 _ => print_underscore!(),
1242 ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)),
1243 ty::ConstKind::Value(value) => {
1244 return self.pretty_print_const_valtree(value, ct.ty(), print_ty);
1247 ty::ConstKind::Bound(debruijn, bound_var) => {
1248 self.pretty_print_bound_var(debruijn, bound_var)?
1250 ty::ConstKind::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
1251 // FIXME(generic_const_exprs):
1252 // write out some legible representation of an abstract const?
1253 ty::ConstKind::Expr(_) => p!("[Const Expr]"),
1254 ty::ConstKind::Error(_) => p!("[const error]"),
1259 fn pretty_print_const_scalar(
1264 ) -> Result<Self::Const, Self::Error> {
1266 Scalar::Ptr(ptr, _size) => self.pretty_print_const_scalar_ptr(ptr, ty, print_ty),
1267 Scalar::Int(int) => self.pretty_print_const_scalar_int(int, ty, print_ty),
1271 fn pretty_print_const_scalar_ptr(
1276 ) -> Result<Self::Const, Self::Error> {
1277 define_scoped_cx!(self);
1279 let (alloc_id, offset) = ptr.into_parts();
1281 // Byte strings (&[u8; N])
1282 ty::Ref(_, inner, _) => {
1283 if let ty::Array(elem, len) = inner.kind() {
1284 if let ty::Uint(ty::UintTy::U8) = elem.kind() {
1285 if let ty::ConstKind::Value(ty::ValTree::Leaf(int)) = len.kind() {
1286 match self.tcx().try_get_global_alloc(alloc_id) {
1287 Some(GlobalAlloc::Memory(alloc)) => {
1288 let len = int.assert_bits(self.tcx().data_layout.pointer_size);
1290 AllocRange { start: offset, size: Size::from_bytes(len) };
1291 if let Ok(byte_str) =
1292 alloc.inner().get_bytes_strip_provenance(&self.tcx(), range)
1294 p!(pretty_print_byte_str(byte_str))
1296 p!("<too short allocation>")
1299 // FIXME: for statics, vtables, and functions, we could in principle print more detail.
1300 Some(GlobalAlloc::Static(def_id)) => {
1301 p!(write("<static({:?})>", def_id))
1303 Some(GlobalAlloc::Function(_)) => p!("<function>"),
1304 Some(GlobalAlloc::VTable(..)) => p!("<vtable>"),
1305 None => p!("<dangling pointer>"),
1313 // FIXME: We should probably have a helper method to share code with the "Byte strings"
1314 // printing above (which also has to handle pointers to all sorts of things).
1315 if let Some(GlobalAlloc::Function(instance)) =
1316 self.tcx().try_get_global_alloc(alloc_id)
1318 self = self.typed_value(
1319 |this| this.print_value_path(instance.def_id(), instance.substs),
1320 |this| this.print_type(ty),
1328 // Any pointer values not covered by a branch above
1329 self = self.pretty_print_const_pointer(ptr, ty, print_ty)?;
1333 fn pretty_print_const_scalar_int(
1338 ) -> Result<Self::Const, Self::Error> {
1339 define_scoped_cx!(self);
1343 ty::Bool if int == ScalarInt::FALSE => p!("false"),
1344 ty::Bool if int == ScalarInt::TRUE => p!("true"),
1346 ty::Float(ty::FloatTy::F32) => {
1347 p!(write("{}f32", Single::try_from(int).unwrap()))
1349 ty::Float(ty::FloatTy::F64) => {
1350 p!(write("{}f64", Double::try_from(int).unwrap()))
1353 ty::Uint(_) | ty::Int(_) => {
1355 ConstInt::new(int, matches!(ty.kind(), ty::Int(_)), ty.is_ptr_sized_integral());
1356 if print_ty { p!(write("{:#?}", int)) } else { p!(write("{:?}", int)) }
1359 ty::Char if char::try_from(int).is_ok() => {
1360 p!(write("{:?}", char::try_from(int).unwrap()))
1363 ty::Ref(..) | ty::RawPtr(_) | ty::FnPtr(_) => {
1364 let data = int.assert_bits(self.tcx().data_layout.pointer_size);
1365 self = self.typed_value(
1367 write!(this, "0x{:x}", data)?;
1370 |this| this.print_type(ty),
1374 // Nontrivial types with scalar bit representation
1376 let print = |mut this: Self| {
1377 if int.size() == Size::ZERO {
1378 write!(this, "transmute(())")?;
1380 write!(this, "transmute(0x{:x})", int)?;
1384 self = if print_ty {
1385 self.typed_value(print, |this| this.print_type(ty), ": ")?
1394 /// This is overridden for MIR printing because we only want to hide alloc ids from users, not
1395 /// from MIR where it is actually useful.
1396 fn pretty_print_const_pointer<Prov: Provenance>(
1401 ) -> Result<Self::Const, Self::Error> {
1405 this.write_str("&_")?;
1408 |this| this.print_type(ty),
1412 self.write_str("&_")?;
1417 fn pretty_print_byte_str(mut self, byte_str: &'tcx [u8]) -> Result<Self::Const, Self::Error> {
1418 write!(self, "b\"{}\"", byte_str.escape_ascii())?;
1422 fn pretty_print_const_valtree(
1424 valtree: ty::ValTree<'tcx>,
1427 ) -> Result<Self::Const, Self::Error> {
1428 define_scoped_cx!(self);
1430 if self.should_print_verbose() {
1431 p!(write("ValTree({:?}: ", valtree), print(ty), ")");
1435 let u8_type = self.tcx().types.u8;
1436 match (valtree, ty.kind()) {
1437 (ty::ValTree::Branch(_), ty::Ref(_, inner_ty, _)) => match inner_ty.kind() {
1438 ty::Slice(t) if *t == u8_type => {
1439 let bytes = valtree.try_to_raw_bytes(self.tcx(), ty).unwrap_or_else(|| {
1441 "expected to convert valtree {:?} to raw bytes for type {:?}",
1446 return self.pretty_print_byte_str(bytes);
1449 let bytes = valtree.try_to_raw_bytes(self.tcx(), ty).unwrap_or_else(|| {
1450 bug!("expected to convert valtree to raw bytes for type {:?}", ty)
1452 p!(write("{:?}", String::from_utf8_lossy(bytes)));
1457 p!(pretty_print_const_valtree(valtree, *inner_ty, print_ty));
1461 (ty::ValTree::Branch(_), ty::Array(t, _)) if *t == u8_type => {
1462 let bytes = valtree.try_to_raw_bytes(self.tcx(), ty).unwrap_or_else(|| {
1463 bug!("expected to convert valtree to raw bytes for type {:?}", t)
1466 p!(pretty_print_byte_str(bytes));
1469 // Aggregates, printed as array/tuple/struct/variant construction syntax.
1470 (ty::ValTree::Branch(_), ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) => {
1472 self.tcx().destructure_const(ty::Const::from_value(self.tcx(), valtree, ty));
1473 let fields = contents.fields.iter().copied();
1476 p!("[", comma_sep(fields), "]");
1479 p!("(", comma_sep(fields));
1480 if contents.fields.len() == 1 {
1485 ty::Adt(def, _) if def.variants().is_empty() => {
1486 self = self.typed_value(
1488 write!(this, "unreachable()")?;
1491 |this| this.print_type(ty),
1495 ty::Adt(def, substs) => {
1497 contents.variant.expect("destructed const of adt without variant idx");
1498 let variant_def = &def.variant(variant_idx);
1499 p!(print_value_path(variant_def.def_id, substs));
1500 match variant_def.ctor_kind() {
1501 Some(CtorKind::Const) => {}
1502 Some(CtorKind::Fn) => {
1503 p!("(", comma_sep(fields), ")");
1507 let mut first = true;
1508 for (field_def, field) in iter::zip(&variant_def.fields, fields) {
1512 p!(write("{}: ", field_def.name), print(field));
1519 _ => unreachable!(),
1523 (ty::ValTree::Leaf(leaf), ty::Ref(_, inner_ty, _)) => {
1525 return self.pretty_print_const_scalar_int(leaf, *inner_ty, print_ty);
1527 (ty::ValTree::Leaf(leaf), _) => {
1528 return self.pretty_print_const_scalar_int(leaf, ty, print_ty);
1530 // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
1531 // their fields instead of just dumping the memory.
1536 if valtree == ty::ValTree::zst() {
1539 p!(write("{:?}", valtree));
1542 p!(": ", print(ty));
1547 fn pretty_closure_as_impl(
1549 closure: ty::ClosureSubsts<'tcx>,
1550 ) -> Result<Self::Const, Self::Error> {
1551 let sig = closure.sig();
1552 let kind = closure.kind_ty().to_opt_closure_kind().unwrap_or(ty::ClosureKind::Fn);
1554 write!(self, "impl ")?;
1555 self.wrap_binder(&sig, |sig, mut cx| {
1556 define_scoped_cx!(cx);
1558 p!(print(kind), "(");
1559 for (i, arg) in sig.inputs()[0].tuple_fields().iter().enumerate() {
1567 if !sig.output().is_unit() {
1568 p!(" -> ", print(sig.output()));
1575 fn should_print_verbose(&self) -> bool {
1576 self.tcx().sess.verbose()
1580 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
1581 pub struct FmtPrinter<'a, 'tcx>(Box<FmtPrinterData<'a, 'tcx>>);
1583 pub struct FmtPrinterData<'a, 'tcx> {
1589 pub print_alloc_ids: bool,
1591 // set of all named (non-anonymous) region names
1592 used_region_names: FxHashSet<Symbol>,
1594 region_index: usize,
1595 binder_depth: usize,
1596 printed_type_count: usize,
1597 type_length_limit: Limit,
1600 pub region_highlight_mode: RegionHighlightMode<'tcx>,
1602 pub ty_infer_name_resolver: Option<Box<dyn Fn(ty::TyVid) -> Option<Symbol> + 'a>>,
1603 pub const_infer_name_resolver: Option<Box<dyn Fn(ty::ConstVid<'tcx>) -> Option<Symbol> + 'a>>,
1606 impl<'a, 'tcx> Deref for FmtPrinter<'a, 'tcx> {
1607 type Target = FmtPrinterData<'a, 'tcx>;
1608 fn deref(&self) -> &Self::Target {
1613 impl DerefMut for FmtPrinter<'_, '_> {
1614 fn deref_mut(&mut self) -> &mut Self::Target {
1619 impl<'a, 'tcx> FmtPrinter<'a, 'tcx> {
1620 pub fn new(tcx: TyCtxt<'tcx>, ns: Namespace) -> Self {
1621 Self::new_with_limit(tcx, ns, tcx.type_length_limit())
1624 pub fn new_with_limit(tcx: TyCtxt<'tcx>, ns: Namespace, type_length_limit: Limit) -> Self {
1625 FmtPrinter(Box::new(FmtPrinterData {
1627 // Estimated reasonable capacity to allocate upfront based on a few
1629 fmt: String::with_capacity(64),
1631 in_value: ns == Namespace::ValueNS,
1632 print_alloc_ids: false,
1633 used_region_names: Default::default(),
1636 printed_type_count: 0,
1639 region_highlight_mode: RegionHighlightMode::new(tcx),
1640 ty_infer_name_resolver: None,
1641 const_infer_name_resolver: None,
1645 pub fn into_buffer(self) -> String {
1650 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1651 // (but also some things just print a `DefId` generally so maybe we need this?)
1652 fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
1653 match tcx.def_key(def_id).disambiguated_data.data {
1654 DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::ImplTrait => {
1658 DefPathData::ValueNs(..)
1659 | DefPathData::AnonConst
1660 | DefPathData::ClosureExpr
1661 | DefPathData::Ctor => Namespace::ValueNS,
1663 DefPathData::MacroNs(..) => Namespace::MacroNS,
1665 _ => Namespace::TypeNS,
1669 impl<'t> TyCtxt<'t> {
1670 /// Returns a string identifying this `DefId`. This string is
1671 /// suitable for user output.
1672 pub fn def_path_str(self, def_id: DefId) -> String {
1673 self.def_path_str_with_substs(def_id, &[])
1676 pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1677 let ns = guess_def_namespace(self, def_id);
1678 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1679 FmtPrinter::new(self, ns).print_def_path(def_id, substs).unwrap().into_buffer()
1682 pub fn value_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1683 let ns = guess_def_namespace(self, def_id);
1684 debug!("value_path_str: def_id={:?}, ns={:?}", def_id, ns);
1685 FmtPrinter::new(self, ns).print_value_path(def_id, substs).unwrap().into_buffer()
1689 impl fmt::Write for FmtPrinter<'_, '_> {
1690 fn write_str(&mut self, s: &str) -> fmt::Result {
1691 self.fmt.push_str(s);
1696 impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> {
1697 type Error = fmt::Error;
1702 type DynExistential = Self;
1705 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
1712 substs: &'tcx [GenericArg<'tcx>],
1713 ) -> Result<Self::Path, Self::Error> {
1714 define_scoped_cx!(self);
1716 if substs.is_empty() {
1717 match self.try_print_trimmed_def_path(def_id)? {
1718 (cx, true) => return Ok(cx),
1719 (cx, false) => self = cx,
1722 match self.try_print_visible_def_path(def_id)? {
1723 (cx, true) => return Ok(cx),
1724 (cx, false) => self = cx,
1728 let key = self.tcx.def_key(def_id);
1729 if let DefPathData::Impl = key.disambiguated_data.data {
1730 // Always use types for non-local impls, where types are always
1731 // available, and filename/line-number is mostly uninteresting.
1732 let use_types = !def_id.is_local() || {
1733 // Otherwise, use filename/line-number if forced.
1734 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1739 // If no type info is available, fall back to
1740 // pretty printing some span information. This should
1741 // only occur very early in the compiler pipeline.
1742 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1743 let span = self.tcx.def_span(def_id);
1745 self = self.print_def_path(parent_def_id, &[])?;
1747 // HACK(eddyb) copy of `path_append` to avoid
1748 // constructing a `DisambiguatedDefPathData`.
1749 if !self.empty_path {
1750 write!(self, "::")?;
1755 // This may end up in stderr diagnostics but it may also be emitted
1756 // into MIR. Hence we use the remapped path if available
1757 self.tcx.sess.source_map().span_to_embeddable_string(span)
1759 self.empty_path = false;
1765 self.default_print_def_path(def_id, substs)
1768 fn print_region(self, region: ty::Region<'tcx>) -> Result<Self::Region, Self::Error> {
1769 self.pretty_print_region(region)
1772 fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1773 if self.type_length_limit.value_within_limit(self.printed_type_count) {
1774 self.printed_type_count += 1;
1775 self.pretty_print_type(ty)
1777 self.truncated = true;
1778 write!(self, "...")?;
1783 fn print_dyn_existential(
1785 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1786 ) -> Result<Self::DynExistential, Self::Error> {
1787 self.pretty_print_dyn_existential(predicates)
1790 fn print_const(self, ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1791 self.pretty_print_const(ct, false)
1794 fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1795 self.empty_path = true;
1796 if cnum == LOCAL_CRATE {
1797 if self.tcx.sess.rust_2018() {
1798 // We add the `crate::` keyword on Rust 2018, only when desired.
1799 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1800 write!(self, "{}", kw::Crate)?;
1801 self.empty_path = false;
1805 write!(self, "{}", self.tcx.crate_name(cnum))?;
1806 self.empty_path = false;
1814 trait_ref: Option<ty::TraitRef<'tcx>>,
1815 ) -> Result<Self::Path, Self::Error> {
1816 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1817 self.empty_path = false;
1821 fn path_append_impl(
1823 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1824 _disambiguated_data: &DisambiguatedDefPathData,
1826 trait_ref: Option<ty::TraitRef<'tcx>>,
1827 ) -> Result<Self::Path, Self::Error> {
1828 self = self.pretty_path_append_impl(
1830 cx = print_prefix(cx)?;
1840 self.empty_path = false;
1846 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1847 disambiguated_data: &DisambiguatedDefPathData,
1848 ) -> Result<Self::Path, Self::Error> {
1849 self = print_prefix(self)?;
1851 // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
1852 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
1856 let name = disambiguated_data.data.name();
1857 if !self.empty_path {
1858 write!(self, "::")?;
1861 if let DefPathDataName::Named(name) = name {
1862 if Ident::with_dummy_span(name).is_raw_guess() {
1863 write!(self, "r#")?;
1867 let verbose = self.should_print_verbose();
1868 disambiguated_data.fmt_maybe_verbose(&mut self, verbose)?;
1870 self.empty_path = false;
1875 fn path_generic_args(
1877 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1878 args: &[GenericArg<'tcx>],
1879 ) -> Result<Self::Path, Self::Error> {
1880 self = print_prefix(self)?;
1882 if args.first().is_some() {
1884 write!(self, "::")?;
1886 self.generic_delimiters(|cx| cx.comma_sep(args.iter().cloned()))
1893 impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> {
1894 fn ty_infer_name(&self, id: ty::TyVid) -> Option<Symbol> {
1895 self.0.ty_infer_name_resolver.as_ref().and_then(|func| func(id))
1898 fn const_infer_name(&self, id: ty::ConstVid<'tcx>) -> Option<Symbol> {
1899 self.0.const_infer_name_resolver.as_ref().and_then(|func| func(id))
1902 fn print_value_path(
1905 substs: &'tcx [GenericArg<'tcx>],
1906 ) -> Result<Self::Path, Self::Error> {
1907 let was_in_value = std::mem::replace(&mut self.in_value, true);
1908 self = self.print_def_path(def_id, substs)?;
1909 self.in_value = was_in_value;
1914 fn in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, Self::Error>
1916 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1918 self.pretty_in_binder(value)
1921 fn wrap_binder<T, C: FnOnce(&T, Self) -> Result<Self, Self::Error>>(
1923 value: &ty::Binder<'tcx, T>,
1925 ) -> Result<Self, Self::Error>
1927 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1929 self.pretty_wrap_binder(value, f)
1934 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1935 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
1937 ) -> Result<Self::Const, Self::Error> {
1938 self.write_str("{")?;
1940 self.write_str(conversion)?;
1941 let was_in_value = std::mem::replace(&mut self.in_value, false);
1943 self.in_value = was_in_value;
1944 self.write_str("}")?;
1948 fn generic_delimiters(
1950 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1951 ) -> Result<Self, Self::Error> {
1954 let was_in_value = std::mem::replace(&mut self.in_value, false);
1955 let mut inner = f(self)?;
1956 inner.in_value = was_in_value;
1958 write!(inner, ">")?;
1962 fn should_print_region(&self, region: ty::Region<'tcx>) -> bool {
1963 let highlight = self.region_highlight_mode;
1964 if highlight.region_highlighted(region).is_some() {
1968 if self.should_print_verbose() {
1972 let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
1975 ty::ReEarlyBound(ref data) => {
1976 data.name != kw::Empty && data.name != kw::UnderscoreLifetime
1979 ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
1980 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1981 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1982 if let ty::BrNamed(_, name) = br {
1983 if name != kw::Empty && name != kw::UnderscoreLifetime {
1988 if let Some((region, _)) = highlight.highlight_bound_region {
1997 ty::ReVar(_) if identify_regions => true,
1999 ty::ReVar(_) | ty::ReErased => false,
2001 ty::ReStatic => true,
2005 fn pretty_print_const_pointer<Prov: Provenance>(
2010 ) -> Result<Self::Const, Self::Error> {
2011 let print = |mut this: Self| {
2012 define_scoped_cx!(this);
2013 if this.print_alloc_ids {
2014 p!(write("{:?}", p));
2021 self.typed_value(print, |this| this.print_type(ty), ": ")
2028 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
2029 impl<'tcx> FmtPrinter<'_, 'tcx> {
2030 pub fn pretty_print_region(mut self, region: ty::Region<'tcx>) -> Result<Self, fmt::Error> {
2031 define_scoped_cx!(self);
2033 // Watch out for region highlights.
2034 let highlight = self.region_highlight_mode;
2035 if let Some(n) = highlight.region_highlighted(region) {
2036 p!(write("'{}", n));
2040 if self.should_print_verbose() {
2041 p!(write("{:?}", region));
2045 let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
2047 // These printouts are concise. They do not contain all the information
2048 // the user might want to diagnose an error, but there is basically no way
2049 // to fit that into a short string. Hence the recommendation to use
2050 // `explain_region()` or `note_and_explain_region()`.
2052 ty::ReEarlyBound(ref data) => {
2053 if data.name != kw::Empty {
2054 p!(write("{}", data.name));
2058 ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
2059 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
2060 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
2061 if let ty::BrNamed(_, name) = br {
2062 if name != kw::Empty && name != kw::UnderscoreLifetime {
2063 p!(write("{}", name));
2068 if let Some((region, counter)) = highlight.highlight_bound_region {
2070 p!(write("'{}", counter));
2075 ty::ReVar(region_vid) if identify_regions => {
2076 p!(write("{:?}", region_vid));
2093 /// Folds through bound vars and placeholders, naming them
2094 struct RegionFolder<'a, 'tcx> {
2096 current_index: ty::DebruijnIndex,
2097 region_map: BTreeMap<ty::BoundRegion, ty::Region<'tcx>>,
2100 Option<ty::DebruijnIndex>, // Debruijn index of the folded late-bound region
2101 ty::DebruijnIndex, // Index corresponding to binder level
2103 ) -> ty::Region<'tcx>
2108 impl<'a, 'tcx> ty::TypeFolder<'tcx> for RegionFolder<'a, 'tcx> {
2109 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
2113 fn fold_binder<T: TypeFoldable<'tcx>>(
2115 t: ty::Binder<'tcx, T>,
2116 ) -> ty::Binder<'tcx, T> {
2117 self.current_index.shift_in(1);
2118 let t = t.super_fold_with(self);
2119 self.current_index.shift_out(1);
2123 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
2125 _ if t.has_vars_bound_at_or_above(self.current_index) || t.has_placeholders() => {
2126 return t.super_fold_with(self);
2133 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
2134 let name = &mut self.name;
2135 let region = match *r {
2136 ty::ReLateBound(db, br) if db >= self.current_index => {
2137 *self.region_map.entry(br).or_insert_with(|| name(Some(db), self.current_index, br))
2139 ty::RePlaceholder(ty::PlaceholderRegion { name: kind, .. }) => {
2140 // If this is an anonymous placeholder, don't rename. Otherwise, in some
2141 // async fns, we get a `for<'r> Send` bound
2143 ty::BrAnon(..) | ty::BrEnv => r,
2145 // Index doesn't matter, since this is just for naming and these never get bound
2146 let br = ty::BoundRegion { var: ty::BoundVar::from_u32(0), kind };
2150 .or_insert_with(|| name(None, self.current_index, br))
2156 if let ty::ReLateBound(debruijn1, br) = *region {
2157 assert_eq!(debruijn1, ty::INNERMOST);
2158 self.tcx.mk_region(ty::ReLateBound(self.current_index, br))
2165 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
2166 // `region_index` and `used_region_names`.
2167 impl<'tcx> FmtPrinter<'_, 'tcx> {
2168 pub fn name_all_regions<T>(
2170 value: &ty::Binder<'tcx, T>,
2171 ) -> Result<(Self, T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>), fmt::Error>
2173 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2175 fn name_by_region_index(
2177 available_names: &mut Vec<Symbol>,
2178 num_available: usize,
2180 if let Some(name) = available_names.pop() {
2183 Symbol::intern(&format!("'z{}", index - num_available))
2187 debug!("name_all_regions");
2189 // Replace any anonymous late-bound regions with named
2190 // variants, using new unique identifiers, so that we can
2191 // clearly differentiate between named and unnamed regions in
2192 // the output. We'll probably want to tweak this over time to
2193 // decide just how much information to give.
2194 if self.binder_depth == 0 {
2195 self.prepare_region_info(value);
2198 debug!("self.used_region_names: {:?}", &self.used_region_names);
2200 let mut empty = true;
2201 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
2208 let _ = write!(cx, "{}", w);
2210 let do_continue = |cx: &mut Self, cont: Symbol| {
2211 let _ = write!(cx, "{}", cont);
2214 define_scoped_cx!(self);
2216 let possible_names = ('a'..='z').rev().map(|s| Symbol::intern(&format!("'{s}")));
2218 let mut available_names = possible_names
2219 .filter(|name| !self.used_region_names.contains(&name))
2220 .collect::<Vec<_>>();
2221 debug!(?available_names);
2222 let num_available = available_names.len();
2224 let mut region_index = self.region_index;
2225 let mut next_name = |this: &Self| {
2229 name = name_by_region_index(region_index, &mut available_names, num_available);
2232 if !this.used_region_names.contains(&name) {
2240 // If we want to print verbosely, then print *all* binders, even if they
2241 // aren't named. Eventually, we might just want this as the default, but
2242 // this is not *quite* right and changes the ordering of some output
2244 let (new_value, map) = if self.should_print_verbose() {
2245 for var in value.bound_vars().iter() {
2246 start_or_continue(&mut self, "for<", ", ");
2247 write!(self, "{:?}", var)?;
2249 start_or_continue(&mut self, "", "> ");
2250 (value.clone().skip_binder(), BTreeMap::default())
2254 // Closure used in `RegionFolder` to create names for anonymous late-bound
2255 // regions. We use two `DebruijnIndex`es (one for the currently folded
2256 // late-bound region and the other for the binder level) to determine
2257 // whether a name has already been created for the currently folded region,
2258 // see issue #102392.
2259 let mut name = |lifetime_idx: Option<ty::DebruijnIndex>,
2260 binder_level_idx: ty::DebruijnIndex,
2261 br: ty::BoundRegion| {
2262 let (name, kind) = match br.kind {
2263 ty::BrAnon(..) | ty::BrEnv => {
2264 let name = next_name(&self);
2266 if let Some(lt_idx) = lifetime_idx {
2267 if lt_idx > binder_level_idx {
2268 let kind = ty::BrNamed(CRATE_DEF_ID.to_def_id(), name);
2269 return tcx.mk_region(ty::ReLateBound(
2271 ty::BoundRegion { var: br.var, kind },
2276 (name, ty::BrNamed(CRATE_DEF_ID.to_def_id(), name))
2278 ty::BrNamed(def_id, kw::UnderscoreLifetime) => {
2279 let name = next_name(&self);
2281 if let Some(lt_idx) = lifetime_idx {
2282 if lt_idx > binder_level_idx {
2283 let kind = ty::BrNamed(def_id, name);
2284 return tcx.mk_region(ty::ReLateBound(
2286 ty::BoundRegion { var: br.var, kind },
2291 (name, ty::BrNamed(def_id, name))
2293 ty::BrNamed(_, name) => {
2294 if let Some(lt_idx) = lifetime_idx {
2295 if lt_idx > binder_level_idx {
2297 return tcx.mk_region(ty::ReLateBound(
2299 ty::BoundRegion { var: br.var, kind },
2308 start_or_continue(&mut self, "for<", ", ");
2309 do_continue(&mut self, name);
2310 tcx.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BoundRegion { var: br.var, kind }))
2312 let mut folder = RegionFolder {
2314 current_index: ty::INNERMOST,
2316 region_map: BTreeMap::new(),
2318 let new_value = value.clone().skip_binder().fold_with(&mut folder);
2319 let region_map = folder.region_map;
2320 start_or_continue(&mut self, "", "> ");
2321 (new_value, region_map)
2324 self.binder_depth += 1;
2325 self.region_index = region_index;
2326 Ok((self, new_value, map))
2329 pub fn pretty_in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, fmt::Error>
2331 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2333 let old_region_index = self.region_index;
2334 let (new, new_value, _) = self.name_all_regions(value)?;
2335 let mut inner = new_value.print(new)?;
2336 inner.region_index = old_region_index;
2337 inner.binder_depth -= 1;
2341 pub fn pretty_wrap_binder<T, C: FnOnce(&T, Self) -> Result<Self, fmt::Error>>(
2343 value: &ty::Binder<'tcx, T>,
2345 ) -> Result<Self, fmt::Error>
2347 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2349 let old_region_index = self.region_index;
2350 let (new, new_value, _) = self.name_all_regions(value)?;
2351 let mut inner = f(&new_value, new)?;
2352 inner.region_index = old_region_index;
2353 inner.binder_depth -= 1;
2357 fn prepare_region_info<T>(&mut self, value: &ty::Binder<'tcx, T>)
2359 T: TypeVisitable<'tcx>,
2361 struct RegionNameCollector<'tcx> {
2362 used_region_names: FxHashSet<Symbol>,
2363 type_collector: SsoHashSet<Ty<'tcx>>,
2366 impl<'tcx> RegionNameCollector<'tcx> {
2368 RegionNameCollector {
2369 used_region_names: Default::default(),
2370 type_collector: SsoHashSet::new(),
2375 impl<'tcx> ty::visit::TypeVisitor<'tcx> for RegionNameCollector<'tcx> {
2378 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
2379 trace!("address: {:p}", r.0.0);
2381 // Collect all named lifetimes. These allow us to prevent duplication
2382 // of already existing lifetime names when introducing names for
2383 // anonymous late-bound regions.
2384 if let Some(name) = r.get_name() {
2385 self.used_region_names.insert(name);
2388 r.super_visit_with(self)
2391 // We collect types in order to prevent really large types from compiling for
2392 // a really long time. See issue #83150 for why this is necessary.
2393 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
2394 let not_previously_inserted = self.type_collector.insert(ty);
2395 if not_previously_inserted {
2396 ty.super_visit_with(self)
2398 ControlFlow::CONTINUE
2403 let mut collector = RegionNameCollector::new();
2404 value.visit_with(&mut collector);
2405 self.used_region_names = collector.used_region_names;
2406 self.region_index = 0;
2410 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<'tcx, T>
2412 T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
2415 type Error = P::Error;
2417 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
2422 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
2424 T: Print<'tcx, P, Output = P, Error = P::Error>,
2425 U: Print<'tcx, P, Output = P, Error = P::Error>,
2428 type Error = P::Error;
2429 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
2430 define_scoped_cx!(cx);
2431 p!(print(self.0), ": ", print(self.1));
2436 macro_rules! forward_display_to_print {
2438 // Some of the $ty arguments may not actually use 'tcx
2439 $(#[allow(unused_lifetimes)] impl<'tcx> fmt::Display for $ty {
2440 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2441 ty::tls::with(|tcx| {
2442 let cx = tcx.lift(*self)
2443 .expect("could not lift for printing")
2444 .print(FmtPrinter::new(tcx, Namespace::TypeNS))?;
2445 f.write_str(&cx.into_buffer())?;
2453 macro_rules! define_print_and_forward_display {
2454 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
2455 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
2457 type Error = fmt::Error;
2458 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
2459 #[allow(unused_mut)]
2461 define_scoped_cx!($cx);
2463 #[allow(unreachable_code)]
2468 forward_display_to_print!($($ty),+);
2472 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2473 /// the trait path. That is, it will print `Trait<U>` instead of
2474 /// `<T as Trait<U>>`.
2475 #[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
2476 pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
2478 impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
2479 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2480 fmt::Display::fmt(self, f)
2484 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2485 /// the trait name. That is, it will print `Trait` instead of
2486 /// `<T as Trait<U>>`.
2487 #[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
2488 pub struct TraitRefPrintOnlyTraitName<'tcx>(ty::TraitRef<'tcx>);
2490 impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitName<'tcx> {
2491 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2492 fmt::Display::fmt(self, f)
2496 impl<'tcx> ty::TraitRef<'tcx> {
2497 pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
2498 TraitRefPrintOnlyTraitPath(self)
2501 pub fn print_only_trait_name(self) -> TraitRefPrintOnlyTraitName<'tcx> {
2502 TraitRefPrintOnlyTraitName(self)
2506 impl<'tcx> ty::Binder<'tcx, ty::TraitRef<'tcx>> {
2507 pub fn print_only_trait_path(self) -> ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>> {
2508 self.map_bound(|tr| tr.print_only_trait_path())
2512 #[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
2513 pub struct TraitPredPrintModifiersAndPath<'tcx>(ty::TraitPredicate<'tcx>);
2515 impl<'tcx> fmt::Debug for TraitPredPrintModifiersAndPath<'tcx> {
2516 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2517 fmt::Display::fmt(self, f)
2521 impl<'tcx> ty::TraitPredicate<'tcx> {
2522 pub fn print_modifiers_and_trait_path(self) -> TraitPredPrintModifiersAndPath<'tcx> {
2523 TraitPredPrintModifiersAndPath(self)
2527 impl<'tcx> ty::PolyTraitPredicate<'tcx> {
2528 pub fn print_modifiers_and_trait_path(
2530 ) -> ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>> {
2531 self.map_bound(TraitPredPrintModifiersAndPath)
2535 #[derive(Debug, Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
2536 pub struct PrintClosureAsImpl<'tcx> {
2537 pub closure: ty::ClosureSubsts<'tcx>,
2540 forward_display_to_print! {
2543 &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2546 // HACK(eddyb) these are exhaustive instead of generic,
2547 // because `for<'tcx>` isn't possible yet.
2548 ty::PolyExistentialPredicate<'tcx>,
2549 ty::Binder<'tcx, ty::TraitRef<'tcx>>,
2550 ty::Binder<'tcx, ty::ExistentialTraitRef<'tcx>>,
2551 ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>>,
2552 ty::Binder<'tcx, TraitRefPrintOnlyTraitName<'tcx>>,
2553 ty::Binder<'tcx, ty::FnSig<'tcx>>,
2554 ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2555 ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>>,
2556 ty::Binder<'tcx, ty::SubtypePredicate<'tcx>>,
2557 ty::Binder<'tcx, ty::ProjectionPredicate<'tcx>>,
2558 ty::Binder<'tcx, ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
2559 ty::Binder<'tcx, ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
2561 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
2562 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
2565 define_print_and_forward_display! {
2568 &'tcx ty::List<Ty<'tcx>> {
2569 p!("{{", comma_sep(self.iter()), "}}")
2572 ty::TypeAndMut<'tcx> {
2573 p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
2576 ty::ExistentialTraitRef<'tcx> {
2577 // Use a type that can't appear in defaults of type parameters.
2578 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
2579 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
2580 p!(print(trait_ref.print_only_trait_path()))
2583 ty::ExistentialProjection<'tcx> {
2584 let name = cx.tcx().associated_item(self.item_def_id).name;
2585 p!(write("{} = ", name), print(self.term))
2588 ty::ExistentialPredicate<'tcx> {
2590 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
2591 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
2592 ty::ExistentialPredicate::AutoTrait(def_id) => {
2593 p!(print_def_path(def_id, &[]));
2599 p!(write("{}", self.unsafety.prefix_str()));
2601 if self.abi != Abi::Rust {
2602 p!(write("extern {} ", self.abi));
2605 p!("fn", pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
2608 ty::TraitRef<'tcx> {
2609 p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
2612 TraitRefPrintOnlyTraitPath<'tcx> {
2613 p!(print_def_path(self.0.def_id, self.0.substs));
2616 TraitRefPrintOnlyTraitName<'tcx> {
2617 p!(print_def_path(self.0.def_id, &[]));
2620 TraitPredPrintModifiersAndPath<'tcx> {
2621 if let ty::BoundConstness::ConstIfConst = self.0.constness {
2625 if let ty::ImplPolarity::Negative = self.0.polarity {
2629 p!(print(self.0.trait_ref.print_only_trait_path()));
2632 PrintClosureAsImpl<'tcx> {
2633 p!(pretty_closure_as_impl(self.closure))
2637 p!(write("{}", self.name))
2641 p!(write("{}", self.name))
2644 ty::SubtypePredicate<'tcx> {
2645 p!(print(self.a), " <: ", print(self.b))
2648 ty::CoercePredicate<'tcx> {
2649 p!(print(self.a), " -> ", print(self.b))
2652 ty::TraitPredicate<'tcx> {
2653 p!(print(self.trait_ref.self_ty()), ": ");
2654 if let ty::BoundConstness::ConstIfConst = self.constness && cx.tcx().features().const_trait_impl {
2657 p!(print(self.trait_ref.print_only_trait_path()))
2660 ty::ProjectionPredicate<'tcx> {
2661 p!(print(self.projection_ty), " == ", print(self.term))
2665 match self.unpack() {
2666 ty::TermKind::Ty(ty) => p!(print(ty)),
2667 ty::TermKind::Const(c) => p!(print(c)),
2671 ty::ProjectionTy<'tcx> {
2672 p!(print_def_path(self.item_def_id, self.substs));
2677 ty::ClosureKind::Fn => p!("Fn"),
2678 ty::ClosureKind::FnMut => p!("FnMut"),
2679 ty::ClosureKind::FnOnce => p!("FnOnce"),
2683 ty::Predicate<'tcx> {
2684 let binder = self.kind();
2688 ty::PredicateKind<'tcx> {
2690 ty::PredicateKind::Clause(ty::Clause::Trait(ref data)) => {
2693 ty::PredicateKind::Subtype(predicate) => p!(print(predicate)),
2694 ty::PredicateKind::Coerce(predicate) => p!(print(predicate)),
2695 ty::PredicateKind::Clause(ty::Clause::RegionOutlives(predicate)) => p!(print(predicate)),
2696 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(predicate)) => p!(print(predicate)),
2697 ty::PredicateKind::Clause(ty::Clause::Projection(predicate)) => p!(print(predicate)),
2698 ty::PredicateKind::WellFormed(arg) => p!(print(arg), " well-formed"),
2699 ty::PredicateKind::ObjectSafe(trait_def_id) => {
2700 p!("the trait `", print_def_path(trait_def_id, &[]), "` is object-safe")
2702 ty::PredicateKind::ClosureKind(closure_def_id, _closure_substs, kind) => {
2704 print_value_path(closure_def_id, &[]),
2705 write("` implements the trait `{}`", kind))
2707 ty::PredicateKind::ConstEvaluatable(ct) => {
2708 p!("the constant `", print(ct), "` can be evaluated")
2710 ty::PredicateKind::ConstEquate(c1, c2) => {
2711 p!("the constant `", print(c1), "` equals `", print(c2), "`")
2713 ty::PredicateKind::TypeWellFormedFromEnv(ty) => {
2714 p!("the type `", print(ty), "` is found in the environment")
2716 ty::PredicateKind::Ambiguous => p!("ambiguous"),
2721 match self.unpack() {
2722 GenericArgKind::Lifetime(lt) => p!(print(lt)),
2723 GenericArgKind::Type(ty) => p!(print(ty)),
2724 GenericArgKind::Const(ct) => p!(print(ct)),
2729 fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
2730 // Iterate all local crate items no matter where they are defined.
2731 let hir = tcx.hir();
2732 for id in hir.items() {
2733 if matches!(tcx.def_kind(id.owner_id), DefKind::Use) {
2737 let item = hir.item(id);
2738 if item.ident.name == kw::Empty {
2742 let def_id = item.owner_id.to_def_id();
2743 let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
2744 collect_fn(&item.ident, ns, def_id);
2747 // Now take care of extern crate items.
2748 let queue = &mut Vec::new();
2749 let mut seen_defs: DefIdSet = Default::default();
2751 for &cnum in tcx.crates(()).iter() {
2752 let def_id = cnum.as_def_id();
2754 // Ignore crates that are not direct dependencies.
2755 match tcx.extern_crate(def_id) {
2757 Some(extern_crate) => {
2758 if !extern_crate.is_direct() {
2767 // Iterate external crate defs but be mindful about visibility
2768 while let Some(def) = queue.pop() {
2769 for child in tcx.module_children(def).iter() {
2770 if !child.vis.is_public() {
2775 def::Res::Def(DefKind::AssocTy, _) => {}
2776 def::Res::Def(DefKind::TyAlias, _) => {}
2777 def::Res::Def(defkind, def_id) => {
2778 if let Some(ns) = defkind.ns() {
2779 collect_fn(&child.ident, ns, def_id);
2782 if matches!(defkind, DefKind::Mod | DefKind::Enum | DefKind::Trait)
2783 && seen_defs.insert(def_id)
2794 /// The purpose of this function is to collect public symbols names that are unique across all
2795 /// crates in the build. Later, when printing about types we can use those names instead of the
2796 /// full exported path to them.
2798 /// So essentially, if a symbol name can only be imported from one place for a type, and as
2799 /// long as it was not glob-imported anywhere in the current crate, we can trim its printed
2800 /// path and print only the name.
2802 /// This has wide implications on error messages with types, for example, shortening
2803 /// `std::vec::Vec` to just `Vec`, as long as there is no other `Vec` importable anywhere.
2805 /// The implementation uses similar import discovery logic to that of 'use' suggestions.
2806 fn trimmed_def_paths(tcx: TyCtxt<'_>, (): ()) -> FxHashMap<DefId, Symbol> {
2807 let mut map: FxHashMap<DefId, Symbol> = FxHashMap::default();
2809 if let TrimmedDefPaths::GoodPath = tcx.sess.opts.trimmed_def_paths {
2810 // For good paths causing this bug, the `rustc_middle::ty::print::with_no_trimmed_paths`
2811 // wrapper can be used to suppress this query, in exchange for full paths being formatted.
2812 tcx.sess.delay_good_path_bug("trimmed_def_paths constructed");
2815 let unique_symbols_rev: &mut FxHashMap<(Namespace, Symbol), Option<DefId>> =
2816 &mut FxHashMap::default();
2818 for symbol_set in tcx.resolutions(()).glob_map.values() {
2819 for symbol in symbol_set {
2820 unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
2821 unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
2822 unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
2826 for_each_def(tcx, |ident, ns, def_id| {
2827 use std::collections::hash_map::Entry::{Occupied, Vacant};
2829 match unique_symbols_rev.entry((ns, ident.name)) {
2830 Occupied(mut v) => match v.get() {
2833 if *existing != def_id {
2839 v.insert(Some(def_id));
2844 for ((_, symbol), opt_def_id) in unique_symbols_rev.drain() {
2845 use std::collections::hash_map::Entry::{Occupied, Vacant};
2847 if let Some(def_id) = opt_def_id {
2848 match map.entry(def_id) {
2849 Occupied(mut v) => {
2850 // A single DefId can be known under multiple names (e.g.,
2851 // with a `pub use ... as ...;`). We need to ensure that the
2852 // name placed in this map is chosen deterministically, so
2853 // if we find multiple names (`symbol`) resolving to the
2854 // same `def_id`, we prefer the lexicographically smallest
2857 // Any stable ordering would be fine here though.
2858 if *v.get() != symbol {
2859 if v.get().as_str() > symbol.as_str() {
2874 pub fn provide(providers: &mut ty::query::Providers) {
2875 *providers = ty::query::Providers { trimmed_def_paths, ..*providers };
2879 pub struct OpaqueFnEntry<'tcx> {
2880 // The trait ref is already stored as a key, so just track if we have it as a real predicate
2882 fn_mut_trait_ref: Option<ty::PolyTraitRef<'tcx>>,
2883 fn_trait_ref: Option<ty::PolyTraitRef<'tcx>>,
2884 return_ty: Option<ty::Binder<'tcx, Term<'tcx>>>,