1 use crate::mir::interpret::{AllocRange, ConstValue, GlobalAlloc, Pointer, Provenance, Scalar};
2 use crate::ty::subst::{GenericArg, GenericArgKind, Subst};
3 use crate::ty::{self, ConstInt, DefIdTree, ParamConst, ScalarInt, Ty, TyCtxt, TypeFoldable};
4 use rustc_apfloat::ieee::{Double, Single};
5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_data_structures::sso::SsoHashSet;
8 use rustc_hir::def::{self, CtorKind, DefKind, Namespace};
9 use rustc_hir::def_id::{DefId, DefIdSet, CRATE_DEF_INDEX, LOCAL_CRATE};
10 use rustc_hir::definitions::{DefPathData, DefPathDataName, DisambiguatedDefPathData};
11 use rustc_hir::ItemKind;
12 use rustc_session::config::TrimmedDefPaths;
13 use rustc_session::cstore::{ExternCrate, ExternCrateSource};
14 use rustc_span::symbol::{kw, Ident, Symbol};
15 use rustc_target::abi::Size;
16 use rustc_target::spec::abi::Abi;
20 use std::collections::BTreeMap;
21 use std::convert::TryFrom;
22 use std::fmt::{self, Write as _};
24 use std::ops::{ControlFlow, Deref, DerefMut};
26 // `pretty` is a separate module only for organization.
31 write!(scoped_cx!(), $lit)?
33 (@write($($data:expr),+)) => {
34 write!(scoped_cx!(), $($data),+)?
36 (@print($x:expr)) => {
37 scoped_cx!() = $x.print(scoped_cx!())?
39 (@$method:ident($($arg:expr),*)) => {
40 scoped_cx!() = scoped_cx!().$method($($arg),*)?
42 ($($elem:tt $(($($args:tt)*))?),+) => {{
43 $(p!(@ $elem $(($($args)*))?);)+
46 macro_rules! define_scoped_cx {
48 #[allow(unused_macros)]
49 macro_rules! scoped_cx {
58 static FORCE_IMPL_FILENAME_LINE: Cell<bool> = const { Cell::new(false) };
59 static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = const { Cell::new(false) };
60 static NO_TRIMMED_PATH: Cell<bool> = const { Cell::new(false) };
61 static NO_QUERIES: Cell<bool> = const { Cell::new(false) };
62 static NO_VISIBLE_PATH: Cell<bool> = const { Cell::new(false) };
65 /// Avoids running any queries during any prints that occur
66 /// during the closure. This may alter the appearance of some
67 /// types (e.g. forcing verbose printing for opaque types).
68 /// This method is used during some queries (e.g. `explicit_item_bounds`
69 /// for opaque types), to ensure that any debug printing that
70 /// occurs during the query computation does not end up recursively
71 /// calling the same query.
72 pub fn with_no_queries<F: FnOnce() -> R, R>(f: F) -> R {
73 NO_QUERIES.with(|no_queries| {
74 let old = no_queries.replace(true);
81 /// Force us to name impls with just the filename/line number. We
82 /// normally try to use types. But at some points, notably while printing
83 /// cycle errors, this can result in extra or suboptimal error output,
84 /// so this variable disables that check.
85 pub fn with_forced_impl_filename_line<F: FnOnce() -> R, R>(f: F) -> R {
86 FORCE_IMPL_FILENAME_LINE.with(|force| {
87 let old = force.replace(true);
94 /// Adds the `crate::` prefix to paths where appropriate.
95 pub fn with_crate_prefix<F: FnOnce() -> R, R>(f: F) -> R {
96 SHOULD_PREFIX_WITH_CRATE.with(|flag| {
97 let old = flag.replace(true);
104 /// Prevent path trimming if it is turned on. Path trimming affects `Display` impl
105 /// of various rustc types, for example `std::vec::Vec` would be trimmed to `Vec`,
106 /// if no other `Vec` is found.
107 pub fn with_no_trimmed_paths<F: FnOnce() -> R, R>(f: F) -> R {
108 NO_TRIMMED_PATH.with(|flag| {
109 let old = flag.replace(true);
116 /// Prevent selection of visible paths. `Display` impl of DefId will prefer visible (public) reexports of types as paths.
117 pub fn with_no_visible_paths<F: FnOnce() -> R, R>(f: F) -> R {
118 NO_VISIBLE_PATH.with(|flag| {
119 let old = flag.replace(true);
126 /// The "region highlights" are used to control region printing during
127 /// specific error messages. When a "region highlight" is enabled, it
128 /// gives an alternate way to print specific regions. For now, we
129 /// always print those regions using a number, so something like "`'0`".
131 /// Regions not selected by the region highlight mode are presently
133 #[derive(Copy, Clone, Default)]
134 pub struct RegionHighlightMode {
135 /// If enabled, when we see the selected region, use "`'N`"
136 /// instead of the ordinary behavior.
137 highlight_regions: [Option<(ty::RegionKind, 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 RegionHighlightMode {
150 /// If `region` and `number` are both `Some`, invokes
151 /// `highlighting_region`.
152 pub fn maybe_highlighting_region(
154 region: Option<ty::Region<'_>>,
155 number: Option<usize>,
157 if let Some(k) = region {
158 if let Some(n) = number {
159 self.highlighting_region(k, n);
164 /// Highlights the region inference variable `vid` as `'N`.
165 pub fn highlighting_region(&mut self, region: ty::Region<'_>, number: usize) {
166 let num_slots = self.highlight_regions.len();
167 let first_avail_slot =
168 self.highlight_regions.iter_mut().find(|s| s.is_none()).unwrap_or_else(|| {
169 bug!("can only highlight {} placeholders at a time", num_slots,)
171 *first_avail_slot = Some((*region, number));
174 /// Convenience wrapper for `highlighting_region`.
175 pub fn highlighting_region_vid(&mut self, vid: ty::RegionVid, number: usize) {
176 self.highlighting_region(&ty::ReVar(vid), number)
179 /// Returns `Some(n)` with the number to use for the given region, if any.
180 fn region_highlighted(&self, region: ty::Region<'_>) -> Option<usize> {
181 self.highlight_regions.iter().find_map(|h| match h {
182 Some((r, n)) if r == region => Some(*n),
187 /// Highlight the given bound region.
188 /// We can only highlight one bound region at a time. See
189 /// the field `highlight_bound_region` for more detailed notes.
190 pub fn highlighting_bound_region(&mut self, br: ty::BoundRegionKind, number: usize) {
191 assert!(self.highlight_bound_region.is_none());
192 self.highlight_bound_region = Some((br, number));
196 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
197 pub trait PrettyPrinter<'tcx>:
204 DynExistential = Self,
208 /// Like `print_def_path` but for value paths.
212 substs: &'tcx [GenericArg<'tcx>],
213 ) -> Result<Self::Path, Self::Error> {
214 self.print_def_path(def_id, substs)
217 fn in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, Self::Error>
219 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
221 value.as_ref().skip_binder().print(self)
224 fn wrap_binder<T, F: Fn(&T, Self) -> Result<Self, fmt::Error>>(
226 value: &ty::Binder<'tcx, T>,
228 ) -> Result<Self, Self::Error>
230 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
232 f(value.as_ref().skip_binder(), self)
235 /// Prints comma-separated elements.
236 fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
238 T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
240 if let Some(first) = elems.next() {
241 self = first.print(self)?;
243 self.write_str(", ")?;
244 self = elem.print(self)?;
250 /// Prints `{f: t}` or `{f as t}` depending on the `cast` argument
253 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
254 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
256 ) -> Result<Self::Const, Self::Error> {
257 self.write_str("{")?;
259 self.write_str(conversion)?;
261 self.write_str("}")?;
265 /// Prints `<...>` around what `f` prints.
266 fn generic_delimiters(
268 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
269 ) -> Result<Self, Self::Error>;
271 /// Returns `true` if the region should be printed in
272 /// optional positions, e.g., `&'a T` or `dyn Tr + 'b`.
273 /// This is typically the case for all non-`'_` regions.
274 fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool;
276 // Defaults (should not be overridden):
278 /// If possible, this returns a global path resolving to `def_id` that is visible
279 /// from at least one local module, and returns `true`. If the crate defining `def_id` is
280 /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
281 fn try_print_visible_def_path(self, def_id: DefId) -> Result<(Self, bool), Self::Error> {
282 if NO_VISIBLE_PATH.with(|flag| flag.get()) {
283 return Ok((self, false));
286 let mut callers = Vec::new();
287 self.try_print_visible_def_path_recur(def_id, &mut callers)
290 /// Try to see if this path can be trimmed to a unique symbol name.
291 fn try_print_trimmed_def_path(
294 ) -> Result<(Self::Path, bool), Self::Error> {
295 if !self.tcx().sess.opts.debugging_opts.trim_diagnostic_paths
296 || matches!(self.tcx().sess.opts.trimmed_def_paths, TrimmedDefPaths::Never)
297 || NO_TRIMMED_PATH.with(|flag| flag.get())
298 || SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get())
300 return Ok((self, false));
303 match self.tcx().trimmed_def_paths(()).get(&def_id) {
304 None => Ok((self, false)),
306 self.write_str(&symbol.as_str())?;
312 /// Does the work of `try_print_visible_def_path`, building the
313 /// full definition path recursively before attempting to
314 /// post-process it into the valid and visible version that
315 /// accounts for re-exports.
317 /// This method should only be called by itself or
318 /// `try_print_visible_def_path`.
320 /// `callers` is a chain of visible_parent's leading to `def_id`,
321 /// to support cycle detection during recursion.
322 fn try_print_visible_def_path_recur(
325 callers: &mut Vec<DefId>,
326 ) -> Result<(Self, bool), Self::Error> {
327 define_scoped_cx!(self);
329 debug!("try_print_visible_def_path: def_id={:?}", def_id);
331 // If `def_id` is a direct or injected extern crate, return the
332 // path to the crate followed by the path to the item within the crate.
333 if def_id.index == CRATE_DEF_INDEX {
334 let cnum = def_id.krate;
336 if cnum == LOCAL_CRATE {
337 return Ok((self.path_crate(cnum)?, true));
340 // In local mode, when we encounter a crate other than
341 // LOCAL_CRATE, execution proceeds in one of two ways:
343 // 1. For a direct dependency, where user added an
344 // `extern crate` manually, we put the `extern
345 // crate` as the parent. So you wind up with
346 // something relative to the current crate.
347 // 2. For an extern inferred from a path or an indirect crate,
348 // where there is no explicit `extern crate`, we just prepend
350 match self.tcx().extern_crate(def_id) {
351 Some(&ExternCrate { src, dependency_of, span, .. }) => match (src, dependency_of) {
352 (ExternCrateSource::Extern(def_id), LOCAL_CRATE) => {
353 // NOTE(eddyb) the only reason `span` might be dummy,
354 // that we're aware of, is that it's the `std`/`core`
355 // `extern crate` injected by default.
356 // FIXME(eddyb) find something better to key this on,
357 // or avoid ending up with `ExternCrateSource::Extern`,
358 // for the injected `std`/`core`.
360 return Ok((self.path_crate(cnum)?, true));
363 // Disable `try_print_trimmed_def_path` behavior within
364 // the `print_def_path` call, to avoid infinite recursion
365 // in cases where the `extern crate foo` has non-trivial
366 // parents, e.g. it's nested in `impl foo::Trait for Bar`
367 // (see also issues #55779 and #87932).
368 self = with_no_visible_paths(|| self.print_def_path(def_id, &[]))?;
370 return Ok((self, true));
372 (ExternCrateSource::Path, LOCAL_CRATE) => {
373 return Ok((self.path_crate(cnum)?, true));
378 return Ok((self.path_crate(cnum)?, true));
383 if def_id.is_local() {
384 return Ok((self, false));
387 let visible_parent_map = self.tcx().visible_parent_map(());
389 let mut cur_def_key = self.tcx().def_key(def_id);
390 debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
392 // For a constructor, we want the name of its parent rather than <unnamed>.
393 if let DefPathData::Ctor = cur_def_key.disambiguated_data.data {
398 .expect("`DefPathData::Ctor` / `VariantData` missing a parent"),
401 cur_def_key = self.tcx().def_key(parent);
404 let visible_parent = match visible_parent_map.get(&def_id).cloned() {
405 Some(parent) => parent,
406 None => return Ok((self, false)),
408 if callers.contains(&visible_parent) {
409 return Ok((self, false));
411 callers.push(visible_parent);
412 // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
413 // knowing ahead of time whether the entire path will succeed or not.
414 // To support printers that do not implement `PrettyPrinter`, a `Vec` or
415 // linked list on the stack would need to be built, before any printing.
416 match self.try_print_visible_def_path_recur(visible_parent, callers)? {
417 (cx, false) => return Ok((cx, false)),
418 (cx, true) => self = cx,
421 let actual_parent = self.tcx().parent(def_id);
423 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
424 visible_parent, actual_parent,
427 let mut data = cur_def_key.disambiguated_data.data;
429 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
430 data, visible_parent, actual_parent,
434 // In order to output a path that could actually be imported (valid and visible),
435 // we need to handle re-exports correctly.
437 // For example, take `std::os::unix::process::CommandExt`, this trait is actually
438 // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
440 // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is
441 // private so the "true" path to `CommandExt` isn't accessible.
443 // In this case, the `visible_parent_map` will look something like this:
445 // (child) -> (parent)
446 // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
447 // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
448 // `std::sys::unix::ext` -> `std::os`
450 // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
453 // When printing the path to `CommandExt` and looking at the `cur_def_key` that
454 // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
455 // to the parent - resulting in a mangled path like
456 // `std::os::ext::process::CommandExt`.
458 // Instead, we must detect that there was a re-export and instead print `unix`
459 // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
460 // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
461 // the visible parent (`std::os`). If these do not match, then we iterate over
462 // the children of the visible parent (as was done when computing
463 // `visible_parent_map`), looking for the specific child we currently have and then
464 // have access to the re-exported name.
465 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
468 .item_children(visible_parent)
470 .find(|child| child.res.opt_def_id() == Some(def_id))
471 .map(|child| child.ident.name);
472 if let Some(reexport) = reexport {
476 // Re-exported `extern crate` (#43189).
477 DefPathData::CrateRoot => {
478 data = DefPathData::TypeNs(self.tcx().crate_name(def_id.krate));
482 debug!("try_print_visible_def_path: data={:?}", data);
484 Ok((self.path_append(Ok, &DisambiguatedDefPathData { data, disambiguator: 0 })?, true))
487 fn pretty_path_qualified(
490 trait_ref: Option<ty::TraitRef<'tcx>>,
491 ) -> Result<Self::Path, Self::Error> {
492 if trait_ref.is_none() {
493 // Inherent impls. Try to print `Foo::bar` for an inherent
494 // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
495 // anything other than a simple path.
496 match self_ty.kind() {
505 return self_ty.print(self);
512 self.generic_delimiters(|mut cx| {
513 define_scoped_cx!(cx);
516 if let Some(trait_ref) = trait_ref {
517 p!(" as ", print(trait_ref.print_only_trait_path()));
523 fn pretty_path_append_impl(
525 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
527 trait_ref: Option<ty::TraitRef<'tcx>>,
528 ) -> Result<Self::Path, Self::Error> {
529 self = print_prefix(self)?;
531 self.generic_delimiters(|mut cx| {
532 define_scoped_cx!(cx);
535 if let Some(trait_ref) = trait_ref {
536 p!(print(trait_ref.print_only_trait_path()), " for ");
544 fn pretty_print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
545 define_scoped_cx!(self);
548 ty::Bool => p!("bool"),
549 ty::Char => p!("char"),
550 ty::Int(t) => p!(write("{}", t.name_str())),
551 ty::Uint(t) => p!(write("{}", t.name_str())),
552 ty::Float(t) => p!(write("{}", t.name_str())),
553 ty::RawPtr(ref tm) => {
557 hir::Mutability::Mut => "mut",
558 hir::Mutability::Not => "const",
563 ty::Ref(r, ty, mutbl) => {
565 if self.region_should_not_be_omitted(r) {
568 p!(print(ty::TypeAndMut { ty, mutbl }))
570 ty::Never => p!("!"),
571 ty::Tuple(ref tys) => {
572 p!("(", comma_sep(tys.iter()));
578 ty::FnDef(def_id, substs) => {
579 let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs);
580 p!(print(sig), " {{", print_value_path(def_id, substs), "}}");
582 ty::FnPtr(ref bare_fn) => p!(print(bare_fn)),
583 ty::Infer(infer_ty) => {
584 let verbose = self.tcx().sess.verbose();
585 if let ty::TyVar(ty_vid) = infer_ty {
586 if let Some(name) = self.infer_ty_name(ty_vid) {
587 p!(write("{}", name))
590 p!(write("{:?}", infer_ty))
592 p!(write("{}", infer_ty))
596 if verbose { p!(write("{:?}", infer_ty)) } else { p!(write("{}", infer_ty)) }
599 ty::Error(_) => p!("[type error]"),
600 ty::Param(ref param_ty) => p!(write("{}", param_ty)),
601 ty::Bound(debruijn, bound_ty) => match bound_ty.kind {
602 ty::BoundTyKind::Anon => self.pretty_print_bound_var(debruijn, bound_ty.var)?,
603 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
605 ty::Adt(def, substs) => {
606 p!(print_def_path(def.did, substs));
608 ty::Dynamic(data, r) => {
609 let print_r = self.region_should_not_be_omitted(r);
613 p!("dyn ", print(data));
615 p!(" + ", print(r), ")");
618 ty::Foreign(def_id) => {
619 p!(print_def_path(def_id, &[]));
621 ty::Projection(ref data) => p!(print(data)),
622 ty::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
623 ty::Opaque(def_id, substs) => {
624 // FIXME(eddyb) print this with `print_def_path`.
625 // We use verbose printing in 'NO_QUERIES' mode, to
626 // avoid needing to call `predicates_of`. This should
627 // only affect certain debug messages (e.g. messages printed
628 // from `rustc_middle::ty` during the computation of `tcx.predicates_of`),
629 // and should have no effect on any compiler output.
630 if self.tcx().sess.verbose() || NO_QUERIES.with(|q| q.get()) {
631 p!(write("Opaque({:?}, {:?})", def_id, substs));
635 return with_no_queries(|| {
636 let def_key = self.tcx().def_key(def_id);
637 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
638 p!(write("{}", name));
639 // FIXME(eddyb) print this with `print_def_path`.
640 if !substs.is_empty() {
642 p!(generic_delimiters(|cx| cx.comma_sep(substs.iter())));
646 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
647 // by looking up the projections associated with the def_id.
648 let bounds = self.tcx().explicit_item_bounds(def_id);
650 let mut first = true;
651 let mut is_sized = false;
653 for (predicate, _) in bounds {
654 let predicate = predicate.subst(self.tcx(), substs);
655 let bound_predicate = predicate.kind();
656 if let ty::PredicateKind::Trait(pred) = bound_predicate.skip_binder() {
657 let trait_ref = bound_predicate.rebind(pred.trait_ref);
658 // Don't print +Sized, but rather +?Sized if absent.
659 if Some(trait_ref.def_id()) == self.tcx().lang_items().sized_trait() {
665 write("{}", if first { " " } else { "+" }),
666 print(trait_ref.print_only_trait_path())
672 p!(write("{}?Sized", if first { " " } else { "+" }));
679 ty::Str => p!("str"),
680 ty::Generator(did, substs, movability) => {
683 hir::Movability::Movable => {}
684 hir::Movability::Static => p!("static "),
687 if !self.tcx().sess.verbose() {
689 // FIXME(eddyb) should use `def_span`.
690 if let Some(did) = did.as_local() {
691 let hir_id = self.tcx().hir().local_def_id_to_hir_id(did);
692 let span = self.tcx().hir().span(hir_id);
695 // This may end up in stderr diagnostics but it may also be emitted
696 // into MIR. Hence we use the remapped path if available
697 self.tcx().sess.source_map().span_to_embeddable_string(span)
700 p!(write("@"), print_def_path(did, substs));
703 p!(print_def_path(did, substs));
705 if !substs.as_generator().is_valid() {
708 self = self.comma_sep(substs.as_generator().upvar_tys())?;
712 if substs.as_generator().is_valid() {
713 p!(" ", print(substs.as_generator().witness()));
719 ty::GeneratorWitness(types) => {
720 p!(in_binder(&types));
722 ty::Closure(did, substs) => {
724 if !self.tcx().sess.verbose() {
725 p!(write("closure"));
726 // FIXME(eddyb) should use `def_span`.
727 if let Some(did) = did.as_local() {
728 let hir_id = self.tcx().hir().local_def_id_to_hir_id(did);
729 if self.tcx().sess.opts.debugging_opts.span_free_formats {
730 p!("@", print_def_path(did.to_def_id(), substs));
732 let span = self.tcx().hir().span(hir_id);
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)");
748 p!(" closure_kind_ty=", print(substs.as_closure().kind_ty()));
750 " closure_sig_as_fn_ptr_ty=",
751 print(substs.as_closure().sig_as_fn_ptr_ty())
754 self = self.comma_sep(substs.as_closure().upvar_tys())?;
760 ty::Array(ty, sz) => {
761 p!("[", print(ty), "; ");
762 if self.tcx().sess.verbose() {
763 p!(write("{:?}", sz));
764 } else if let ty::ConstKind::Unevaluated(..) = sz.val {
765 // Do not try to evaluate unevaluated constants. If we are const evaluating an
766 // array length anon const, rustc will (with debug assertions) print the
767 // constant's path. Which will end up here again.
769 } else if let Some(n) = sz.val.try_to_bits(self.tcx().data_layout.pointer_size) {
771 } else if let ty::ConstKind::Param(param) = sz.val {
772 p!(write("{}", param));
778 ty::Slice(ty) => p!("[", print(ty), "]"),
784 fn pretty_print_bound_var(
786 debruijn: ty::DebruijnIndex,
788 ) -> Result<(), Self::Error> {
789 if debruijn == ty::INNERMOST {
790 write!(self, "^{}", var.index())
792 write!(self, "^{}_{}", debruijn.index(), var.index())
796 fn infer_ty_name(&self, _: ty::TyVid) -> Option<String> {
800 fn pretty_print_dyn_existential(
802 predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
803 ) -> Result<Self::DynExistential, Self::Error> {
804 // Generate the main trait ref, including associated types.
805 let mut first = true;
807 if let Some(principal) = predicates.principal() {
808 self = self.wrap_binder(&principal, |principal, mut cx| {
809 define_scoped_cx!(cx);
810 p!(print_def_path(principal.def_id, &[]));
812 let mut resugared = false;
814 // Special-case `Fn(...) -> ...` and resugar it.
815 let fn_trait_kind = cx.tcx().fn_trait_kind_from_lang_item(principal.def_id);
816 if !cx.tcx().sess.verbose() && fn_trait_kind.is_some() {
817 if let ty::Tuple(ref args) = principal.substs.type_at(0).kind() {
818 let mut projections = predicates.projection_bounds();
819 if let (Some(proj), None) = (projections.next(), projections.next()) {
820 let tys: Vec<_> = args.iter().map(|k| k.expect_ty()).collect();
821 p!(pretty_fn_sig(&tys, false, proj.skip_binder().ty));
827 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
828 // in order to place the projections inside the `<...>`.
830 // Use a type that can't appear in defaults of type parameters.
831 let dummy_cx = cx.tcx().mk_ty_infer(ty::FreshTy(0));
832 let principal = principal.with_self_ty(cx.tcx(), dummy_cx);
834 let args = cx.generic_args_to_print(
835 cx.tcx().generics_of(principal.def_id),
839 // Don't print `'_` if there's no unerased regions.
840 let print_regions = args.iter().any(|arg| match arg.unpack() {
841 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
844 let mut args = args.iter().cloned().filter(|arg| match arg.unpack() {
845 GenericArgKind::Lifetime(_) => print_regions,
848 let mut projections = predicates.projection_bounds();
850 let arg0 = args.next();
851 let projection0 = projections.next();
852 if arg0.is_some() || projection0.is_some() {
853 let args = arg0.into_iter().chain(args);
854 let projections = projection0.into_iter().chain(projections);
856 p!(generic_delimiters(|mut cx| {
857 cx = cx.comma_sep(args)?;
858 if arg0.is_some() && projection0.is_some() {
861 cx.comma_sep(projections)
871 define_scoped_cx!(self);
874 // FIXME(eddyb) avoid printing twice (needed to ensure
875 // that the auto traits are sorted *and* printed via cx).
876 let mut auto_traits: Vec<_> =
877 predicates.auto_traits().map(|did| (self.tcx().def_path_str(did), did)).collect();
879 // The auto traits come ordered by `DefPathHash`. While
880 // `DefPathHash` is *stable* in the sense that it depends on
881 // neither the host nor the phase of the moon, it depends
882 // "pseudorandomly" on the compiler version and the target.
884 // To avoid that causing instabilities in compiletest
885 // output, sort the auto-traits alphabetically.
888 for (_, def_id) in auto_traits {
894 p!(print_def_path(def_id, &[]));
905 ) -> Result<Self, Self::Error> {
906 define_scoped_cx!(self);
908 p!("(", comma_sep(inputs.iter().copied()));
910 if !inputs.is_empty() {
916 if !output.is_unit() {
917 p!(" -> ", print(output));
923 fn pretty_print_const(
925 ct: &'tcx ty::Const<'tcx>,
927 ) -> Result<Self::Const, Self::Error> {
928 define_scoped_cx!(self);
930 if self.tcx().sess.verbose() {
931 p!(write("Const({:?}: {:?})", ct.val, ct.ty));
935 macro_rules! print_underscore {
938 self = self.typed_value(
943 |this| this.print_type(ct.ty),
953 ty::ConstKind::Unevaluated(uv) => {
954 if let Some(promoted) = uv.promoted {
955 let substs = uv.substs_.unwrap();
956 p!(print_value_path(uv.def.did, substs));
957 p!(write("::{:?}", promoted));
959 let tcx = self.tcx();
960 match tcx.def_kind(uv.def.did) {
961 DefKind::Static | DefKind::Const | DefKind::AssocConst => {
962 p!(print_value_path(uv.def.did, uv.substs(tcx)))
965 if uv.def.is_local() {
966 let span = tcx.def_span(uv.def.did);
967 if let Ok(snip) = tcx.sess.source_map().span_to_snippet(span) {
968 p!(write("{}", snip))
979 ty::ConstKind::Infer(..) => print_underscore!(),
980 ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)),
981 ty::ConstKind::Value(value) => {
982 return self.pretty_print_const_value(value, ct.ty, print_ty);
985 ty::ConstKind::Bound(debruijn, bound_var) => {
986 self.pretty_print_bound_var(debruijn, bound_var)?
988 ty::ConstKind::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
989 ty::ConstKind::Error(_) => p!("[const error]"),
994 fn pretty_print_const_scalar(
999 ) -> Result<Self::Const, Self::Error> {
1001 Scalar::Ptr(ptr, _size) => self.pretty_print_const_scalar_ptr(ptr, ty, print_ty),
1002 Scalar::Int(int) => self.pretty_print_const_scalar_int(int, ty, print_ty),
1006 fn pretty_print_const_scalar_ptr(
1011 ) -> Result<Self::Const, Self::Error> {
1012 define_scoped_cx!(self);
1014 let (alloc_id, offset) = ptr.into_parts();
1016 // Byte strings (&[u8; N])
1022 ty::TyS { kind: ty::Uint(ty::UintTy::U8), .. },
1024 val: ty::ConstKind::Value(ConstValue::Scalar(int)), ..
1030 ) => match self.tcx().get_global_alloc(alloc_id) {
1031 Some(GlobalAlloc::Memory(alloc)) => {
1032 let len = int.assert_bits(self.tcx().data_layout.pointer_size);
1033 let range = AllocRange { start: offset, size: Size::from_bytes(len) };
1034 if let Ok(byte_str) = alloc.get_bytes(&self.tcx(), range) {
1035 p!(pretty_print_byte_str(byte_str))
1037 p!("<too short allocation>")
1040 // FIXME: for statics and functions, we could in principle print more detail.
1041 Some(GlobalAlloc::Static(def_id)) => p!(write("<static({:?})>", def_id)),
1042 Some(GlobalAlloc::Function(_)) => p!("<function>"),
1043 None => p!("<dangling pointer>"),
1046 // FIXME: We should probably have a helper method to share code with the "Byte strings"
1047 // printing above (which also has to handle pointers to all sorts of things).
1048 match self.tcx().get_global_alloc(alloc_id) {
1049 Some(GlobalAlloc::Function(instance)) => {
1050 self = self.typed_value(
1051 |this| this.print_value_path(instance.def_id(), instance.substs),
1052 |this| this.print_type(ty),
1056 _ => self = self.pretty_print_const_pointer(ptr, ty, print_ty)?,
1059 // Any pointer values not covered by a branch above
1061 self = self.pretty_print_const_pointer(ptr, ty, print_ty)?;
1067 fn pretty_print_const_scalar_int(
1072 ) -> Result<Self::Const, Self::Error> {
1073 define_scoped_cx!(self);
1077 ty::Bool if int == ScalarInt::FALSE => p!("false"),
1078 ty::Bool if int == ScalarInt::TRUE => p!("true"),
1080 ty::Float(ty::FloatTy::F32) => {
1081 p!(write("{}f32", Single::try_from(int).unwrap()))
1083 ty::Float(ty::FloatTy::F64) => {
1084 p!(write("{}f64", Double::try_from(int).unwrap()))
1087 ty::Uint(_) | ty::Int(_) => {
1089 ConstInt::new(int, matches!(ty.kind(), ty::Int(_)), ty.is_ptr_sized_integral());
1090 if print_ty { p!(write("{:#?}", int)) } else { p!(write("{:?}", int)) }
1093 ty::Char if char::try_from(int).is_ok() => {
1094 p!(write("{:?}", char::try_from(int).unwrap()))
1097 ty::Ref(..) | ty::RawPtr(_) | ty::FnPtr(_) => {
1098 let data = int.assert_bits(self.tcx().data_layout.pointer_size);
1099 self = self.typed_value(
1101 write!(this, "0x{:x}", data)?;
1104 |this| this.print_type(ty),
1108 // For function type zsts just printing the path is enough
1109 ty::FnDef(d, s) if int == ScalarInt::ZST => {
1110 p!(print_value_path(*d, s))
1112 // Nontrivial types with scalar bit representation
1114 let print = |mut this: Self| {
1115 if int.size() == Size::ZERO {
1116 write!(this, "transmute(())")?;
1118 write!(this, "transmute(0x{:x})", int)?;
1122 self = if print_ty {
1123 self.typed_value(print, |this| this.print_type(ty), ": ")?
1132 /// This is overridden for MIR printing because we only want to hide alloc ids from users, not
1133 /// from MIR where it is actually useful.
1134 fn pretty_print_const_pointer<Tag: Provenance>(
1139 ) -> Result<Self::Const, Self::Error> {
1143 this.write_str("&_")?;
1146 |this| this.print_type(ty),
1150 self.write_str("&_")?;
1155 fn pretty_print_byte_str(mut self, byte_str: &'tcx [u8]) -> Result<Self::Const, Self::Error> {
1156 define_scoped_cx!(self);
1158 for &c in byte_str {
1159 for e in std::ascii::escape_default(c) {
1160 self.write_char(e as char)?;
1167 fn pretty_print_const_value(
1169 ct: ConstValue<'tcx>,
1172 ) -> Result<Self::Const, Self::Error> {
1173 define_scoped_cx!(self);
1175 if self.tcx().sess.verbose() {
1176 p!(write("ConstValue({:?}: ", ct), print(ty), ")");
1180 let u8_type = self.tcx().types.u8;
1182 match (ct, ty.kind()) {
1183 // Byte/string slices, printed as (byte) string literals.
1185 ConstValue::Slice { data, start, end },
1186 ty::Ref(_, ty::TyS { kind: ty::Slice(t), .. }, _),
1187 ) if *t == u8_type => {
1188 // The `inspect` here is okay since we checked the bounds, and there are
1189 // no relocations (we have an active slice reference here). We don't use
1190 // this result to affect interpreter execution.
1191 let byte_str = data.inspect_with_uninit_and_ptr_outside_interpreter(start..end);
1192 self.pretty_print_byte_str(byte_str)
1195 ConstValue::Slice { data, start, end },
1196 ty::Ref(_, ty::TyS { kind: ty::Str, .. }, _),
1198 // The `inspect` here is okay since we checked the bounds, and there are no
1199 // relocations (we have an active `str` reference here). We don't use this
1200 // result to affect interpreter execution.
1201 let slice = data.inspect_with_uninit_and_ptr_outside_interpreter(start..end);
1202 let s = std::str::from_utf8(slice).expect("non utf8 str from miri");
1203 p!(write("{:?}", s));
1206 (ConstValue::ByRef { alloc, offset }, ty::Array(t, n)) if *t == u8_type => {
1207 let n = n.val.try_to_bits(self.tcx().data_layout.pointer_size).unwrap();
1208 // cast is ok because we already checked for pointer size (32 or 64 bit) above
1209 let range = AllocRange { start: offset, size: Size::from_bytes(n) };
1211 let byte_str = alloc.get_bytes(&self.tcx(), range).unwrap();
1213 p!(pretty_print_byte_str(byte_str));
1217 // Aggregates, printed as array/tuple/struct/variant construction syntax.
1219 // NB: the `potentially_has_param_types_or_consts` check ensures that we can use
1220 // the `destructure_const` query with an empty `ty::ParamEnv` without
1221 // introducing ICEs (e.g. via `layout_of`) from missing bounds.
1222 // E.g. `transmute([0usize; 2]): (u8, *mut T)` needs to know `T: Sized`
1223 // to be able to destructure the tuple into `(0u8, *mut T)
1225 // FIXME(eddyb) for `--emit=mir`/`-Z dump-mir`, we should provide the
1226 // correct `ty::ParamEnv` to allow printing *all* constant values.
1227 (_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..))
1228 if !ty.potentially_has_param_types_or_consts() =>
1230 let contents = self.tcx().destructure_const(
1231 ty::ParamEnv::reveal_all()
1232 .and(self.tcx().mk_const(ty::Const { val: ty::ConstKind::Value(ct), ty })),
1234 let fields = contents.fields.iter().copied();
1238 p!("[", comma_sep(fields), "]");
1241 p!("(", comma_sep(fields));
1242 if contents.fields.len() == 1 {
1247 ty::Adt(def, _) if def.variants.is_empty() => {
1248 self = self.typed_value(
1250 write!(this, "unreachable()")?;
1253 |this| this.print_type(ty),
1257 ty::Adt(def, substs) => {
1259 contents.variant.expect("destructed const of adt without variant idx");
1260 let variant_def = &def.variants[variant_idx];
1261 p!(print_value_path(variant_def.def_id, substs));
1263 match variant_def.ctor_kind {
1264 CtorKind::Const => {}
1266 p!("(", comma_sep(fields), ")");
1268 CtorKind::Fictive => {
1270 let mut first = true;
1271 for (field_def, field) in iter::zip(&variant_def.fields, fields) {
1275 p!(write("{}: ", field_def.ident), print(field));
1282 _ => unreachable!(),
1288 (ConstValue::Scalar(scalar), _) => self.pretty_print_const_scalar(scalar, ty, print_ty),
1290 // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
1291 // their fields instead of just dumping the memory.
1294 p!(write("{:?}", ct));
1296 p!(": ", print(ty));
1304 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
1305 pub struct FmtPrinter<'a, 'tcx, F>(Box<FmtPrinterData<'a, 'tcx, F>>);
1307 pub struct FmtPrinterData<'a, 'tcx, F> {
1313 pub print_alloc_ids: bool,
1315 used_region_names: FxHashSet<Symbol>,
1316 region_index: usize,
1317 binder_depth: usize,
1318 printed_type_count: usize,
1320 pub region_highlight_mode: RegionHighlightMode,
1322 pub name_resolver: Option<Box<&'a dyn Fn(ty::TyVid) -> Option<String>>>,
1325 impl<F> Deref for FmtPrinter<'a, 'tcx, F> {
1326 type Target = FmtPrinterData<'a, 'tcx, F>;
1327 fn deref(&self) -> &Self::Target {
1332 impl<F> DerefMut for FmtPrinter<'_, '_, F> {
1333 fn deref_mut(&mut self) -> &mut Self::Target {
1338 impl<F> FmtPrinter<'a, 'tcx, F> {
1339 pub fn new(tcx: TyCtxt<'tcx>, fmt: F, ns: Namespace) -> Self {
1340 FmtPrinter(Box::new(FmtPrinterData {
1344 in_value: ns == Namespace::ValueNS,
1345 print_alloc_ids: false,
1346 used_region_names: Default::default(),
1349 printed_type_count: 0,
1350 region_highlight_mode: RegionHighlightMode::default(),
1351 name_resolver: None,
1356 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1357 // (but also some things just print a `DefId` generally so maybe we need this?)
1358 fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
1359 match tcx.def_key(def_id).disambiguated_data.data {
1360 DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::ImplTrait => {
1364 DefPathData::ValueNs(..)
1365 | DefPathData::AnonConst
1366 | DefPathData::ClosureExpr
1367 | DefPathData::Ctor => Namespace::ValueNS,
1369 DefPathData::MacroNs(..) => Namespace::MacroNS,
1371 _ => Namespace::TypeNS,
1376 /// Returns a string identifying this `DefId`. This string is
1377 /// suitable for user output.
1378 pub fn def_path_str(self, def_id: DefId) -> String {
1379 self.def_path_str_with_substs(def_id, &[])
1382 pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1383 let ns = guess_def_namespace(self, def_id);
1384 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1385 let mut s = String::new();
1386 let _ = FmtPrinter::new(self, &mut s, ns).print_def_path(def_id, substs);
1391 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, F> {
1392 fn write_str(&mut self, s: &str) -> fmt::Result {
1393 self.fmt.write_str(s)
1397 impl<F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
1398 type Error = fmt::Error;
1403 type DynExistential = Self;
1406 fn tcx(&'a self) -> TyCtxt<'tcx> {
1413 substs: &'tcx [GenericArg<'tcx>],
1414 ) -> Result<Self::Path, Self::Error> {
1415 define_scoped_cx!(self);
1417 if substs.is_empty() {
1418 match self.try_print_trimmed_def_path(def_id)? {
1419 (cx, true) => return Ok(cx),
1420 (cx, false) => self = cx,
1423 match self.try_print_visible_def_path(def_id)? {
1424 (cx, true) => return Ok(cx),
1425 (cx, false) => self = cx,
1429 let key = self.tcx.def_key(def_id);
1430 if let DefPathData::Impl = key.disambiguated_data.data {
1431 // Always use types for non-local impls, where types are always
1432 // available, and filename/line-number is mostly uninteresting.
1433 let use_types = !def_id.is_local() || {
1434 // Otherwise, use filename/line-number if forced.
1435 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1440 // If no type info is available, fall back to
1441 // pretty printing some span information. This should
1442 // only occur very early in the compiler pipeline.
1443 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1444 let span = self.tcx.def_span(def_id);
1446 self = self.print_def_path(parent_def_id, &[])?;
1448 // HACK(eddyb) copy of `path_append` to avoid
1449 // constructing a `DisambiguatedDefPathData`.
1450 if !self.empty_path {
1451 write!(self, "::")?;
1456 // This may end up in stderr diagnostics but it may also be emitted
1457 // into MIR. Hence we use the remapped path if available
1458 self.tcx.sess.source_map().span_to_embeddable_string(span)
1460 self.empty_path = false;
1466 self.default_print_def_path(def_id, substs)
1469 fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
1470 self.pretty_print_region(region)
1473 fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1474 let type_length_limit = self.tcx.type_length_limit();
1475 if type_length_limit.value_within_limit(self.printed_type_count) {
1476 self.printed_type_count += 1;
1477 self.pretty_print_type(ty)
1479 write!(self, "...")?;
1484 fn print_dyn_existential(
1486 predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
1487 ) -> Result<Self::DynExistential, Self::Error> {
1488 self.pretty_print_dyn_existential(predicates)
1491 fn print_const(self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1492 self.pretty_print_const(ct, true)
1495 fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1496 self.empty_path = true;
1497 if cnum == LOCAL_CRATE {
1498 if self.tcx.sess.rust_2018() {
1499 // We add the `crate::` keyword on Rust 2018, only when desired.
1500 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1501 write!(self, "{}", kw::Crate)?;
1502 self.empty_path = false;
1506 write!(self, "{}", self.tcx.crate_name(cnum))?;
1507 self.empty_path = false;
1515 trait_ref: Option<ty::TraitRef<'tcx>>,
1516 ) -> Result<Self::Path, Self::Error> {
1517 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1518 self.empty_path = false;
1522 fn path_append_impl(
1524 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1525 _disambiguated_data: &DisambiguatedDefPathData,
1527 trait_ref: Option<ty::TraitRef<'tcx>>,
1528 ) -> Result<Self::Path, Self::Error> {
1529 self = self.pretty_path_append_impl(
1531 cx = print_prefix(cx)?;
1541 self.empty_path = false;
1547 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1548 disambiguated_data: &DisambiguatedDefPathData,
1549 ) -> Result<Self::Path, Self::Error> {
1550 self = print_prefix(self)?;
1552 // Skip `::{{constructor}}` on tuple/unit structs.
1553 if let DefPathData::Ctor = disambiguated_data.data {
1557 // FIXME(eddyb) `name` should never be empty, but it
1558 // currently is for `extern { ... }` "foreign modules".
1559 let name = disambiguated_data.data.name();
1560 if name != DefPathDataName::Named(kw::Empty) {
1561 if !self.empty_path {
1562 write!(self, "::")?;
1565 if let DefPathDataName::Named(name) = name {
1566 if Ident::with_dummy_span(name).is_raw_guess() {
1567 write!(self, "r#")?;
1571 let verbose = self.tcx.sess.verbose();
1572 disambiguated_data.fmt_maybe_verbose(&mut self, verbose)?;
1574 self.empty_path = false;
1580 fn path_generic_args(
1582 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1583 args: &[GenericArg<'tcx>],
1584 ) -> Result<Self::Path, Self::Error> {
1585 self = print_prefix(self)?;
1587 // Don't print `'_` if there's no unerased regions.
1588 let print_regions = args.iter().any(|arg| match arg.unpack() {
1589 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
1592 let args = args.iter().cloned().filter(|arg| match arg.unpack() {
1593 GenericArgKind::Lifetime(_) => print_regions,
1597 if args.clone().next().is_some() {
1599 write!(self, "::")?;
1601 self.generic_delimiters(|cx| cx.comma_sep(args))
1608 impl<F: fmt::Write> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx, F> {
1609 fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> {
1610 self.0.name_resolver.as_ref().and_then(|func| func(id))
1613 fn print_value_path(
1616 substs: &'tcx [GenericArg<'tcx>],
1617 ) -> Result<Self::Path, Self::Error> {
1618 let was_in_value = std::mem::replace(&mut self.in_value, true);
1619 self = self.print_def_path(def_id, substs)?;
1620 self.in_value = was_in_value;
1625 fn in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, Self::Error>
1627 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1629 self.pretty_in_binder(value)
1632 fn wrap_binder<T, C: Fn(&T, Self) -> Result<Self, Self::Error>>(
1634 value: &ty::Binder<'tcx, T>,
1636 ) -> Result<Self, Self::Error>
1638 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1640 self.pretty_wrap_binder(value, f)
1645 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1646 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
1648 ) -> Result<Self::Const, Self::Error> {
1649 self.write_str("{")?;
1651 self.write_str(conversion)?;
1652 let was_in_value = std::mem::replace(&mut self.in_value, false);
1654 self.in_value = was_in_value;
1655 self.write_str("}")?;
1659 fn generic_delimiters(
1661 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1662 ) -> Result<Self, Self::Error> {
1665 let was_in_value = std::mem::replace(&mut self.in_value, false);
1666 let mut inner = f(self)?;
1667 inner.in_value = was_in_value;
1669 write!(inner, ">")?;
1673 fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool {
1674 let highlight = self.region_highlight_mode;
1675 if highlight.region_highlighted(region).is_some() {
1679 if self.tcx.sess.verbose() {
1683 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1686 ty::ReEarlyBound(ref data) => {
1687 data.name != kw::Empty && data.name != kw::UnderscoreLifetime
1690 ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
1691 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1692 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1693 if let ty::BrNamed(_, name) = br {
1694 if name != kw::Empty && name != kw::UnderscoreLifetime {
1699 if let Some((region, _)) = highlight.highlight_bound_region {
1708 ty::ReVar(_) if identify_regions => true,
1710 ty::ReVar(_) | ty::ReErased => false,
1712 ty::ReStatic | ty::ReEmpty(_) => true,
1716 fn pretty_print_const_pointer<Tag: Provenance>(
1721 ) -> Result<Self::Const, Self::Error> {
1722 let print = |mut this: Self| {
1723 define_scoped_cx!(this);
1724 if this.print_alloc_ids {
1725 p!(write("{:?}", p));
1732 self.typed_value(print, |this| this.print_type(ty), ": ")
1739 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1740 impl<F: fmt::Write> FmtPrinter<'_, '_, F> {
1741 pub fn pretty_print_region(mut self, region: ty::Region<'_>) -> Result<Self, fmt::Error> {
1742 define_scoped_cx!(self);
1744 // Watch out for region highlights.
1745 let highlight = self.region_highlight_mode;
1746 if let Some(n) = highlight.region_highlighted(region) {
1747 p!(write("'{}", n));
1751 if self.tcx.sess.verbose() {
1752 p!(write("{:?}", region));
1756 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1758 // These printouts are concise. They do not contain all the information
1759 // the user might want to diagnose an error, but there is basically no way
1760 // to fit that into a short string. Hence the recommendation to use
1761 // `explain_region()` or `note_and_explain_region()`.
1763 ty::ReEarlyBound(ref data) => {
1764 if data.name != kw::Empty {
1765 p!(write("{}", data.name));
1769 ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
1770 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1771 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1772 if let ty::BrNamed(_, name) = br {
1773 if name != kw::Empty && name != kw::UnderscoreLifetime {
1774 p!(write("{}", name));
1779 if let Some((region, counter)) = highlight.highlight_bound_region {
1781 p!(write("'{}", counter));
1786 ty::ReVar(region_vid) if identify_regions => {
1787 p!(write("{:?}", region_vid));
1796 ty::ReEmpty(ty::UniverseIndex::ROOT) => {
1800 ty::ReEmpty(ui) => {
1801 p!(write("'<empty:{:?}>", ui));
1812 /// Folds through bound vars and placeholders, naming them
1813 struct RegionFolder<'a, 'tcx> {
1815 current_index: ty::DebruijnIndex,
1816 region_map: BTreeMap<ty::BoundRegion, ty::Region<'tcx>>,
1817 name: &'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a),
1820 impl<'a, 'tcx> ty::TypeFolder<'tcx> for RegionFolder<'a, 'tcx> {
1821 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1825 fn fold_binder<T: TypeFoldable<'tcx>>(
1827 t: ty::Binder<'tcx, T>,
1828 ) -> ty::Binder<'tcx, T> {
1829 self.current_index.shift_in(1);
1830 let t = t.super_fold_with(self);
1831 self.current_index.shift_out(1);
1835 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
1837 _ if t.has_vars_bound_at_or_above(self.current_index) || t.has_placeholders() => {
1838 return t.super_fold_with(self);
1845 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
1846 let name = &mut self.name;
1847 let region = match *r {
1848 ty::ReLateBound(_, br) => self.region_map.entry(br).or_insert_with(|| name(br)),
1849 ty::RePlaceholder(ty::PlaceholderRegion { name: kind, .. }) => {
1850 // If this is an anonymous placeholder, don't rename. Otherwise, in some
1851 // async fns, we get a `for<'r> Send` bound
1853 ty::BrAnon(_) | ty::BrEnv => r,
1855 // Index doesn't matter, since this is just for naming and these never get bound
1856 let br = ty::BoundRegion { var: ty::BoundVar::from_u32(0), kind };
1857 self.region_map.entry(br).or_insert_with(|| name(br))
1863 if let ty::ReLateBound(debruijn1, br) = *region {
1864 assert_eq!(debruijn1, ty::INNERMOST);
1865 self.tcx.mk_region(ty::ReLateBound(self.current_index, br))
1872 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1873 // `region_index` and `used_region_names`.
1874 impl<F: fmt::Write> FmtPrinter<'_, 'tcx, F> {
1875 pub fn name_all_regions<T>(
1877 value: &ty::Binder<'tcx, T>,
1878 ) -> Result<(Self, T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>), fmt::Error>
1880 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1882 fn name_by_region_index(index: usize) -> Symbol {
1884 0 => Symbol::intern("'r"),
1885 1 => Symbol::intern("'s"),
1886 i => Symbol::intern(&format!("'t{}", i - 2)),
1890 // Replace any anonymous late-bound regions with named
1891 // variants, using new unique identifiers, so that we can
1892 // clearly differentiate between named and unnamed regions in
1893 // the output. We'll probably want to tweak this over time to
1894 // decide just how much information to give.
1895 if self.binder_depth == 0 {
1896 self.prepare_late_bound_region_info(value);
1899 let mut empty = true;
1900 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1907 let _ = write!(cx, "{}", w);
1909 let do_continue = |cx: &mut Self, cont: Symbol| {
1910 let _ = write!(cx, "{}", cont);
1913 define_scoped_cx!(self);
1915 let mut region_index = self.region_index;
1916 // If we want to print verbosly, then print *all* binders, even if they
1917 // aren't named. Eventually, we might just want this as the default, but
1918 // this is not *quite* right and changes the ordering of some output
1920 let (new_value, map) = if self.tcx().sess.verbose() {
1921 // anon index + 1 (BrEnv takes 0) -> name
1922 let mut region_map: BTreeMap<u32, Symbol> = BTreeMap::default();
1923 let bound_vars = value.bound_vars();
1924 for var in bound_vars {
1926 ty::BoundVariableKind::Region(ty::BrNamed(_, name)) => {
1927 start_or_continue(&mut self, "for<", ", ");
1928 do_continue(&mut self, name);
1930 ty::BoundVariableKind::Region(ty::BrAnon(i)) => {
1931 start_or_continue(&mut self, "for<", ", ");
1933 let name = name_by_region_index(region_index);
1935 if !self.used_region_names.contains(&name) {
1939 do_continue(&mut self, name);
1940 region_map.insert(i + 1, name);
1942 ty::BoundVariableKind::Region(ty::BrEnv) => {
1943 start_or_continue(&mut self, "for<", ", ");
1945 let name = name_by_region_index(region_index);
1947 if !self.used_region_names.contains(&name) {
1951 do_continue(&mut self, name);
1952 region_map.insert(0, name);
1957 start_or_continue(&mut self, "", "> ");
1959 self.tcx.replace_late_bound_regions(value.clone(), |br| {
1960 let kind = match br.kind {
1961 ty::BrNamed(_, _) => br.kind,
1963 let name = region_map[&(i + 1)];
1964 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1967 let name = region_map[&0];
1968 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1971 self.tcx.mk_region(ty::ReLateBound(
1973 ty::BoundRegion { var: br.var, kind },
1978 let mut name = |br: ty::BoundRegion| {
1979 start_or_continue(&mut self, "for<", ", ");
1980 let kind = match br.kind {
1981 ty::BrNamed(_, name) => {
1982 do_continue(&mut self, name);
1985 ty::BrAnon(_) | ty::BrEnv => {
1987 let name = name_by_region_index(region_index);
1989 if !self.used_region_names.contains(&name) {
1993 do_continue(&mut self, name);
1994 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1997 tcx.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BoundRegion { var: br.var, kind }))
1999 let mut folder = RegionFolder {
2001 current_index: ty::INNERMOST,
2003 region_map: BTreeMap::new(),
2005 let new_value = value.clone().skip_binder().fold_with(&mut folder);
2006 let region_map = folder.region_map;
2007 start_or_continue(&mut self, "", "> ");
2008 (new_value, region_map)
2011 self.binder_depth += 1;
2012 self.region_index = region_index;
2013 Ok((self, new_value, map))
2016 pub fn pretty_in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, fmt::Error>
2018 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2020 let old_region_index = self.region_index;
2021 let (new, new_value, _) = self.name_all_regions(value)?;
2022 let mut inner = new_value.print(new)?;
2023 inner.region_index = old_region_index;
2024 inner.binder_depth -= 1;
2028 pub fn pretty_wrap_binder<T, C: Fn(&T, Self) -> Result<Self, fmt::Error>>(
2030 value: &ty::Binder<'tcx, T>,
2032 ) -> Result<Self, fmt::Error>
2034 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2036 let old_region_index = self.region_index;
2037 let (new, new_value, _) = self.name_all_regions(value)?;
2038 let mut inner = f(&new_value, new)?;
2039 inner.region_index = old_region_index;
2040 inner.binder_depth -= 1;
2044 #[instrument(skip(self), level = "debug")]
2045 fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<'tcx, T>)
2047 T: TypeFoldable<'tcx>,
2049 struct LateBoundRegionNameCollector<'a, 'tcx> {
2051 used_region_names: &'a mut FxHashSet<Symbol>,
2052 type_collector: SsoHashSet<Ty<'tcx>>,
2055 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_, 'tcx> {
2058 fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> {
2062 #[instrument(skip(self), level = "trace")]
2063 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
2064 trace!("address: {:p}", r);
2065 if let ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name), .. }) = *r {
2066 self.used_region_names.insert(name);
2067 } else if let ty::RePlaceholder(ty::PlaceholderRegion {
2068 name: ty::BrNamed(_, name),
2072 self.used_region_names.insert(name);
2074 r.super_visit_with(self)
2077 // We collect types in order to prevent really large types from compiling for
2078 // a really long time. See issue #83150 for why this is necessary.
2079 #[instrument(skip(self), level = "trace")]
2080 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
2081 let not_previously_inserted = self.type_collector.insert(ty);
2082 if not_previously_inserted {
2083 ty.super_visit_with(self)
2085 ControlFlow::CONTINUE
2090 self.used_region_names.clear();
2091 let mut collector = LateBoundRegionNameCollector {
2093 used_region_names: &mut self.used_region_names,
2094 type_collector: SsoHashSet::new(),
2096 value.visit_with(&mut collector);
2097 self.region_index = 0;
2101 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<'tcx, T>
2103 T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
2106 type Error = P::Error;
2107 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
2112 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
2114 T: Print<'tcx, P, Output = P, Error = P::Error>,
2115 U: Print<'tcx, P, Output = P, Error = P::Error>,
2118 type Error = P::Error;
2119 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
2120 define_scoped_cx!(cx);
2121 p!(print(self.0), ": ", print(self.1));
2126 macro_rules! forward_display_to_print {
2128 $(impl fmt::Display for $ty {
2129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2130 ty::tls::with(|tcx| {
2132 .expect("could not lift for printing")
2133 .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
2141 macro_rules! define_print_and_forward_display {
2142 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
2143 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
2145 type Error = fmt::Error;
2146 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
2147 #[allow(unused_mut)]
2149 define_scoped_cx!($cx);
2151 #[allow(unreachable_code)]
2156 forward_display_to_print!($($ty),+);
2160 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
2161 impl fmt::Display for ty::RegionKind {
2162 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2163 ty::tls::with(|tcx| {
2164 self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
2170 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2171 /// the trait path. That is, it will print `Trait<U>` instead of
2172 /// `<T as Trait<U>>`.
2173 #[derive(Copy, Clone, TypeFoldable, Lift)]
2174 pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
2176 impl fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
2177 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2178 fmt::Display::fmt(self, f)
2182 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2183 /// the trait name. That is, it will print `Trait` instead of
2184 /// `<T as Trait<U>>`.
2185 #[derive(Copy, Clone, TypeFoldable, Lift)]
2186 pub struct TraitRefPrintOnlyTraitName<'tcx>(ty::TraitRef<'tcx>);
2188 impl fmt::Debug for TraitRefPrintOnlyTraitName<'tcx> {
2189 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2190 fmt::Display::fmt(self, f)
2194 impl ty::TraitRef<'tcx> {
2195 pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
2196 TraitRefPrintOnlyTraitPath(self)
2199 pub fn print_only_trait_name(self) -> TraitRefPrintOnlyTraitName<'tcx> {
2200 TraitRefPrintOnlyTraitName(self)
2204 impl ty::Binder<'tcx, ty::TraitRef<'tcx>> {
2205 pub fn print_only_trait_path(self) -> ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>> {
2206 self.map_bound(|tr| tr.print_only_trait_path())
2210 forward_display_to_print! {
2212 &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
2213 &'tcx ty::Const<'tcx>,
2215 // HACK(eddyb) these are exhaustive instead of generic,
2216 // because `for<'tcx>` isn't possible yet.
2217 ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>,
2218 ty::Binder<'tcx, ty::TraitRef<'tcx>>,
2219 ty::Binder<'tcx, ty::ExistentialTraitRef<'tcx>>,
2220 ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>>,
2221 ty::Binder<'tcx, TraitRefPrintOnlyTraitName<'tcx>>,
2222 ty::Binder<'tcx, ty::FnSig<'tcx>>,
2223 ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2224 ty::Binder<'tcx, ty::SubtypePredicate<'tcx>>,
2225 ty::Binder<'tcx, ty::ProjectionPredicate<'tcx>>,
2226 ty::Binder<'tcx, ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
2227 ty::Binder<'tcx, ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
2229 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
2230 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
2233 define_print_and_forward_display! {
2236 &'tcx ty::List<Ty<'tcx>> {
2237 p!("{{", comma_sep(self.iter()), "}}")
2240 ty::TypeAndMut<'tcx> {
2241 p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
2244 ty::ExistentialTraitRef<'tcx> {
2245 // Use a type that can't appear in defaults of type parameters.
2246 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
2247 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
2248 p!(print(trait_ref.print_only_trait_path()))
2251 ty::ExistentialProjection<'tcx> {
2252 let name = cx.tcx().associated_item(self.item_def_id).ident;
2253 p!(write("{} = ", name), print(self.ty))
2256 ty::ExistentialPredicate<'tcx> {
2258 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
2259 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
2260 ty::ExistentialPredicate::AutoTrait(def_id) => {
2261 p!(print_def_path(def_id, &[]));
2267 p!(write("{}", self.unsafety.prefix_str()));
2269 if self.abi != Abi::Rust {
2270 p!(write("extern {} ", self.abi));
2273 p!("fn", pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
2276 ty::TraitRef<'tcx> {
2277 p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
2280 TraitRefPrintOnlyTraitPath<'tcx> {
2281 p!(print_def_path(self.0.def_id, self.0.substs));
2284 TraitRefPrintOnlyTraitName<'tcx> {
2285 p!(print_def_path(self.0.def_id, &[]));
2289 p!(write("{}", self.name))
2293 p!(write("{}", self.name))
2296 ty::SubtypePredicate<'tcx> {
2297 p!(print(self.a), " <: ", print(self.b))
2300 ty::CoercePredicate<'tcx> {
2301 p!(print(self.a), " -> ", print(self.b))
2304 ty::TraitPredicate<'tcx> {
2305 p!(print(self.trait_ref.self_ty()), ": ",
2306 print(self.trait_ref.print_only_trait_path()))
2309 ty::ProjectionPredicate<'tcx> {
2310 p!(print(self.projection_ty), " == ", print(self.ty))
2313 ty::ProjectionTy<'tcx> {
2314 p!(print_def_path(self.item_def_id, self.substs));
2319 ty::ClosureKind::Fn => p!("Fn"),
2320 ty::ClosureKind::FnMut => p!("FnMut"),
2321 ty::ClosureKind::FnOnce => p!("FnOnce"),
2325 ty::Predicate<'tcx> {
2326 let binder = self.kind();
2330 ty::PredicateKind<'tcx> {
2332 ty::PredicateKind::Trait(ref data) => {
2335 ty::PredicateKind::Subtype(predicate) => p!(print(predicate)),
2336 ty::PredicateKind::Coerce(predicate) => p!(print(predicate)),
2337 ty::PredicateKind::RegionOutlives(predicate) => p!(print(predicate)),
2338 ty::PredicateKind::TypeOutlives(predicate) => p!(print(predicate)),
2339 ty::PredicateKind::Projection(predicate) => p!(print(predicate)),
2340 ty::PredicateKind::WellFormed(arg) => p!(print(arg), " well-formed"),
2341 ty::PredicateKind::ObjectSafe(trait_def_id) => {
2342 p!("the trait `", print_def_path(trait_def_id, &[]), "` is object-safe")
2344 ty::PredicateKind::ClosureKind(closure_def_id, _closure_substs, kind) => {
2346 print_value_path(closure_def_id, &[]),
2347 write("` implements the trait `{}`", kind))
2349 ty::PredicateKind::ConstEvaluatable(uv) => {
2350 p!("the constant `", print_value_path(uv.def.did, uv.substs_.map_or(&[], |x| x)), "` can be evaluated")
2352 ty::PredicateKind::ConstEquate(c1, c2) => {
2353 p!("the constant `", print(c1), "` equals `", print(c2), "`")
2355 ty::PredicateKind::TypeWellFormedFromEnv(ty) => {
2356 p!("the type `", print(ty), "` is found in the environment")
2362 match self.unpack() {
2363 GenericArgKind::Lifetime(lt) => p!(print(lt)),
2364 GenericArgKind::Type(ty) => p!(print(ty)),
2365 GenericArgKind::Const(ct) => p!(print(ct)),
2370 fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
2371 // Iterate all local crate items no matter where they are defined.
2372 let hir = tcx.hir();
2373 for item in hir.items() {
2374 if item.ident.name.as_str().is_empty() || matches!(item.kind, ItemKind::Use(_, _)) {
2378 let def_id = item.def_id.to_def_id();
2379 let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
2380 collect_fn(&item.ident, ns, def_id);
2383 // Now take care of extern crate items.
2384 let queue = &mut Vec::new();
2385 let mut seen_defs: DefIdSet = Default::default();
2387 for &cnum in tcx.crates(()).iter() {
2388 let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
2390 // Ignore crates that are not direct dependencies.
2391 match tcx.extern_crate(def_id) {
2393 Some(extern_crate) => {
2394 if !extern_crate.is_direct() {
2403 // Iterate external crate defs but be mindful about visibility
2404 while let Some(def) = queue.pop() {
2405 for child in tcx.item_children(def).iter() {
2406 if child.vis != ty::Visibility::Public {
2411 def::Res::Def(DefKind::AssocTy, _) => {}
2412 def::Res::Def(DefKind::TyAlias, _) => {}
2413 def::Res::Def(defkind, def_id) => {
2414 if let Some(ns) = defkind.ns() {
2415 collect_fn(&child.ident, ns, def_id);
2418 if seen_defs.insert(def_id) {
2428 /// The purpose of this function is to collect public symbols names that are unique across all
2429 /// crates in the build. Later, when printing about types we can use those names instead of the
2430 /// full exported path to them.
2432 /// So essentially, if a symbol name can only be imported from one place for a type, and as
2433 /// long as it was not glob-imported anywhere in the current crate, we can trim its printed
2434 /// path and print only the name.
2436 /// This has wide implications on error messages with types, for example, shortening
2437 /// `std::vec::Vec` to just `Vec`, as long as there is no other `Vec` importable anywhere.
2439 /// The implementation uses similar import discovery logic to that of 'use' suggestions.
2440 fn trimmed_def_paths(tcx: TyCtxt<'_>, (): ()) -> FxHashMap<DefId, Symbol> {
2441 let mut map: FxHashMap<DefId, Symbol> = FxHashMap::default();
2443 if let TrimmedDefPaths::GoodPath = tcx.sess.opts.trimmed_def_paths {
2444 // For good paths causing this bug, the `rustc_middle::ty::print::with_no_trimmed_paths`
2445 // wrapper can be used to suppress this query, in exchange for full paths being formatted.
2446 tcx.sess.delay_good_path_bug("trimmed_def_paths constructed");
2449 let unique_symbols_rev: &mut FxHashMap<(Namespace, Symbol), Option<DefId>> =
2450 &mut FxHashMap::default();
2452 for symbol_set in tcx.resolutions(()).glob_map.values() {
2453 for symbol in symbol_set {
2454 unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
2455 unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
2456 unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
2460 for_each_def(tcx, |ident, ns, def_id| {
2461 use std::collections::hash_map::Entry::{Occupied, Vacant};
2463 match unique_symbols_rev.entry((ns, ident.name)) {
2464 Occupied(mut v) => match v.get() {
2467 if *existing != def_id {
2473 v.insert(Some(def_id));
2478 for ((_, symbol), opt_def_id) in unique_symbols_rev.drain() {
2479 use std::collections::hash_map::Entry::{Occupied, Vacant};
2481 if let Some(def_id) = opt_def_id {
2482 match map.entry(def_id) {
2483 Occupied(mut v) => {
2484 // A single DefId can be known under multiple names (e.g.,
2485 // with a `pub use ... as ...;`). We need to ensure that the
2486 // name placed in this map is chosen deterministically, so
2487 // if we find multiple names (`symbol`) resolving to the
2488 // same `def_id`, we prefer the lexicographically smallest
2491 // Any stable ordering would be fine here though.
2492 if *v.get() != symbol {
2493 if v.get().as_str() > symbol.as_str() {
2508 pub fn provide(providers: &mut ty::query::Providers) {
2509 *providers = ty::query::Providers { trimmed_def_paths, ..*providers };