1 use crate::middle::cstore::{ExternCrate, ExternCrateSource};
2 use crate::mir::interpret::{AllocId, ConstValue, GlobalAlloc, Pointer, Scalar};
3 use crate::ty::subst::{GenericArg, GenericArgKind, Subst};
4 use crate::ty::{self, ConstInt, DefIdTree, ParamConst, ScalarInt, Ty, TyCtxt, TypeFoldable};
5 use rustc_apfloat::ieee::{Double, Single};
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_data_structures::sso::SsoHashSet;
9 use rustc_hir::def::{self, CtorKind, DefKind, Namespace};
10 use rustc_hir::def_id::{DefId, DefIdSet, CRATE_DEF_INDEX, LOCAL_CRATE};
11 use rustc_hir::definitions::{DefPathData, DefPathDataName, DisambiguatedDefPathData};
12 use rustc_hir::ItemKind;
13 use rustc_session::config::TrimmedDefPaths;
14 use rustc_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) };
64 /// Avoids running any queries during any prints that occur
65 /// during the closure. This may alter the appearance of some
66 /// types (e.g. forcing verbose printing for opaque types).
67 /// This method is used during some queries (e.g. `explicit_item_bounds`
68 /// for opaque types), to ensure that any debug printing that
69 /// occurs during the query computation does not end up recursively
70 /// calling the same query.
71 pub fn with_no_queries<F: FnOnce() -> R, R>(f: F) -> R {
72 NO_QUERIES.with(|no_queries| {
73 let old = no_queries.replace(true);
80 /// Force us to name impls with just the filename/line number. We
81 /// normally try to use types. But at some points, notably while printing
82 /// cycle errors, this can result in extra or suboptimal error output,
83 /// so this variable disables that check.
84 pub fn with_forced_impl_filename_line<F: FnOnce() -> R, R>(f: F) -> R {
85 FORCE_IMPL_FILENAME_LINE.with(|force| {
86 let old = force.replace(true);
93 /// Adds the `crate::` prefix to paths where appropriate.
94 pub fn with_crate_prefix<F: FnOnce() -> R, R>(f: F) -> R {
95 SHOULD_PREFIX_WITH_CRATE.with(|flag| {
96 let old = flag.replace(true);
103 /// Prevent path trimming if it is turned on. Path trimming affects `Display` impl
104 /// of various rustc types, for example `std::vec::Vec` would be trimmed to `Vec`,
105 /// if no other `Vec` is found.
106 pub fn with_no_trimmed_paths<F: FnOnce() -> R, R>(f: F) -> R {
107 NO_TRIMMED_PATH.with(|flag| {
108 let old = flag.replace(true);
115 /// The "region highlights" are used to control region printing during
116 /// specific error messages. When a "region highlight" is enabled, it
117 /// gives an alternate way to print specific regions. For now, we
118 /// always print those regions using a number, so something like "`'0`".
120 /// Regions not selected by the region highlight mode are presently
122 #[derive(Copy, Clone, Default)]
123 pub struct RegionHighlightMode {
124 /// If enabled, when we see the selected region, use "`'N`"
125 /// instead of the ordinary behavior.
126 highlight_regions: [Option<(ty::RegionKind, usize)>; 3],
128 /// If enabled, when printing a "free region" that originated from
129 /// the given `ty::BoundRegionKind`, print it as "`'1`". Free regions that would ordinarily
130 /// have names print as normal.
132 /// This is used when you have a signature like `fn foo(x: &u32,
133 /// y: &'a u32)` and we want to give a name to the region of the
135 highlight_bound_region: Option<(ty::BoundRegionKind, usize)>,
138 impl RegionHighlightMode {
139 /// If `region` and `number` are both `Some`, invokes
140 /// `highlighting_region`.
141 pub fn maybe_highlighting_region(
143 region: Option<ty::Region<'_>>,
144 number: Option<usize>,
146 if let Some(k) = region {
147 if let Some(n) = number {
148 self.highlighting_region(k, n);
153 /// Highlights the region inference variable `vid` as `'N`.
154 pub fn highlighting_region(&mut self, region: ty::Region<'_>, number: usize) {
155 let num_slots = self.highlight_regions.len();
156 let first_avail_slot =
157 self.highlight_regions.iter_mut().find(|s| s.is_none()).unwrap_or_else(|| {
158 bug!("can only highlight {} placeholders at a time", num_slots,)
160 *first_avail_slot = Some((*region, number));
163 /// Convenience wrapper for `highlighting_region`.
164 pub fn highlighting_region_vid(&mut self, vid: ty::RegionVid, number: usize) {
165 self.highlighting_region(&ty::ReVar(vid), number)
168 /// Returns `Some(n)` with the number to use for the given region, if any.
169 fn region_highlighted(&self, region: ty::Region<'_>) -> Option<usize> {
170 self.highlight_regions.iter().find_map(|h| match h {
171 Some((r, n)) if r == region => Some(*n),
176 /// Highlight the given bound region.
177 /// We can only highlight one bound region at a time. See
178 /// the field `highlight_bound_region` for more detailed notes.
179 pub fn highlighting_bound_region(&mut self, br: ty::BoundRegionKind, number: usize) {
180 assert!(self.highlight_bound_region.is_none());
181 self.highlight_bound_region = Some((br, number));
185 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
186 pub trait PrettyPrinter<'tcx>:
193 DynExistential = Self,
197 /// Like `print_def_path` but for value paths.
201 substs: &'tcx [GenericArg<'tcx>],
202 ) -> Result<Self::Path, Self::Error> {
203 self.print_def_path(def_id, substs)
206 fn in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, Self::Error>
208 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
210 value.as_ref().skip_binder().print(self)
213 fn wrap_binder<T, F: Fn(&T, Self) -> Result<Self, fmt::Error>>(
215 value: &ty::Binder<'tcx, T>,
217 ) -> Result<Self, Self::Error>
219 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
221 f(value.as_ref().skip_binder(), self)
224 /// Prints comma-separated elements.
225 fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
227 T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
229 if let Some(first) = elems.next() {
230 self = first.print(self)?;
232 self.write_str(", ")?;
233 self = elem.print(self)?;
239 /// Prints `{f: t}` or `{f as t}` depending on the `cast` argument
242 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
243 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
245 ) -> Result<Self::Const, Self::Error> {
246 self.write_str("{")?;
248 self.write_str(conversion)?;
250 self.write_str("}")?;
254 /// Prints `<...>` around what `f` prints.
255 fn generic_delimiters(
257 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
258 ) -> Result<Self, Self::Error>;
260 /// Returns `true` if the region should be printed in
261 /// optional positions, e.g., `&'a T` or `dyn Tr + 'b`.
262 /// This is typically the case for all non-`'_` regions.
263 fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool;
265 // Defaults (should not be overridden):
267 /// If possible, this returns a global path resolving to `def_id` that is visible
268 /// from at least one local module, and returns `true`. If the crate defining `def_id` is
269 /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
270 fn try_print_visible_def_path(self, def_id: DefId) -> Result<(Self, bool), Self::Error> {
271 let mut callers = Vec::new();
272 self.try_print_visible_def_path_recur(def_id, &mut callers)
275 /// Try to see if this path can be trimmed to a unique symbol name.
276 fn try_print_trimmed_def_path(
279 ) -> Result<(Self::Path, bool), Self::Error> {
280 if !self.tcx().sess.opts.debugging_opts.trim_diagnostic_paths
281 || matches!(self.tcx().sess.opts.trimmed_def_paths, TrimmedDefPaths::Never)
282 || NO_TRIMMED_PATH.with(|flag| flag.get())
283 || SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get())
285 return Ok((self, false));
288 match self.tcx().trimmed_def_paths(()).get(&def_id) {
289 None => Ok((self, false)),
291 self.write_str(&symbol.as_str())?;
297 /// Does the work of `try_print_visible_def_path`, building the
298 /// full definition path recursively before attempting to
299 /// post-process it into the valid and visible version that
300 /// accounts for re-exports.
302 /// This method should only be called by itself or
303 /// `try_print_visible_def_path`.
305 /// `callers` is a chain of visible_parent's leading to `def_id`,
306 /// to support cycle detection during recursion.
307 fn try_print_visible_def_path_recur(
310 callers: &mut Vec<DefId>,
311 ) -> Result<(Self, bool), Self::Error> {
312 define_scoped_cx!(self);
314 debug!("try_print_visible_def_path: def_id={:?}", def_id);
316 // If `def_id` is a direct or injected extern crate, return the
317 // path to the crate followed by the path to the item within the crate.
318 if def_id.index == CRATE_DEF_INDEX {
319 let cnum = def_id.krate;
321 if cnum == LOCAL_CRATE {
322 return Ok((self.path_crate(cnum)?, true));
325 // In local mode, when we encounter a crate other than
326 // LOCAL_CRATE, execution proceeds in one of two ways:
328 // 1. For a direct dependency, where user added an
329 // `extern crate` manually, we put the `extern
330 // crate` as the parent. So you wind up with
331 // something relative to the current crate.
332 // 2. For an extern inferred from a path or an indirect crate,
333 // where there is no explicit `extern crate`, we just prepend
335 match self.tcx().extern_crate(def_id) {
336 Some(&ExternCrate { src, dependency_of, span, .. }) => match (src, dependency_of) {
337 (ExternCrateSource::Extern(def_id), LOCAL_CRATE) => {
338 debug!("try_print_visible_def_path: def_id={:?}", def_id);
340 if !span.is_dummy() {
341 self.print_def_path(def_id, &[])?
343 self.path_crate(cnum)?
348 (ExternCrateSource::Path, LOCAL_CRATE) => {
349 debug!("try_print_visible_def_path: def_id={:?}", def_id);
350 return Ok((self.path_crate(cnum)?, true));
355 return Ok((self.path_crate(cnum)?, true));
360 if def_id.is_local() {
361 return Ok((self, false));
364 let visible_parent_map = self.tcx().visible_parent_map(());
366 let mut cur_def_key = self.tcx().def_key(def_id);
367 debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
369 // For a constructor, we want the name of its parent rather than <unnamed>.
370 if let DefPathData::Ctor = cur_def_key.disambiguated_data.data {
375 .expect("`DefPathData::Ctor` / `VariantData` missing a parent"),
378 cur_def_key = self.tcx().def_key(parent);
381 let visible_parent = match visible_parent_map.get(&def_id).cloned() {
382 Some(parent) => parent,
383 None => return Ok((self, false)),
385 if callers.contains(&visible_parent) {
386 return Ok((self, false));
388 callers.push(visible_parent);
389 // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
390 // knowing ahead of time whether the entire path will succeed or not.
391 // To support printers that do not implement `PrettyPrinter`, a `Vec` or
392 // linked list on the stack would need to be built, before any printing.
393 match self.try_print_visible_def_path_recur(visible_parent, callers)? {
394 (cx, false) => return Ok((cx, false)),
395 (cx, true) => self = cx,
398 let actual_parent = self.tcx().parent(def_id);
400 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
401 visible_parent, actual_parent,
404 let mut data = cur_def_key.disambiguated_data.data;
406 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
407 data, visible_parent, actual_parent,
411 // In order to output a path that could actually be imported (valid and visible),
412 // we need to handle re-exports correctly.
414 // For example, take `std::os::unix::process::CommandExt`, this trait is actually
415 // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
417 // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is
418 // private so the "true" path to `CommandExt` isn't accessible.
420 // In this case, the `visible_parent_map` will look something like this:
422 // (child) -> (parent)
423 // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
424 // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
425 // `std::sys::unix::ext` -> `std::os`
427 // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
430 // When printing the path to `CommandExt` and looking at the `cur_def_key` that
431 // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
432 // to the parent - resulting in a mangled path like
433 // `std::os::ext::process::CommandExt`.
435 // Instead, we must detect that there was a re-export and instead print `unix`
436 // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
437 // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
438 // the visible parent (`std::os`). If these do not match, then we iterate over
439 // the children of the visible parent (as was done when computing
440 // `visible_parent_map`), looking for the specific child we currently have and then
441 // have access to the re-exported name.
442 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
445 .item_children(visible_parent)
447 .find(|child| child.res.opt_def_id() == Some(def_id))
448 .map(|child| child.ident.name);
449 if let Some(reexport) = reexport {
453 // Re-exported `extern crate` (#43189).
454 DefPathData::CrateRoot => {
455 data = DefPathData::TypeNs(self.tcx().original_crate_name(def_id.krate));
459 debug!("try_print_visible_def_path: data={:?}", data);
461 Ok((self.path_append(Ok, &DisambiguatedDefPathData { data, disambiguator: 0 })?, true))
464 fn pretty_path_qualified(
467 trait_ref: Option<ty::TraitRef<'tcx>>,
468 ) -> Result<Self::Path, Self::Error> {
469 if trait_ref.is_none() {
470 // Inherent impls. Try to print `Foo::bar` for an inherent
471 // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
472 // anything other than a simple path.
473 match self_ty.kind() {
482 return self_ty.print(self);
489 self.generic_delimiters(|mut cx| {
490 define_scoped_cx!(cx);
493 if let Some(trait_ref) = trait_ref {
494 p!(" as ", print(trait_ref.print_only_trait_path()));
500 fn pretty_path_append_impl(
502 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
504 trait_ref: Option<ty::TraitRef<'tcx>>,
505 ) -> Result<Self::Path, Self::Error> {
506 self = print_prefix(self)?;
508 self.generic_delimiters(|mut cx| {
509 define_scoped_cx!(cx);
512 if let Some(trait_ref) = trait_ref {
513 p!(print(trait_ref.print_only_trait_path()), " for ");
521 fn pretty_print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
522 define_scoped_cx!(self);
525 ty::Bool => p!("bool"),
526 ty::Char => p!("char"),
527 ty::Int(t) => p!(write("{}", t.name_str())),
528 ty::Uint(t) => p!(write("{}", t.name_str())),
529 ty::Float(t) => p!(write("{}", t.name_str())),
530 ty::RawPtr(ref tm) => {
534 hir::Mutability::Mut => "mut",
535 hir::Mutability::Not => "const",
540 ty::Ref(r, ty, mutbl) => {
542 if self.region_should_not_be_omitted(r) {
545 p!(print(ty::TypeAndMut { ty, mutbl }))
547 ty::Never => p!("!"),
548 ty::Tuple(ref tys) => {
549 p!("(", comma_sep(tys.iter()));
555 ty::FnDef(def_id, substs) => {
556 let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs);
557 p!(print(sig), " {{", print_value_path(def_id, substs), "}}");
559 ty::FnPtr(ref bare_fn) => p!(print(bare_fn)),
560 ty::Infer(infer_ty) => {
561 let verbose = self.tcx().sess.verbose();
562 if let ty::TyVar(ty_vid) = infer_ty {
563 if let Some(name) = self.infer_ty_name(ty_vid) {
564 p!(write("{}", name))
567 p!(write("{:?}", infer_ty))
569 p!(write("{}", infer_ty))
573 if verbose { p!(write("{:?}", infer_ty)) } else { p!(write("{}", infer_ty)) }
576 ty::Error(_) => p!("[type error]"),
577 ty::Param(ref param_ty) => p!(write("{}", param_ty)),
578 ty::Bound(debruijn, bound_ty) => match bound_ty.kind {
579 ty::BoundTyKind::Anon => self.pretty_print_bound_var(debruijn, bound_ty.var)?,
580 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
582 ty::Adt(def, substs) => {
583 p!(print_def_path(def.did, substs));
585 ty::Dynamic(data, r) => {
586 let print_r = self.region_should_not_be_omitted(r);
590 p!("dyn ", print(data));
592 p!(" + ", print(r), ")");
595 ty::Foreign(def_id) => {
596 p!(print_def_path(def_id, &[]));
598 ty::Projection(ref data) => p!(print(data)),
599 ty::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
600 ty::Opaque(def_id, substs) => {
601 // FIXME(eddyb) print this with `print_def_path`.
602 // We use verbose printing in 'NO_QUERIES' mode, to
603 // avoid needing to call `predicates_of`. This should
604 // only affect certain debug messages (e.g. messages printed
605 // from `rustc_middle::ty` during the computation of `tcx.predicates_of`),
606 // and should have no effect on any compiler output.
607 if self.tcx().sess.verbose() || NO_QUERIES.with(|q| q.get()) {
608 p!(write("Opaque({:?}, {:?})", def_id, substs));
612 return with_no_queries(|| {
613 let def_key = self.tcx().def_key(def_id);
614 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
615 p!(write("{}", name));
616 // FIXME(eddyb) print this with `print_def_path`.
617 if !substs.is_empty() {
619 p!(generic_delimiters(|cx| cx.comma_sep(substs.iter())));
623 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
624 // by looking up the projections associated with the def_id.
625 let bounds = self.tcx().explicit_item_bounds(def_id);
627 let mut first = true;
628 let mut is_sized = false;
630 for (predicate, _) in bounds {
631 let predicate = predicate.subst(self.tcx(), substs);
632 let bound_predicate = predicate.kind();
633 if let ty::PredicateKind::Trait(pred, _) = bound_predicate.skip_binder() {
634 let trait_ref = bound_predicate.rebind(pred.trait_ref);
635 // Don't print +Sized, but rather +?Sized if absent.
636 if Some(trait_ref.def_id()) == self.tcx().lang_items().sized_trait() {
642 write("{}", if first { " " } else { "+" }),
643 print(trait_ref.print_only_trait_path())
649 p!(write("{}?Sized", if first { " " } else { "+" }));
656 ty::Str => p!("str"),
657 ty::Generator(did, substs, movability) => {
660 hir::Movability::Movable => {}
661 hir::Movability::Static => p!("static "),
664 if !self.tcx().sess.verbose() {
666 // FIXME(eddyb) should use `def_span`.
667 if let Some(did) = did.as_local() {
668 let hir_id = self.tcx().hir().local_def_id_to_hir_id(did);
669 let span = self.tcx().hir().span(hir_id);
672 // This may end up in stderr diagnostics but it may also be emitted
673 // into MIR. Hence we use the remapped path if available
674 self.tcx().sess.source_map().span_to_embeddable_string(span)
677 p!(write("@"), print_def_path(did, substs));
680 p!(print_def_path(did, substs));
682 if !substs.as_generator().is_valid() {
685 self = self.comma_sep(substs.as_generator().upvar_tys())?;
690 if substs.as_generator().is_valid() {
691 p!(" ", print(substs.as_generator().witness()));
696 ty::GeneratorWitness(types) => {
697 p!(in_binder(&types));
699 ty::Closure(did, substs) => {
701 if !self.tcx().sess.verbose() {
702 p!(write("closure"));
703 // FIXME(eddyb) should use `def_span`.
704 if let Some(did) = did.as_local() {
705 let hir_id = self.tcx().hir().local_def_id_to_hir_id(did);
706 if self.tcx().sess.opts.debugging_opts.span_free_formats {
707 p!("@", print_def_path(did.to_def_id(), substs));
709 let span = self.tcx().hir().span(hir_id);
712 // This may end up in stderr diagnostics but it may also be emitted
713 // into MIR. Hence we use the remapped path if available
714 self.tcx().sess.source_map().span_to_embeddable_string(span)
718 p!(write("@"), print_def_path(did, substs));
721 p!(print_def_path(did, substs));
722 if !substs.as_closure().is_valid() {
723 p!(" closure_substs=(unavailable)");
725 p!(" closure_kind_ty=", print(substs.as_closure().kind_ty()));
727 " closure_sig_as_fn_ptr_ty=",
728 print(substs.as_closure().sig_as_fn_ptr_ty())
731 self = self.comma_sep(substs.as_closure().upvar_tys())?;
737 ty::Array(ty, sz) => {
738 p!("[", print(ty), "; ");
739 if self.tcx().sess.verbose() {
740 p!(write("{:?}", sz));
741 } else if let ty::ConstKind::Unevaluated(..) = sz.val {
742 // Do not try to evaluate unevaluated constants. If we are const evaluating an
743 // array length anon const, rustc will (with debug assertions) print the
744 // constant's path. Which will end up here again.
746 } else if let Some(n) = sz.val.try_to_bits(self.tcx().data_layout.pointer_size) {
748 } else if let ty::ConstKind::Param(param) = sz.val {
749 p!(write("{}", param));
755 ty::Slice(ty) => p!("[", print(ty), "]"),
761 fn pretty_print_bound_var(
763 debruijn: ty::DebruijnIndex,
765 ) -> Result<(), Self::Error> {
766 if debruijn == ty::INNERMOST {
767 write!(self, "^{}", var.index())
769 write!(self, "^{}_{}", debruijn.index(), var.index())
773 fn infer_ty_name(&self, _: ty::TyVid) -> Option<String> {
777 fn pretty_print_dyn_existential(
779 predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
780 ) -> Result<Self::DynExistential, Self::Error> {
781 // Generate the main trait ref, including associated types.
782 let mut first = true;
784 if let Some(principal) = predicates.principal() {
785 self = self.wrap_binder(&principal, |principal, mut cx| {
786 define_scoped_cx!(cx);
787 p!(print_def_path(principal.def_id, &[]));
789 let mut resugared = false;
791 // Special-case `Fn(...) -> ...` and resugar it.
792 let fn_trait_kind = cx.tcx().fn_trait_kind_from_lang_item(principal.def_id);
793 if !cx.tcx().sess.verbose() && fn_trait_kind.is_some() {
794 if let ty::Tuple(ref args) = principal.substs.type_at(0).kind() {
795 let mut projections = predicates.projection_bounds();
796 if let (Some(proj), None) = (projections.next(), projections.next()) {
797 let tys: Vec<_> = args.iter().map(|k| k.expect_ty()).collect();
798 p!(pretty_fn_sig(&tys, false, proj.skip_binder().ty));
804 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
805 // in order to place the projections inside the `<...>`.
807 // Use a type that can't appear in defaults of type parameters.
808 let dummy_cx = cx.tcx().mk_ty_infer(ty::FreshTy(0));
809 let principal = principal.with_self_ty(cx.tcx(), dummy_cx);
811 let args = cx.generic_args_to_print(
812 cx.tcx().generics_of(principal.def_id),
816 // Don't print `'_` if there's no unerased regions.
817 let print_regions = args.iter().any(|arg| match arg.unpack() {
818 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
821 let mut args = args.iter().cloned().filter(|arg| match arg.unpack() {
822 GenericArgKind::Lifetime(_) => print_regions,
825 let mut projections = predicates.projection_bounds();
827 let arg0 = args.next();
828 let projection0 = projections.next();
829 if arg0.is_some() || projection0.is_some() {
830 let args = arg0.into_iter().chain(args);
831 let projections = projection0.into_iter().chain(projections);
833 p!(generic_delimiters(|mut cx| {
834 cx = cx.comma_sep(args)?;
835 if arg0.is_some() && projection0.is_some() {
838 cx.comma_sep(projections)
848 define_scoped_cx!(self);
851 // FIXME(eddyb) avoid printing twice (needed to ensure
852 // that the auto traits are sorted *and* printed via cx).
853 let mut auto_traits: Vec<_> =
854 predicates.auto_traits().map(|did| (self.tcx().def_path_str(did), did)).collect();
856 // The auto traits come ordered by `DefPathHash`. While
857 // `DefPathHash` is *stable* in the sense that it depends on
858 // neither the host nor the phase of the moon, it depends
859 // "pseudorandomly" on the compiler version and the target.
861 // To avoid that causing instabilities in compiletest
862 // output, sort the auto-traits alphabetically.
865 for (_, def_id) in auto_traits {
871 p!(print_def_path(def_id, &[]));
882 ) -> Result<Self, Self::Error> {
883 define_scoped_cx!(self);
885 p!("(", comma_sep(inputs.iter().copied()));
887 if !inputs.is_empty() {
893 if !output.is_unit() {
894 p!(" -> ", print(output));
900 fn pretty_print_const(
902 ct: &'tcx ty::Const<'tcx>,
904 ) -> Result<Self::Const, Self::Error> {
905 define_scoped_cx!(self);
907 if self.tcx().sess.verbose() {
908 p!(write("Const({:?}: {:?})", ct.val, ct.ty));
912 macro_rules! print_underscore {
915 self = self.typed_value(
920 |this| this.print_type(ct.ty),
930 ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted }) => {
931 if let Some(promoted) = promoted {
932 p!(print_value_path(def.did, substs));
933 p!(write("::{:?}", promoted));
935 match self.tcx().def_kind(def.did) {
936 DefKind::Static | DefKind::Const | DefKind::AssocConst => {
937 p!(print_value_path(def.did, substs))
941 let span = self.tcx().def_span(def.did);
942 if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span)
944 p!(write("{}", snip))
955 ty::ConstKind::Infer(..) => print_underscore!(),
956 ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)),
957 ty::ConstKind::Value(value) => {
958 return self.pretty_print_const_value(value, ct.ty, print_ty);
961 ty::ConstKind::Bound(debruijn, bound_var) => {
962 self.pretty_print_bound_var(debruijn, bound_var)?
964 ty::ConstKind::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
965 ty::ConstKind::Error(_) => p!("[const error]"),
970 fn pretty_print_const_scalar(
975 ) -> Result<Self::Const, Self::Error> {
977 Scalar::Ptr(ptr) => self.pretty_print_const_scalar_ptr(ptr, ty, print_ty),
978 Scalar::Int(int) => self.pretty_print_const_scalar_int(int, ty, print_ty),
982 fn pretty_print_const_scalar_ptr(
987 ) -> Result<Self::Const, Self::Error> {
988 define_scoped_cx!(self);
991 // Byte strings (&[u8; N])
997 ty::TyS { kind: ty::Uint(ty::UintTy::U8), .. },
999 val: ty::ConstKind::Value(ConstValue::Scalar(int)), ..
1005 ) => match self.tcx().get_global_alloc(ptr.alloc_id) {
1006 Some(GlobalAlloc::Memory(alloc)) => {
1007 let bytes = int.assert_bits(self.tcx().data_layout.pointer_size);
1008 let size = Size::from_bytes(bytes);
1009 if let Ok(byte_str) = alloc.get_bytes(&self.tcx(), ptr, size) {
1010 p!(pretty_print_byte_str(byte_str))
1012 p!("<too short allocation>")
1015 // FIXME: for statics and functions, we could in principle print more detail.
1016 Some(GlobalAlloc::Static(def_id)) => p!(write("<static({:?})>", def_id)),
1017 Some(GlobalAlloc::Function(_)) => p!("<function>"),
1018 None => p!("<dangling pointer>"),
1021 // FIXME: We should probably have a helper method to share code with the "Byte strings"
1022 // printing above (which also has to handle pointers to all sorts of things).
1023 match self.tcx().get_global_alloc(ptr.alloc_id) {
1024 Some(GlobalAlloc::Function(instance)) => {
1025 self = self.typed_value(
1026 |this| this.print_value_path(instance.def_id(), instance.substs),
1027 |this| this.print_type(ty),
1031 _ => self = self.pretty_print_const_pointer(ptr, ty, print_ty)?,
1034 // Any pointer values not covered by a branch above
1036 self = self.pretty_print_const_pointer(ptr, ty, print_ty)?;
1042 fn pretty_print_const_scalar_int(
1047 ) -> Result<Self::Const, Self::Error> {
1048 define_scoped_cx!(self);
1052 ty::Bool if int == ScalarInt::FALSE => p!("false"),
1053 ty::Bool if int == ScalarInt::TRUE => p!("true"),
1055 ty::Float(ty::FloatTy::F32) => {
1056 p!(write("{}f32", Single::try_from(int).unwrap()))
1058 ty::Float(ty::FloatTy::F64) => {
1059 p!(write("{}f64", Double::try_from(int).unwrap()))
1062 ty::Uint(_) | ty::Int(_) => {
1064 ConstInt::new(int, matches!(ty.kind(), ty::Int(_)), ty.is_ptr_sized_integral());
1065 if print_ty { p!(write("{:#?}", int)) } else { p!(write("{:?}", int)) }
1068 ty::Char if char::try_from(int).is_ok() => {
1069 p!(write("{:?}", char::try_from(int).unwrap()))
1072 ty::RawPtr(_) | ty::FnPtr(_) => {
1073 let data = int.assert_bits(self.tcx().data_layout.pointer_size);
1074 self = self.typed_value(
1076 write!(this, "0x{:x}", data)?;
1079 |this| this.print_type(ty),
1083 // For function type zsts just printing the path is enough
1084 ty::FnDef(d, s) if int == ScalarInt::ZST => {
1085 p!(print_value_path(*d, s))
1087 // Nontrivial types with scalar bit representation
1089 let print = |mut this: Self| {
1090 if int.size() == Size::ZERO {
1091 write!(this, "transmute(())")?;
1093 write!(this, "transmute(0x{:x})", int)?;
1097 self = if print_ty {
1098 self.typed_value(print, |this| this.print_type(ty), ": ")?
1107 /// This is overridden for MIR printing because we only want to hide alloc ids from users, not
1108 /// from MIR where it is actually useful.
1109 fn pretty_print_const_pointer(
1114 ) -> Result<Self::Const, Self::Error> {
1118 this.write_str("&_")?;
1121 |this| this.print_type(ty),
1125 self.write_str("&_")?;
1130 fn pretty_print_byte_str(mut self, byte_str: &'tcx [u8]) -> Result<Self::Const, Self::Error> {
1131 define_scoped_cx!(self);
1133 for &c in byte_str {
1134 for e in std::ascii::escape_default(c) {
1135 self.write_char(e as char)?;
1142 fn pretty_print_const_value(
1144 ct: ConstValue<'tcx>,
1147 ) -> Result<Self::Const, Self::Error> {
1148 define_scoped_cx!(self);
1150 if self.tcx().sess.verbose() {
1151 p!(write("ConstValue({:?}: ", ct), print(ty), ")");
1155 let u8_type = self.tcx().types.u8;
1157 match (ct, ty.kind()) {
1158 // Byte/string slices, printed as (byte) string literals.
1160 ConstValue::Slice { data, start, end },
1161 ty::Ref(_, ty::TyS { kind: ty::Slice(t), .. }, _),
1162 ) if *t == u8_type => {
1163 // The `inspect` here is okay since we checked the bounds, and there are
1164 // no relocations (we have an active slice reference here). We don't use
1165 // this result to affect interpreter execution.
1166 let byte_str = data.inspect_with_uninit_and_ptr_outside_interpreter(start..end);
1167 self.pretty_print_byte_str(byte_str)
1170 ConstValue::Slice { data, start, end },
1171 ty::Ref(_, ty::TyS { kind: ty::Str, .. }, _),
1173 // The `inspect` here is okay since we checked the bounds, and there are no
1174 // relocations (we have an active `str` reference here). We don't use this
1175 // result to affect interpreter execution.
1176 let slice = data.inspect_with_uninit_and_ptr_outside_interpreter(start..end);
1177 let s = std::str::from_utf8(slice).expect("non utf8 str from miri");
1178 p!(write("{:?}", s));
1181 (ConstValue::ByRef { alloc, offset }, ty::Array(t, n)) if *t == u8_type => {
1182 let n = n.val.try_to_bits(self.tcx().data_layout.pointer_size).unwrap();
1183 // cast is ok because we already checked for pointer size (32 or 64 bit) above
1184 let n = Size::from_bytes(n);
1185 let ptr = Pointer::new(AllocId(0), offset);
1187 let byte_str = alloc.get_bytes(&self.tcx(), ptr, n).unwrap();
1189 p!(pretty_print_byte_str(byte_str));
1193 // Aggregates, printed as array/tuple/struct/variant construction syntax.
1195 // NB: the `has_param_types_or_consts` check ensures that we can use
1196 // the `destructure_const` query with an empty `ty::ParamEnv` without
1197 // introducing ICEs (e.g. via `layout_of`) from missing bounds.
1198 // E.g. `transmute([0usize; 2]): (u8, *mut T)` needs to know `T: Sized`
1199 // to be able to destructure the tuple into `(0u8, *mut T)
1201 // FIXME(eddyb) for `--emit=mir`/`-Z dump-mir`, we should provide the
1202 // correct `ty::ParamEnv` to allow printing *all* constant values.
1203 (_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) if !ty.has_param_types_or_consts() => {
1204 let contents = self.tcx().destructure_const(
1205 ty::ParamEnv::reveal_all()
1206 .and(self.tcx().mk_const(ty::Const { val: ty::ConstKind::Value(ct), ty })),
1208 let fields = contents.fields.iter().copied();
1212 p!("[", comma_sep(fields), "]");
1215 p!("(", comma_sep(fields));
1216 if contents.fields.len() == 1 {
1221 ty::Adt(def, substs) if def.variants.is_empty() => {
1222 p!(print_value_path(def.did, substs));
1224 ty::Adt(def, substs) => {
1226 contents.variant.expect("destructed const of adt without variant id");
1227 let variant_def = &def.variants[variant_id];
1228 p!(print_value_path(variant_def.def_id, substs));
1230 match variant_def.ctor_kind {
1231 CtorKind::Const => {}
1233 p!("(", comma_sep(fields), ")");
1235 CtorKind::Fictive => {
1237 let mut first = true;
1238 for (field_def, field) in iter::zip(&variant_def.fields, fields) {
1242 p!(write("{}: ", field_def.ident), print(field));
1249 _ => unreachable!(),
1255 (ConstValue::Scalar(scalar), _) => self.pretty_print_const_scalar(scalar, ty, print_ty),
1257 // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
1258 // their fields instead of just dumping the memory.
1261 p!(write("{:?}", ct));
1263 p!(": ", print(ty));
1271 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
1272 pub struct FmtPrinter<'a, 'tcx, F>(Box<FmtPrinterData<'a, 'tcx, F>>);
1274 pub struct FmtPrinterData<'a, 'tcx, F> {
1280 pub print_alloc_ids: bool,
1282 used_region_names: FxHashSet<Symbol>,
1283 region_index: usize,
1284 binder_depth: usize,
1285 printed_type_count: usize,
1287 pub region_highlight_mode: RegionHighlightMode,
1289 pub name_resolver: Option<Box<&'a dyn Fn(ty::TyVid) -> Option<String>>>,
1292 impl<F> Deref for FmtPrinter<'a, 'tcx, F> {
1293 type Target = FmtPrinterData<'a, 'tcx, F>;
1294 fn deref(&self) -> &Self::Target {
1299 impl<F> DerefMut for FmtPrinter<'_, '_, F> {
1300 fn deref_mut(&mut self) -> &mut Self::Target {
1305 impl<F> FmtPrinter<'a, 'tcx, F> {
1306 pub fn new(tcx: TyCtxt<'tcx>, fmt: F, ns: Namespace) -> Self {
1307 FmtPrinter(Box::new(FmtPrinterData {
1311 in_value: ns == Namespace::ValueNS,
1312 print_alloc_ids: false,
1313 used_region_names: Default::default(),
1316 printed_type_count: 0,
1317 region_highlight_mode: RegionHighlightMode::default(),
1318 name_resolver: None,
1323 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1324 // (but also some things just print a `DefId` generally so maybe we need this?)
1325 fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
1326 match tcx.def_key(def_id).disambiguated_data.data {
1327 DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::ImplTrait => {
1331 DefPathData::ValueNs(..)
1332 | DefPathData::AnonConst
1333 | DefPathData::ClosureExpr
1334 | DefPathData::Ctor => Namespace::ValueNS,
1336 DefPathData::MacroNs(..) => Namespace::MacroNS,
1338 _ => Namespace::TypeNS,
1343 /// Returns a string identifying this `DefId`. This string is
1344 /// suitable for user output.
1345 pub fn def_path_str(self, def_id: DefId) -> String {
1346 self.def_path_str_with_substs(def_id, &[])
1349 pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1350 let ns = guess_def_namespace(self, def_id);
1351 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1352 let mut s = String::new();
1353 let _ = FmtPrinter::new(self, &mut s, ns).print_def_path(def_id, substs);
1358 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, F> {
1359 fn write_str(&mut self, s: &str) -> fmt::Result {
1360 self.fmt.write_str(s)
1364 impl<F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
1365 type Error = fmt::Error;
1370 type DynExistential = Self;
1373 fn tcx(&'a self) -> TyCtxt<'tcx> {
1380 substs: &'tcx [GenericArg<'tcx>],
1381 ) -> Result<Self::Path, Self::Error> {
1382 define_scoped_cx!(self);
1384 if substs.is_empty() {
1385 match self.try_print_trimmed_def_path(def_id)? {
1386 (cx, true) => return Ok(cx),
1387 (cx, false) => self = cx,
1390 match self.try_print_visible_def_path(def_id)? {
1391 (cx, true) => return Ok(cx),
1392 (cx, false) => self = cx,
1396 let key = self.tcx.def_key(def_id);
1397 if let DefPathData::Impl = key.disambiguated_data.data {
1398 // Always use types for non-local impls, where types are always
1399 // available, and filename/line-number is mostly uninteresting.
1400 let use_types = !def_id.is_local() || {
1401 // Otherwise, use filename/line-number if forced.
1402 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1407 // If no type info is available, fall back to
1408 // pretty printing some span information. This should
1409 // only occur very early in the compiler pipeline.
1410 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1411 let span = self.tcx.def_span(def_id);
1413 self = self.print_def_path(parent_def_id, &[])?;
1415 // HACK(eddyb) copy of `path_append` to avoid
1416 // constructing a `DisambiguatedDefPathData`.
1417 if !self.empty_path {
1418 write!(self, "::")?;
1423 // This may end up in stderr diagnostics but it may also be emitted
1424 // into MIR. Hence we use the remapped path if available
1425 self.tcx.sess.source_map().span_to_embeddable_string(span)
1427 self.empty_path = false;
1433 self.default_print_def_path(def_id, substs)
1436 fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
1437 self.pretty_print_region(region)
1440 fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1441 let type_length_limit = self.tcx.sess.type_length_limit();
1442 if type_length_limit.value_within_limit(self.printed_type_count) {
1443 self.printed_type_count += 1;
1444 self.pretty_print_type(ty)
1446 write!(self, "...")?;
1451 fn print_dyn_existential(
1453 predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
1454 ) -> Result<Self::DynExistential, Self::Error> {
1455 self.pretty_print_dyn_existential(predicates)
1458 fn print_const(self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1459 self.pretty_print_const(ct, true)
1462 fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1463 self.empty_path = true;
1464 if cnum == LOCAL_CRATE {
1465 if self.tcx.sess.rust_2018() {
1466 // We add the `crate::` keyword on Rust 2018, only when desired.
1467 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1468 write!(self, "{}", kw::Crate)?;
1469 self.empty_path = false;
1473 write!(self, "{}", self.tcx.crate_name(cnum))?;
1474 self.empty_path = false;
1482 trait_ref: Option<ty::TraitRef<'tcx>>,
1483 ) -> Result<Self::Path, Self::Error> {
1484 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1485 self.empty_path = false;
1489 fn path_append_impl(
1491 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1492 _disambiguated_data: &DisambiguatedDefPathData,
1494 trait_ref: Option<ty::TraitRef<'tcx>>,
1495 ) -> Result<Self::Path, Self::Error> {
1496 self = self.pretty_path_append_impl(
1498 cx = print_prefix(cx)?;
1508 self.empty_path = false;
1514 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1515 disambiguated_data: &DisambiguatedDefPathData,
1516 ) -> Result<Self::Path, Self::Error> {
1517 self = print_prefix(self)?;
1519 // Skip `::{{constructor}}` on tuple/unit structs.
1520 if let DefPathData::Ctor = disambiguated_data.data {
1524 // FIXME(eddyb) `name` should never be empty, but it
1525 // currently is for `extern { ... }` "foreign modules".
1526 let name = disambiguated_data.data.name();
1527 if name != DefPathDataName::Named(kw::Empty) {
1528 if !self.empty_path {
1529 write!(self, "::")?;
1532 if let DefPathDataName::Named(name) = name {
1533 if Ident::with_dummy_span(name).is_raw_guess() {
1534 write!(self, "r#")?;
1538 let verbose = self.tcx.sess.verbose();
1539 disambiguated_data.fmt_maybe_verbose(&mut self, verbose)?;
1541 self.empty_path = false;
1547 fn path_generic_args(
1549 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1550 args: &[GenericArg<'tcx>],
1551 ) -> Result<Self::Path, Self::Error> {
1552 self = print_prefix(self)?;
1554 // Don't print `'_` if there's no unerased regions.
1555 let print_regions = args.iter().any(|arg| match arg.unpack() {
1556 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
1559 let args = args.iter().cloned().filter(|arg| match arg.unpack() {
1560 GenericArgKind::Lifetime(_) => print_regions,
1564 if args.clone().next().is_some() {
1566 write!(self, "::")?;
1568 self.generic_delimiters(|cx| cx.comma_sep(args))
1575 impl<F: fmt::Write> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx, F> {
1576 fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> {
1577 self.0.name_resolver.as_ref().and_then(|func| func(id))
1580 fn print_value_path(
1583 substs: &'tcx [GenericArg<'tcx>],
1584 ) -> Result<Self::Path, Self::Error> {
1585 let was_in_value = std::mem::replace(&mut self.in_value, true);
1586 self = self.print_def_path(def_id, substs)?;
1587 self.in_value = was_in_value;
1592 fn in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, Self::Error>
1594 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1596 self.pretty_in_binder(value)
1599 fn wrap_binder<T, C: Fn(&T, Self) -> Result<Self, Self::Error>>(
1601 value: &ty::Binder<'tcx, T>,
1603 ) -> Result<Self, Self::Error>
1605 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1607 self.pretty_wrap_binder(value, f)
1612 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1613 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
1615 ) -> Result<Self::Const, Self::Error> {
1616 self.write_str("{")?;
1618 self.write_str(conversion)?;
1619 let was_in_value = std::mem::replace(&mut self.in_value, false);
1621 self.in_value = was_in_value;
1622 self.write_str("}")?;
1626 fn generic_delimiters(
1628 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1629 ) -> Result<Self, Self::Error> {
1632 let was_in_value = std::mem::replace(&mut self.in_value, false);
1633 let mut inner = f(self)?;
1634 inner.in_value = was_in_value;
1636 write!(inner, ">")?;
1640 fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool {
1641 let highlight = self.region_highlight_mode;
1642 if highlight.region_highlighted(region).is_some() {
1646 if self.tcx.sess.verbose() {
1650 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1653 ty::ReEarlyBound(ref data) => {
1654 data.name != kw::Empty && data.name != kw::UnderscoreLifetime
1657 ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
1658 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1659 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1660 if let ty::BrNamed(_, name) = br {
1661 if name != kw::Empty && name != kw::UnderscoreLifetime {
1666 if let Some((region, _)) = highlight.highlight_bound_region {
1675 ty::ReVar(_) if identify_regions => true,
1677 ty::ReVar(_) | ty::ReErased => false,
1679 ty::ReStatic | ty::ReEmpty(_) => true,
1683 fn pretty_print_const_pointer(
1688 ) -> Result<Self::Const, Self::Error> {
1689 let print = |mut this: Self| {
1690 define_scoped_cx!(this);
1691 if this.print_alloc_ids {
1692 p!(write("{:?}", p));
1699 self.typed_value(print, |this| this.print_type(ty), ": ")
1706 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1707 impl<F: fmt::Write> FmtPrinter<'_, '_, F> {
1708 pub fn pretty_print_region(mut self, region: ty::Region<'_>) -> Result<Self, fmt::Error> {
1709 define_scoped_cx!(self);
1711 // Watch out for region highlights.
1712 let highlight = self.region_highlight_mode;
1713 if let Some(n) = highlight.region_highlighted(region) {
1714 p!(write("'{}", n));
1718 if self.tcx.sess.verbose() {
1719 p!(write("{:?}", region));
1723 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1725 // These printouts are concise. They do not contain all the information
1726 // the user might want to diagnose an error, but there is basically no way
1727 // to fit that into a short string. Hence the recommendation to use
1728 // `explain_region()` or `note_and_explain_region()`.
1730 ty::ReEarlyBound(ref data) => {
1731 if data.name != kw::Empty {
1732 p!(write("{}", data.name));
1736 ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
1737 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1738 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1739 if let ty::BrNamed(_, name) = br {
1740 if name != kw::Empty && name != kw::UnderscoreLifetime {
1741 p!(write("{}", name));
1746 if let Some((region, counter)) = highlight.highlight_bound_region {
1748 p!(write("'{}", counter));
1753 ty::ReVar(region_vid) if identify_regions => {
1754 p!(write("{:?}", region_vid));
1763 ty::ReEmpty(ty::UniverseIndex::ROOT) => {
1767 ty::ReEmpty(ui) => {
1768 p!(write("'<empty:{:?}>", ui));
1779 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1780 // `region_index` and `used_region_names`.
1781 impl<F: fmt::Write> FmtPrinter<'_, 'tcx, F> {
1782 pub fn name_all_regions<T>(
1784 value: &ty::Binder<'tcx, T>,
1785 ) -> Result<(Self, (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)), fmt::Error>
1787 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1789 fn name_by_region_index(index: usize) -> Symbol {
1791 0 => Symbol::intern("'r"),
1792 1 => Symbol::intern("'s"),
1793 i => Symbol::intern(&format!("'t{}", i - 2)),
1797 // Replace any anonymous late-bound regions with named
1798 // variants, using new unique identifiers, so that we can
1799 // clearly differentiate between named and unnamed regions in
1800 // the output. We'll probably want to tweak this over time to
1801 // decide just how much information to give.
1802 if self.binder_depth == 0 {
1803 self.prepare_late_bound_region_info(value);
1806 let mut empty = true;
1807 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1820 define_scoped_cx!(self);
1822 let mut region_index = self.region_index;
1823 // If we want to print verbosly, then print *all* binders, even if they
1824 // aren't named. Eventually, we might just want this as the default, but
1825 // this is not *quite* right and changes the ordering of some output
1827 let new_value = if self.tcx().sess.verbose() {
1828 // anon index + 1 (BrEnv takes 0) -> name
1829 let mut region_map: BTreeMap<u32, Symbol> = BTreeMap::default();
1830 let bound_vars = value.bound_vars();
1831 for var in bound_vars {
1833 ty::BoundVariableKind::Region(ty::BrNamed(_, name)) => {
1834 let _ = start_or_continue(&mut self, "for<", ", ");
1835 let _ = write!(self, "{}", name);
1837 ty::BoundVariableKind::Region(ty::BrAnon(i)) => {
1838 let _ = start_or_continue(&mut self, "for<", ", ");
1840 let name = name_by_region_index(region_index);
1842 if !self.used_region_names.contains(&name) {
1846 let _ = write!(self, "{}", name);
1847 region_map.insert(i + 1, name);
1849 ty::BoundVariableKind::Region(ty::BrEnv) => {
1850 let _ = start_or_continue(&mut self, "for<", ", ");
1852 let name = name_by_region_index(region_index);
1854 if !self.used_region_names.contains(&name) {
1858 let _ = write!(self, "{}", name);
1859 region_map.insert(0, name);
1864 start_or_continue(&mut self, "", "> ")?;
1866 self.tcx.replace_late_bound_regions(value.clone(), |br| {
1867 let kind = match br.kind {
1868 ty::BrNamed(_, _) => br.kind,
1870 let name = region_map[&(i + 1)];
1871 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1874 let name = region_map[&0];
1875 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1878 self.tcx.mk_region(ty::ReLateBound(
1880 ty::BoundRegion { var: br.var, kind },
1884 let new_value = self.tcx.replace_late_bound_regions(value.clone(), |br| {
1885 let _ = start_or_continue(&mut self, "for<", ", ");
1886 let kind = match br.kind {
1887 ty::BrNamed(_, name) => {
1888 let _ = write!(self, "{}", name);
1891 ty::BrAnon(_) | ty::BrEnv => {
1893 let name = name_by_region_index(region_index);
1895 if !self.used_region_names.contains(&name) {
1899 let _ = write!(self, "{}", name);
1900 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1903 self.tcx.mk_region(ty::ReLateBound(
1905 ty::BoundRegion { var: br.var, kind },
1908 start_or_continue(&mut self, "", "> ")?;
1912 self.binder_depth += 1;
1913 self.region_index = region_index;
1914 Ok((self, new_value))
1917 pub fn pretty_in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, fmt::Error>
1919 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1921 let old_region_index = self.region_index;
1922 let (new, new_value) = self.name_all_regions(value)?;
1923 let mut inner = new_value.0.print(new)?;
1924 inner.region_index = old_region_index;
1925 inner.binder_depth -= 1;
1929 pub fn pretty_wrap_binder<T, C: Fn(&T, Self) -> Result<Self, fmt::Error>>(
1931 value: &ty::Binder<'tcx, T>,
1933 ) -> Result<Self, fmt::Error>
1935 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1937 let old_region_index = self.region_index;
1938 let (new, new_value) = self.name_all_regions(value)?;
1939 let mut inner = f(&new_value.0, new)?;
1940 inner.region_index = old_region_index;
1941 inner.binder_depth -= 1;
1945 fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<'tcx, T>)
1947 T: TypeFoldable<'tcx>,
1949 debug!("prepare_late_bound_region_info(value: {:?})", value);
1951 struct LateBoundRegionNameCollector<'a, 'tcx> {
1952 used_region_names: &'a mut FxHashSet<Symbol>,
1953 type_collector: SsoHashSet<Ty<'tcx>>,
1956 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_, 'tcx> {
1959 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1960 debug!("LateBoundRegionNameCollector::visit_region(r: {:?}, address: {:p})", r, &r);
1961 if let ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name), .. }) = *r {
1962 self.used_region_names.insert(name);
1964 r.super_visit_with(self)
1967 // We collect types in order to prevent really large types from compiling for
1968 // a really long time. See issue #83150 for why this is necessary.
1969 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1970 debug!("LateBoundRegionNameCollector::visit_ty(ty: {:?}", ty);
1971 let not_previously_inserted = self.type_collector.insert(ty);
1972 if not_previously_inserted {
1973 ty.super_visit_with(self)
1975 ControlFlow::CONTINUE
1980 self.used_region_names.clear();
1981 let mut collector = LateBoundRegionNameCollector {
1982 used_region_names: &mut self.used_region_names,
1983 type_collector: SsoHashSet::new(),
1985 value.visit_with(&mut collector);
1986 self.region_index = 0;
1990 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<'tcx, T>
1992 T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
1995 type Error = P::Error;
1996 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
2001 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
2003 T: Print<'tcx, P, Output = P, Error = P::Error>,
2004 U: Print<'tcx, P, Output = P, Error = P::Error>,
2007 type Error = P::Error;
2008 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
2009 define_scoped_cx!(cx);
2010 p!(print(self.0), ": ", print(self.1));
2015 macro_rules! forward_display_to_print {
2017 $(impl fmt::Display for $ty {
2018 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2019 ty::tls::with(|tcx| {
2021 .expect("could not lift for printing")
2022 .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
2030 macro_rules! define_print_and_forward_display {
2031 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
2032 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
2034 type Error = fmt::Error;
2035 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
2036 #[allow(unused_mut)]
2038 define_scoped_cx!($cx);
2040 #[allow(unreachable_code)]
2045 forward_display_to_print!($($ty),+);
2049 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
2050 impl fmt::Display for ty::RegionKind {
2051 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2052 ty::tls::with(|tcx| {
2053 self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
2059 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2060 /// the trait path. That is, it will print `Trait<U>` instead of
2061 /// `<T as Trait<U>>`.
2062 #[derive(Copy, Clone, TypeFoldable, Lift)]
2063 pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
2065 impl fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
2066 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2067 fmt::Display::fmt(self, f)
2071 impl ty::TraitRef<'tcx> {
2072 pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
2073 TraitRefPrintOnlyTraitPath(self)
2077 impl ty::Binder<'tcx, ty::TraitRef<'tcx>> {
2078 pub fn print_only_trait_path(self) -> ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>> {
2079 self.map_bound(|tr| tr.print_only_trait_path())
2083 forward_display_to_print! {
2085 &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
2086 &'tcx ty::Const<'tcx>,
2088 // HACK(eddyb) these are exhaustive instead of generic,
2089 // because `for<'tcx>` isn't possible yet.
2090 ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>,
2091 ty::Binder<'tcx, ty::TraitRef<'tcx>>,
2092 ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>>,
2093 ty::Binder<'tcx, ty::FnSig<'tcx>>,
2094 ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2095 ty::Binder<'tcx, ty::SubtypePredicate<'tcx>>,
2096 ty::Binder<'tcx, ty::ProjectionPredicate<'tcx>>,
2097 ty::Binder<'tcx, ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
2098 ty::Binder<'tcx, ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
2100 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
2101 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
2104 define_print_and_forward_display! {
2107 &'tcx ty::List<Ty<'tcx>> {
2108 p!("{{", comma_sep(self.iter()), "}}")
2111 ty::TypeAndMut<'tcx> {
2112 p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
2115 ty::ExistentialTraitRef<'tcx> {
2116 // Use a type that can't appear in defaults of type parameters.
2117 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
2118 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
2119 p!(print(trait_ref.print_only_trait_path()))
2122 ty::ExistentialProjection<'tcx> {
2123 let name = cx.tcx().associated_item(self.item_def_id).ident;
2124 p!(write("{} = ", name), print(self.ty))
2127 ty::ExistentialPredicate<'tcx> {
2129 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
2130 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
2131 ty::ExistentialPredicate::AutoTrait(def_id) => {
2132 p!(print_def_path(def_id, &[]));
2138 p!(write("{}", self.unsafety.prefix_str()));
2140 if self.abi != Abi::Rust {
2141 p!(write("extern {} ", self.abi));
2144 p!("fn", pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
2147 ty::TraitRef<'tcx> {
2148 p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
2151 TraitRefPrintOnlyTraitPath<'tcx> {
2152 p!(print_def_path(self.0.def_id, self.0.substs));
2156 p!(write("{}", self.name))
2160 p!(write("{}", self.name))
2163 ty::SubtypePredicate<'tcx> {
2164 p!(print(self.a), " <: ", print(self.b))
2167 ty::TraitPredicate<'tcx> {
2168 p!(print(self.trait_ref.self_ty()), ": ",
2169 print(self.trait_ref.print_only_trait_path()))
2172 ty::ProjectionPredicate<'tcx> {
2173 p!(print(self.projection_ty), " == ", print(self.ty))
2176 ty::ProjectionTy<'tcx> {
2177 p!(print_def_path(self.item_def_id, self.substs));
2182 ty::ClosureKind::Fn => p!("Fn"),
2183 ty::ClosureKind::FnMut => p!("FnMut"),
2184 ty::ClosureKind::FnOnce => p!("FnOnce"),
2188 ty::Predicate<'tcx> {
2189 let binder = self.kind();
2193 ty::PredicateKind<'tcx> {
2195 ty::PredicateKind::Trait(ref data, constness) => {
2196 if let hir::Constness::Const = constness {
2201 ty::PredicateKind::Subtype(predicate) => p!(print(predicate)),
2202 ty::PredicateKind::RegionOutlives(predicate) => p!(print(predicate)),
2203 ty::PredicateKind::TypeOutlives(predicate) => p!(print(predicate)),
2204 ty::PredicateKind::Projection(predicate) => p!(print(predicate)),
2205 ty::PredicateKind::WellFormed(arg) => p!(print(arg), " well-formed"),
2206 ty::PredicateKind::ObjectSafe(trait_def_id) => {
2207 p!("the trait `", print_def_path(trait_def_id, &[]), "` is object-safe")
2209 ty::PredicateKind::ClosureKind(closure_def_id, _closure_substs, kind) => {
2211 print_value_path(closure_def_id, &[]),
2212 write("` implements the trait `{}`", kind))
2214 ty::PredicateKind::ConstEvaluatable(def, substs) => {
2215 p!("the constant `", print_value_path(def.did, substs), "` can be evaluated")
2217 ty::PredicateKind::ConstEquate(c1, c2) => {
2218 p!("the constant `", print(c1), "` equals `", print(c2), "`")
2220 ty::PredicateKind::TypeWellFormedFromEnv(ty) => {
2221 p!("the type `", print(ty), "` is found in the environment")
2227 match self.unpack() {
2228 GenericArgKind::Lifetime(lt) => p!(print(lt)),
2229 GenericArgKind::Type(ty) => p!(print(ty)),
2230 GenericArgKind::Const(ct) => p!(print(ct)),
2235 fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
2236 // Iterate all local crate items no matter where they are defined.
2237 let hir = tcx.hir();
2238 for item in hir.krate().items.values() {
2239 if item.ident.name.as_str().is_empty() || matches!(item.kind, ItemKind::Use(_, _)) {
2243 let def_id = item.def_id.to_def_id();
2244 let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
2245 collect_fn(&item.ident, ns, def_id);
2248 // Now take care of extern crate items.
2249 let queue = &mut Vec::new();
2250 let mut seen_defs: DefIdSet = Default::default();
2252 for &cnum in tcx.crates().iter() {
2253 let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
2255 // Ignore crates that are not direct dependencies.
2256 match tcx.extern_crate(def_id) {
2258 Some(extern_crate) => {
2259 if !extern_crate.is_direct() {
2268 // Iterate external crate defs but be mindful about visibility
2269 while let Some(def) = queue.pop() {
2270 for child in tcx.item_children(def).iter() {
2271 if child.vis != ty::Visibility::Public {
2276 def::Res::Def(DefKind::AssocTy, _) => {}
2277 def::Res::Def(DefKind::TyAlias, _) => {}
2278 def::Res::Def(defkind, def_id) => {
2279 if let Some(ns) = defkind.ns() {
2280 collect_fn(&child.ident, ns, def_id);
2283 if seen_defs.insert(def_id) {
2293 /// The purpose of this function is to collect public symbols names that are unique across all
2294 /// crates in the build. Later, when printing about types we can use those names instead of the
2295 /// full exported path to them.
2297 /// So essentially, if a symbol name can only be imported from one place for a type, and as
2298 /// long as it was not glob-imported anywhere in the current crate, we can trim its printed
2299 /// path and print only the name.
2301 /// This has wide implications on error messages with types, for example, shortening
2302 /// `std::vec::Vec` to just `Vec`, as long as there is no other `Vec` importable anywhere.
2304 /// The implementation uses similar import discovery logic to that of 'use' suggestions.
2305 fn trimmed_def_paths(tcx: TyCtxt<'_>, (): ()) -> FxHashMap<DefId, Symbol> {
2306 let mut map = FxHashMap::default();
2308 if let TrimmedDefPaths::GoodPath = tcx.sess.opts.trimmed_def_paths {
2309 // For good paths causing this bug, the `rustc_middle::ty::print::with_no_trimmed_paths`
2310 // wrapper can be used to suppress this query, in exchange for full paths being formatted.
2311 tcx.sess.delay_good_path_bug("trimmed_def_paths constructed");
2314 let unique_symbols_rev: &mut FxHashMap<(Namespace, Symbol), Option<DefId>> =
2315 &mut FxHashMap::default();
2317 for symbol_set in tcx.glob_map.values() {
2318 for symbol in symbol_set {
2319 unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
2320 unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
2321 unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
2325 for_each_def(tcx, |ident, ns, def_id| {
2326 use std::collections::hash_map::Entry::{Occupied, Vacant};
2328 match unique_symbols_rev.entry((ns, ident.name)) {
2329 Occupied(mut v) => match v.get() {
2332 if *existing != def_id {
2338 v.insert(Some(def_id));
2343 for ((_, symbol), opt_def_id) in unique_symbols_rev.drain() {
2344 if let Some(def_id) = opt_def_id {
2345 map.insert(def_id, symbol);
2352 pub fn provide(providers: &mut ty::query::Providers) {
2353 *providers = ty::query::Providers { trimmed_def_paths, ..*providers };