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;
8 use rustc_hir::def::{self, CtorKind, DefKind, Namespace};
9 use rustc_hir::def_id::{CrateNum, 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_span::symbol::{kw, Ident, Symbol};
14 use rustc_target::abi::Size;
15 use rustc_target::spec::abi::Abi;
19 use std::collections::BTreeMap;
20 use std::convert::TryFrom;
21 use std::fmt::{self, Write as _};
22 use std::ops::{ControlFlow, Deref, DerefMut};
24 // `pretty` is a separate module only for organization.
29 write!(scoped_cx!(), $lit)?
31 (@write($($data:expr),+)) => {
32 write!(scoped_cx!(), $($data),+)?
34 (@print($x:expr)) => {
35 scoped_cx!() = $x.print(scoped_cx!())?
37 (@$method:ident($($arg:expr),*)) => {
38 scoped_cx!() = scoped_cx!().$method($($arg),*)?
40 ($($elem:tt $(($($args:tt)*))?),+) => {{
41 $(p!(@ $elem $(($($args)*))?);)+
44 macro_rules! define_scoped_cx {
46 #[allow(unused_macros)]
47 macro_rules! scoped_cx {
56 static FORCE_IMPL_FILENAME_LINE: Cell<bool> = Cell::new(false);
57 static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = Cell::new(false);
58 static NO_TRIMMED_PATH: Cell<bool> = Cell::new(false);
59 static NO_QUERIES: Cell<bool> = Cell::new(false);
62 /// Avoids running any queries during any prints that occur
63 /// during the closure. This may alter the appearance of some
64 /// types (e.g. forcing verbose printing for opaque types).
65 /// This method is used during some queries (e.g. `explicit_item_bounds`
66 /// for opaque types), to ensure that any debug printing that
67 /// occurs during the query computation does not end up recursively
68 /// calling the same query.
69 pub fn with_no_queries<F: FnOnce() -> R, R>(f: F) -> R {
70 NO_QUERIES.with(|no_queries| {
71 let old = no_queries.replace(true);
78 /// Force us to name impls with just the filename/line number. We
79 /// normally try to use types. But at some points, notably while printing
80 /// cycle errors, this can result in extra or suboptimal error output,
81 /// so this variable disables that check.
82 pub fn with_forced_impl_filename_line<F: FnOnce() -> R, R>(f: F) -> R {
83 FORCE_IMPL_FILENAME_LINE.with(|force| {
84 let old = force.replace(true);
91 /// Adds the `crate::` prefix to paths where appropriate.
92 pub fn with_crate_prefix<F: FnOnce() -> R, R>(f: F) -> R {
93 SHOULD_PREFIX_WITH_CRATE.with(|flag| {
94 let old = flag.replace(true);
101 /// Prevent path trimming if it is turned on. Path trimming affects `Display` impl
102 /// of various rustc types, for example `std::vec::Vec` would be trimmed to `Vec`,
103 /// if no other `Vec` is found.
104 pub fn with_no_trimmed_paths<F: FnOnce() -> R, R>(f: F) -> R {
105 NO_TRIMMED_PATH.with(|flag| {
106 let old = flag.replace(true);
113 /// The "region highlights" are used to control region printing during
114 /// specific error messages. When a "region highlight" is enabled, it
115 /// gives an alternate way to print specific regions. For now, we
116 /// always print those regions using a number, so something like "`'0`".
118 /// Regions not selected by the region highlight mode are presently
120 #[derive(Copy, Clone, Default)]
121 pub struct RegionHighlightMode {
122 /// If enabled, when we see the selected region, use "`'N`"
123 /// instead of the ordinary behavior.
124 highlight_regions: [Option<(ty::RegionKind, usize)>; 3],
126 /// If enabled, when printing a "free region" that originated from
127 /// the given `ty::BoundRegionKind`, print it as "`'1`". Free regions that would ordinarily
128 /// have names print as normal.
130 /// This is used when you have a signature like `fn foo(x: &u32,
131 /// y: &'a u32)` and we want to give a name to the region of the
133 highlight_bound_region: Option<(ty::BoundRegionKind, usize)>,
136 impl RegionHighlightMode {
137 /// If `region` and `number` are both `Some`, invokes
138 /// `highlighting_region`.
139 pub fn maybe_highlighting_region(
141 region: Option<ty::Region<'_>>,
142 number: Option<usize>,
144 if let Some(k) = region {
145 if let Some(n) = number {
146 self.highlighting_region(k, n);
151 /// Highlights the region inference variable `vid` as `'N`.
152 pub fn highlighting_region(&mut self, region: ty::Region<'_>, number: usize) {
153 let num_slots = self.highlight_regions.len();
154 let first_avail_slot =
155 self.highlight_regions.iter_mut().find(|s| s.is_none()).unwrap_or_else(|| {
156 bug!("can only highlight {} placeholders at a time", num_slots,)
158 *first_avail_slot = Some((*region, number));
161 /// Convenience wrapper for `highlighting_region`.
162 pub fn highlighting_region_vid(&mut self, vid: ty::RegionVid, number: usize) {
163 self.highlighting_region(&ty::ReVar(vid), number)
166 /// Returns `Some(n)` with the number to use for the given region, if any.
167 fn region_highlighted(&self, region: ty::Region<'_>) -> Option<usize> {
168 self.highlight_regions.iter().find_map(|h| match h {
169 Some((r, n)) if r == region => Some(*n),
174 /// Highlight the given bound region.
175 /// We can only highlight one bound region at a time. See
176 /// the field `highlight_bound_region` for more detailed notes.
177 pub fn highlighting_bound_region(&mut self, br: ty::BoundRegionKind, number: usize) {
178 assert!(self.highlight_bound_region.is_none());
179 self.highlight_bound_region = Some((br, number));
183 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
184 pub trait PrettyPrinter<'tcx>:
191 DynExistential = Self,
195 /// Like `print_def_path` but for value paths.
199 substs: &'tcx [GenericArg<'tcx>],
200 ) -> Result<Self::Path, Self::Error> {
201 self.print_def_path(def_id, substs)
204 fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
206 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
208 value.as_ref().skip_binder().print(self)
211 fn wrap_binder<T, F: Fn(&T, Self) -> Result<Self, fmt::Error>>(
213 value: &ty::Binder<T>,
215 ) -> Result<Self, Self::Error>
217 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
219 f(value.as_ref().skip_binder(), self)
222 /// Prints comma-separated elements.
223 fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
225 T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
227 if let Some(first) = elems.next() {
228 self = first.print(self)?;
230 self.write_str(", ")?;
231 self = elem.print(self)?;
237 /// Prints `{f: t}` or `{f as t}` depending on the `cast` argument
240 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
241 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
243 ) -> Result<Self::Const, Self::Error> {
244 self.write_str("{")?;
246 self.write_str(conversion)?;
248 self.write_str("}")?;
252 /// Prints `<...>` around what `f` prints.
253 fn generic_delimiters(
255 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
256 ) -> Result<Self, Self::Error>;
258 /// Returns `true` if the region should be printed in
259 /// optional positions, e.g., `&'a T` or `dyn Tr + 'b`.
260 /// This is typically the case for all non-`'_` regions.
261 fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool;
263 // Defaults (should not be overridden):
265 /// If possible, this returns a global path resolving to `def_id` that is visible
266 /// from at least one local module, and returns `true`. If the crate defining `def_id` is
267 /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
268 fn try_print_visible_def_path(self, def_id: DefId) -> Result<(Self, bool), Self::Error> {
269 let mut callers = Vec::new();
270 self.try_print_visible_def_path_recur(def_id, &mut callers)
273 /// Try to see if this path can be trimmed to a unique symbol name.
274 fn try_print_trimmed_def_path(
277 ) -> Result<(Self::Path, bool), Self::Error> {
278 if !self.tcx().sess.opts.debugging_opts.trim_diagnostic_paths
279 || matches!(self.tcx().sess.opts.trimmed_def_paths, TrimmedDefPaths::Never)
280 || NO_TRIMMED_PATH.with(|flag| flag.get())
281 || SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get())
283 return Ok((self, false));
286 match self.tcx().trimmed_def_paths(LOCAL_CRATE).get(&def_id) {
287 None => Ok((self, false)),
289 self.write_str(&symbol.as_str())?;
295 /// Does the work of `try_print_visible_def_path`, building the
296 /// full definition path recursively before attempting to
297 /// post-process it into the valid and visible version that
298 /// accounts for re-exports.
300 /// This method should only be called by itself or
301 /// `try_print_visible_def_path`.
303 /// `callers` is a chain of visible_parent's leading to `def_id`,
304 /// to support cycle detection during recursion.
305 fn try_print_visible_def_path_recur(
308 callers: &mut Vec<DefId>,
309 ) -> Result<(Self, bool), Self::Error> {
310 define_scoped_cx!(self);
312 debug!("try_print_visible_def_path: def_id={:?}", def_id);
314 // If `def_id` is a direct or injected extern crate, return the
315 // path to the crate followed by the path to the item within the crate.
316 if def_id.index == CRATE_DEF_INDEX {
317 let cnum = def_id.krate;
319 if cnum == LOCAL_CRATE {
320 return Ok((self.path_crate(cnum)?, true));
323 // In local mode, when we encounter a crate other than
324 // LOCAL_CRATE, execution proceeds in one of two ways:
326 // 1. For a direct dependency, where user added an
327 // `extern crate` manually, we put the `extern
328 // crate` as the parent. So you wind up with
329 // something relative to the current crate.
330 // 2. For an extern inferred from a path or an indirect crate,
331 // where there is no explicit `extern crate`, we just prepend
333 match self.tcx().extern_crate(def_id) {
334 Some(&ExternCrate { src, dependency_of, span, .. }) => match (src, dependency_of) {
335 (ExternCrateSource::Extern(def_id), LOCAL_CRATE) => {
336 debug!("try_print_visible_def_path: def_id={:?}", def_id);
338 if !span.is_dummy() {
339 self.print_def_path(def_id, &[])?
341 self.path_crate(cnum)?
346 (ExternCrateSource::Path, LOCAL_CRATE) => {
347 debug!("try_print_visible_def_path: def_id={:?}", def_id);
348 return Ok((self.path_crate(cnum)?, true));
353 return Ok((self.path_crate(cnum)?, true));
358 if def_id.is_local() {
359 return Ok((self, false));
362 let visible_parent_map = self.tcx().visible_parent_map(LOCAL_CRATE);
364 let mut cur_def_key = self.tcx().def_key(def_id);
365 debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
367 // For a constructor, we want the name of its parent rather than <unnamed>.
368 if let DefPathData::Ctor = cur_def_key.disambiguated_data.data {
373 .expect("`DefPathData::Ctor` / `VariantData` missing a parent"),
376 cur_def_key = self.tcx().def_key(parent);
379 let visible_parent = match visible_parent_map.get(&def_id).cloned() {
380 Some(parent) => parent,
381 None => return Ok((self, false)),
383 if callers.contains(&visible_parent) {
384 return Ok((self, false));
386 callers.push(visible_parent);
387 // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
388 // knowing ahead of time whether the entire path will succeed or not.
389 // To support printers that do not implement `PrettyPrinter`, a `Vec` or
390 // linked list on the stack would need to be built, before any printing.
391 match self.try_print_visible_def_path_recur(visible_parent, callers)? {
392 (cx, false) => return Ok((cx, false)),
393 (cx, true) => self = cx,
396 let actual_parent = self.tcx().parent(def_id);
398 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
399 visible_parent, actual_parent,
402 let mut data = cur_def_key.disambiguated_data.data;
404 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
405 data, visible_parent, actual_parent,
409 // In order to output a path that could actually be imported (valid and visible),
410 // we need to handle re-exports correctly.
412 // For example, take `std::os::unix::process::CommandExt`, this trait is actually
413 // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
415 // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is
416 // private so the "true" path to `CommandExt` isn't accessible.
418 // In this case, the `visible_parent_map` will look something like this:
420 // (child) -> (parent)
421 // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
422 // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
423 // `std::sys::unix::ext` -> `std::os`
425 // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
428 // When printing the path to `CommandExt` and looking at the `cur_def_key` that
429 // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
430 // to the parent - resulting in a mangled path like
431 // `std::os::ext::process::CommandExt`.
433 // Instead, we must detect that there was a re-export and instead print `unix`
434 // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
435 // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
436 // the visible parent (`std::os`). If these do not match, then we iterate over
437 // the children of the visible parent (as was done when computing
438 // `visible_parent_map`), looking for the specific child we currently have and then
439 // have access to the re-exported name.
440 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
443 .item_children(visible_parent)
445 .find(|child| child.res.opt_def_id() == Some(def_id))
446 .map(|child| child.ident.name);
447 if let Some(reexport) = reexport {
451 // Re-exported `extern crate` (#43189).
452 DefPathData::CrateRoot => {
453 data = DefPathData::TypeNs(self.tcx().original_crate_name(def_id.krate));
457 debug!("try_print_visible_def_path: data={:?}", data);
459 Ok((self.path_append(Ok, &DisambiguatedDefPathData { data, disambiguator: 0 })?, true))
462 fn pretty_path_qualified(
465 trait_ref: Option<ty::TraitRef<'tcx>>,
466 ) -> Result<Self::Path, Self::Error> {
467 if trait_ref.is_none() {
468 // Inherent impls. Try to print `Foo::bar` for an inherent
469 // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
470 // anything other than a simple path.
471 match self_ty.kind() {
480 return self_ty.print(self);
487 self.generic_delimiters(|mut cx| {
488 define_scoped_cx!(cx);
491 if let Some(trait_ref) = trait_ref {
492 p!(" as ", print(trait_ref.print_only_trait_path()));
498 fn pretty_path_append_impl(
500 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
502 trait_ref: Option<ty::TraitRef<'tcx>>,
503 ) -> Result<Self::Path, Self::Error> {
504 self = print_prefix(self)?;
506 self.generic_delimiters(|mut cx| {
507 define_scoped_cx!(cx);
510 if let Some(trait_ref) = trait_ref {
511 p!(print(trait_ref.print_only_trait_path()), " for ");
519 fn pretty_print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
520 define_scoped_cx!(self);
523 ty::Bool => p!("bool"),
524 ty::Char => p!("char"),
525 ty::Int(t) => p!(write("{}", t.name_str())),
526 ty::Uint(t) => p!(write("{}", t.name_str())),
527 ty::Float(t) => p!(write("{}", t.name_str())),
528 ty::RawPtr(ref tm) => {
532 hir::Mutability::Mut => "mut",
533 hir::Mutability::Not => "const",
538 ty::Ref(r, ty, mutbl) => {
540 if self.region_should_not_be_omitted(r) {
543 p!(print(ty::TypeAndMut { ty, mutbl }))
545 ty::Never => p!("!"),
546 ty::Tuple(ref tys) => {
547 p!("(", comma_sep(tys.iter()));
553 ty::FnDef(def_id, substs) => {
554 let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs);
555 p!(print(sig), " {{", print_value_path(def_id, substs), "}}");
557 ty::FnPtr(ref bare_fn) => p!(print(bare_fn)),
558 ty::Infer(infer_ty) => {
559 let verbose = self.tcx().sess.verbose();
560 if let ty::TyVar(ty_vid) = infer_ty {
561 if let Some(name) = self.infer_ty_name(ty_vid) {
562 p!(write("{}", name))
565 p!(write("{:?}", infer_ty))
567 p!(write("{}", infer_ty))
571 if verbose { p!(write("{:?}", infer_ty)) } else { p!(write("{}", infer_ty)) }
574 ty::Error(_) => p!("[type error]"),
575 ty::Param(ref param_ty) => p!(write("{}", param_ty)),
576 ty::Bound(debruijn, bound_ty) => match bound_ty.kind {
577 ty::BoundTyKind::Anon => self.pretty_print_bound_var(debruijn, bound_ty.var)?,
578 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
580 ty::Adt(def, substs) => {
581 p!(print_def_path(def.did, substs));
583 ty::Dynamic(data, r) => {
584 let print_r = self.region_should_not_be_omitted(r);
588 p!("dyn ", print(data));
590 p!(" + ", print(r), ")");
593 ty::Foreign(def_id) => {
594 p!(print_def_path(def_id, &[]));
596 ty::Projection(ref data) => p!(print(data)),
597 ty::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
598 ty::Opaque(def_id, substs) => {
599 // FIXME(eddyb) print this with `print_def_path`.
600 // We use verbose printing in 'NO_QUERIES' mode, to
601 // avoid needing to call `predicates_of`. This should
602 // only affect certain debug messages (e.g. messages printed
603 // from `rustc_middle::ty` during the computation of `tcx.predicates_of`),
604 // and should have no effect on any compiler output.
605 if self.tcx().sess.verbose() || NO_QUERIES.with(|q| q.get()) {
606 p!(write("Opaque({:?}, {:?})", def_id, substs));
610 return with_no_queries(|| {
611 let def_key = self.tcx().def_key(def_id);
612 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
613 p!(write("{}", name));
614 // FIXME(eddyb) print this with `print_def_path`.
615 if !substs.is_empty() {
617 p!(generic_delimiters(|cx| cx.comma_sep(substs.iter())));
621 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
622 // by looking up the projections associated with the def_id.
623 let bounds = self.tcx().explicit_item_bounds(def_id);
625 let mut first = true;
626 let mut is_sized = false;
628 for (predicate, _) in bounds {
629 let predicate = predicate.subst(self.tcx(), substs);
630 let bound_predicate = predicate.kind();
631 if let ty::PredicateKind::Trait(pred, _) = bound_predicate.skip_binder() {
632 let trait_ref = bound_predicate.rebind(pred.trait_ref);
633 // Don't print +Sized, but rather +?Sized if absent.
634 if Some(trait_ref.def_id()) == self.tcx().lang_items().sized_trait() {
640 write("{}", if first { " " } else { "+" }),
641 print(trait_ref.print_only_trait_path())
647 p!(write("{}?Sized", if first { " " } else { "+" }));
654 ty::Str => p!("str"),
655 ty::Generator(did, substs, movability) => {
658 hir::Movability::Movable => {}
659 hir::Movability::Static => p!("static "),
662 if !self.tcx().sess.verbose() {
664 // FIXME(eddyb) should use `def_span`.
665 if let Some(did) = did.as_local() {
666 let hir_id = self.tcx().hir().local_def_id_to_hir_id(did);
667 let span = self.tcx().hir().span(hir_id);
668 p!(write("@{}", self.tcx().sess.source_map().span_to_string(span)));
670 p!(write("@"), print_def_path(did, substs));
673 p!(print_def_path(did, substs));
675 if !substs.as_generator().is_valid() {
678 self = self.comma_sep(substs.as_generator().upvar_tys())?;
683 if substs.as_generator().is_valid() {
684 p!(" ", print(substs.as_generator().witness()));
689 ty::GeneratorWitness(types) => {
690 p!(in_binder(&types));
692 ty::Closure(did, substs) => {
694 if !self.tcx().sess.verbose() {
695 p!(write("closure"));
696 // FIXME(eddyb) should use `def_span`.
697 if let Some(did) = did.as_local() {
698 let hir_id = self.tcx().hir().local_def_id_to_hir_id(did);
699 if self.tcx().sess.opts.debugging_opts.span_free_formats {
700 p!("@", print_def_path(did.to_def_id(), substs));
702 let span = self.tcx().hir().span(hir_id);
703 p!(write("@{}", self.tcx().sess.source_map().span_to_string(span)));
706 p!(write("@"), print_def_path(did, substs));
709 p!(print_def_path(did, substs));
710 if !substs.as_closure().is_valid() {
711 p!(" closure_substs=(unavailable)");
713 p!(" closure_kind_ty=", print(substs.as_closure().kind_ty()));
715 " closure_sig_as_fn_ptr_ty=",
716 print(substs.as_closure().sig_as_fn_ptr_ty())
719 self = self.comma_sep(substs.as_closure().upvar_tys())?;
725 ty::Array(ty, sz) => {
726 p!("[", print(ty), "; ");
727 if self.tcx().sess.verbose() {
728 p!(write("{:?}", sz));
729 } else if let ty::ConstKind::Unevaluated(..) = sz.val {
730 // Do not try to evaluate unevaluated constants. If we are const evaluating an
731 // array length anon const, rustc will (with debug assertions) print the
732 // constant's path. Which will end up here again.
734 } else if let Some(n) = sz.val.try_to_bits(self.tcx().data_layout.pointer_size) {
736 } else if let ty::ConstKind::Param(param) = sz.val {
737 p!(write("{}", param));
743 ty::Slice(ty) => p!("[", print(ty), "]"),
749 fn pretty_print_bound_var(
751 debruijn: ty::DebruijnIndex,
753 ) -> Result<(), Self::Error> {
754 if debruijn == ty::INNERMOST {
755 write!(self, "^{}", var.index())
757 write!(self, "^{}_{}", debruijn.index(), var.index())
761 fn infer_ty_name(&self, _: ty::TyVid) -> Option<String> {
765 fn pretty_print_dyn_existential(
767 predicates: &'tcx ty::List<ty::Binder<ty::ExistentialPredicate<'tcx>>>,
768 ) -> Result<Self::DynExistential, Self::Error> {
769 // Generate the main trait ref, including associated types.
770 let mut first = true;
772 if let Some(principal) = predicates.principal() {
773 self = self.wrap_binder(&principal, |principal, mut cx| {
774 define_scoped_cx!(cx);
775 p!(print_def_path(principal.def_id, &[]));
777 let mut resugared = false;
779 // Special-case `Fn(...) -> ...` and resugar it.
780 let fn_trait_kind = cx.tcx().fn_trait_kind_from_lang_item(principal.def_id);
781 if !cx.tcx().sess.verbose() && fn_trait_kind.is_some() {
782 if let ty::Tuple(ref args) = principal.substs.type_at(0).kind() {
783 let mut projections = predicates.projection_bounds();
784 if let (Some(proj), None) = (projections.next(), projections.next()) {
785 let tys: Vec<_> = args.iter().map(|k| k.expect_ty()).collect();
786 p!(pretty_fn_sig(&tys, false, proj.skip_binder().ty));
792 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
793 // in order to place the projections inside the `<...>`.
795 // Use a type that can't appear in defaults of type parameters.
796 let dummy_cx = cx.tcx().mk_ty_infer(ty::FreshTy(0));
797 let principal = principal.with_self_ty(cx.tcx(), dummy_cx);
799 let args = cx.generic_args_to_print(
800 cx.tcx().generics_of(principal.def_id),
804 // Don't print `'_` if there's no unerased regions.
805 let print_regions = args.iter().any(|arg| match arg.unpack() {
806 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
809 let mut args = args.iter().cloned().filter(|arg| match arg.unpack() {
810 GenericArgKind::Lifetime(_) => print_regions,
813 let mut projections = predicates.projection_bounds();
815 let arg0 = args.next();
816 let projection0 = projections.next();
817 if arg0.is_some() || projection0.is_some() {
818 let args = arg0.into_iter().chain(args);
819 let projections = projection0.into_iter().chain(projections);
821 p!(generic_delimiters(|mut cx| {
822 cx = cx.comma_sep(args)?;
823 if arg0.is_some() && projection0.is_some() {
826 cx.comma_sep(projections)
836 define_scoped_cx!(self);
839 // FIXME(eddyb) avoid printing twice (needed to ensure
840 // that the auto traits are sorted *and* printed via cx).
841 let mut auto_traits: Vec<_> =
842 predicates.auto_traits().map(|did| (self.tcx().def_path_str(did), did)).collect();
844 // The auto traits come ordered by `DefPathHash`. While
845 // `DefPathHash` is *stable* in the sense that it depends on
846 // neither the host nor the phase of the moon, it depends
847 // "pseudorandomly" on the compiler version and the target.
849 // To avoid that causing instabilities in compiletest
850 // output, sort the auto-traits alphabetically.
853 for (_, def_id) in auto_traits {
859 p!(print_def_path(def_id, &[]));
870 ) -> Result<Self, Self::Error> {
871 define_scoped_cx!(self);
873 p!("(", comma_sep(inputs.iter().copied()));
875 if !inputs.is_empty() {
881 if !output.is_unit() {
882 p!(" -> ", print(output));
888 fn pretty_print_const(
890 ct: &'tcx ty::Const<'tcx>,
892 ) -> Result<Self::Const, Self::Error> {
893 define_scoped_cx!(self);
895 if self.tcx().sess.verbose() {
896 p!(write("Const({:?}: {:?})", ct.val, ct.ty));
900 macro_rules! print_underscore {
903 self = self.typed_value(
908 |this| this.print_type(ct.ty),
918 ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted }) => {
919 if let Some(promoted) = promoted {
920 p!(print_value_path(def.did, substs));
921 p!(write("::{:?}", promoted));
923 match self.tcx().def_kind(def.did) {
924 DefKind::Static | DefKind::Const | DefKind::AssocConst => {
925 p!(print_value_path(def.did, substs))
929 let span = self.tcx().def_span(def.did);
930 if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span)
932 p!(write("{}", snip))
943 ty::ConstKind::Infer(..) => print_underscore!(),
944 ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)),
945 ty::ConstKind::Value(value) => {
946 return self.pretty_print_const_value(value, ct.ty, print_ty);
949 ty::ConstKind::Bound(debruijn, bound_var) => {
950 self.pretty_print_bound_var(debruijn, bound_var)?
952 ty::ConstKind::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
953 ty::ConstKind::Error(_) => p!("[const error]"),
958 fn pretty_print_const_scalar(
963 ) -> Result<Self::Const, Self::Error> {
965 Scalar::Ptr(ptr) => self.pretty_print_const_scalar_ptr(ptr, ty, print_ty),
966 Scalar::Int(int) => self.pretty_print_const_scalar_int(int, ty, print_ty),
970 fn pretty_print_const_scalar_ptr(
975 ) -> Result<Self::Const, Self::Error> {
976 define_scoped_cx!(self);
979 // Byte strings (&[u8; N])
985 ty::TyS { kind: ty::Uint(ty::UintTy::U8), .. },
987 val: ty::ConstKind::Value(ConstValue::Scalar(int)), ..
993 ) => match self.tcx().get_global_alloc(ptr.alloc_id) {
994 Some(GlobalAlloc::Memory(alloc)) => {
995 let bytes = int.assert_bits(self.tcx().data_layout.pointer_size);
996 let size = Size::from_bytes(bytes);
997 if let Ok(byte_str) = alloc.get_bytes(&self.tcx(), ptr, size) {
998 p!(pretty_print_byte_str(byte_str))
1000 p!("<too short allocation>")
1003 // FIXME: for statics and functions, we could in principle print more detail.
1004 Some(GlobalAlloc::Static(def_id)) => p!(write("<static({:?})>", def_id)),
1005 Some(GlobalAlloc::Function(_)) => p!("<function>"),
1006 None => p!("<dangling pointer>"),
1009 // FIXME: We should probably have a helper method to share code with the "Byte strings"
1010 // printing above (which also has to handle pointers to all sorts of things).
1011 match self.tcx().get_global_alloc(ptr.alloc_id) {
1012 Some(GlobalAlloc::Function(instance)) => {
1013 self = self.typed_value(
1014 |this| this.print_value_path(instance.def_id(), instance.substs),
1015 |this| this.print_type(ty),
1019 _ => self = self.pretty_print_const_pointer(ptr, ty, print_ty)?,
1022 // Any pointer values not covered by a branch above
1024 self = self.pretty_print_const_pointer(ptr, ty, print_ty)?;
1030 fn pretty_print_const_scalar_int(
1035 ) -> Result<Self::Const, Self::Error> {
1036 define_scoped_cx!(self);
1040 ty::Bool if int == ScalarInt::FALSE => p!("false"),
1041 ty::Bool if int == ScalarInt::TRUE => p!("true"),
1043 ty::Float(ty::FloatTy::F32) => {
1044 p!(write("{}f32", Single::try_from(int).unwrap()))
1046 ty::Float(ty::FloatTy::F64) => {
1047 p!(write("{}f64", Double::try_from(int).unwrap()))
1050 ty::Uint(_) | ty::Int(_) => {
1052 ConstInt::new(int, matches!(ty.kind(), ty::Int(_)), ty.is_ptr_sized_integral());
1053 if print_ty { p!(write("{:#?}", int)) } else { p!(write("{:?}", int)) }
1056 ty::Char if char::try_from(int).is_ok() => {
1057 p!(write("{:?}", char::try_from(int).unwrap()))
1060 ty::RawPtr(_) | ty::FnPtr(_) => {
1061 let data = int.assert_bits(self.tcx().data_layout.pointer_size);
1062 self = self.typed_value(
1064 write!(this, "0x{:x}", data)?;
1067 |this| this.print_type(ty),
1071 // For function type zsts just printing the path is enough
1072 ty::FnDef(d, s) if int == ScalarInt::ZST => {
1073 p!(print_value_path(*d, s))
1075 // Nontrivial types with scalar bit representation
1077 let print = |mut this: Self| {
1078 if int.size() == Size::ZERO {
1079 write!(this, "transmute(())")?;
1081 write!(this, "transmute(0x{:x})", int)?;
1085 self = if print_ty {
1086 self.typed_value(print, |this| this.print_type(ty), ": ")?
1095 /// This is overridden for MIR printing because we only want to hide alloc ids from users, not
1096 /// from MIR where it is actually useful.
1097 fn pretty_print_const_pointer(
1102 ) -> Result<Self::Const, Self::Error> {
1106 this.write_str("&_")?;
1109 |this| this.print_type(ty),
1113 self.write_str("&_")?;
1118 fn pretty_print_byte_str(mut self, byte_str: &'tcx [u8]) -> Result<Self::Const, Self::Error> {
1119 define_scoped_cx!(self);
1121 for &c in byte_str {
1122 for e in std::ascii::escape_default(c) {
1123 self.write_char(e as char)?;
1130 fn pretty_print_const_value(
1132 ct: ConstValue<'tcx>,
1135 ) -> Result<Self::Const, Self::Error> {
1136 define_scoped_cx!(self);
1138 if self.tcx().sess.verbose() {
1139 p!(write("ConstValue({:?}: ", ct), print(ty), ")");
1143 let u8_type = self.tcx().types.u8;
1145 match (ct, ty.kind()) {
1146 // Byte/string slices, printed as (byte) string literals.
1148 ConstValue::Slice { data, start, end },
1149 ty::Ref(_, ty::TyS { kind: ty::Slice(t), .. }, _),
1150 ) if *t == u8_type => {
1151 // The `inspect` here is okay since we checked the bounds, and there are
1152 // no relocations (we have an active slice reference here). We don't use
1153 // this result to affect interpreter execution.
1154 let byte_str = data.inspect_with_uninit_and_ptr_outside_interpreter(start..end);
1155 self.pretty_print_byte_str(byte_str)
1158 ConstValue::Slice { data, start, end },
1159 ty::Ref(_, ty::TyS { kind: ty::Str, .. }, _),
1161 // The `inspect` here is okay since we checked the bounds, and there are no
1162 // relocations (we have an active `str` reference here). We don't use this
1163 // result to affect interpreter execution.
1164 let slice = data.inspect_with_uninit_and_ptr_outside_interpreter(start..end);
1165 let s = std::str::from_utf8(slice).expect("non utf8 str from miri");
1166 p!(write("{:?}", s));
1169 (ConstValue::ByRef { alloc, offset }, ty::Array(t, n)) if *t == u8_type => {
1170 let n = n.val.try_to_bits(self.tcx().data_layout.pointer_size).unwrap();
1171 // cast is ok because we already checked for pointer size (32 or 64 bit) above
1172 let n = Size::from_bytes(n);
1173 let ptr = Pointer::new(AllocId(0), offset);
1175 let byte_str = alloc.get_bytes(&self.tcx(), ptr, n).unwrap();
1177 p!(pretty_print_byte_str(byte_str));
1181 // Aggregates, printed as array/tuple/struct/variant construction syntax.
1183 // NB: the `has_param_types_or_consts` check ensures that we can use
1184 // the `destructure_const` query with an empty `ty::ParamEnv` without
1185 // introducing ICEs (e.g. via `layout_of`) from missing bounds.
1186 // E.g. `transmute([0usize; 2]): (u8, *mut T)` needs to know `T: Sized`
1187 // to be able to destructure the tuple into `(0u8, *mut T)
1189 // FIXME(eddyb) for `--emit=mir`/`-Z dump-mir`, we should provide the
1190 // correct `ty::ParamEnv` to allow printing *all* constant values.
1191 (_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) if !ty.has_param_types_or_consts() => {
1192 let contents = self.tcx().destructure_const(
1193 ty::ParamEnv::reveal_all()
1194 .and(self.tcx().mk_const(ty::Const { val: ty::ConstKind::Value(ct), ty })),
1196 let fields = contents.fields.iter().copied();
1200 p!("[", comma_sep(fields), "]");
1203 p!("(", comma_sep(fields));
1204 if contents.fields.len() == 1 {
1209 ty::Adt(def, substs) if def.variants.is_empty() => {
1210 p!(print_value_path(def.did, substs));
1212 ty::Adt(def, substs) => {
1214 contents.variant.expect("destructed const of adt without variant id");
1215 let variant_def = &def.variants[variant_id];
1216 p!(print_value_path(variant_def.def_id, substs));
1218 match variant_def.ctor_kind {
1219 CtorKind::Const => {}
1221 p!("(", comma_sep(fields), ")");
1223 CtorKind::Fictive => {
1225 let mut first = true;
1226 for (field_def, field) in variant_def.fields.iter().zip(fields) {
1230 p!(write("{}: ", field_def.ident), print(field));
1237 _ => unreachable!(),
1243 (ConstValue::Scalar(scalar), _) => self.pretty_print_const_scalar(scalar, ty, print_ty),
1245 // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
1246 // their fields instead of just dumping the memory.
1249 p!(write("{:?}", ct));
1251 p!(": ", print(ty));
1259 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
1260 pub struct FmtPrinter<'a, 'tcx, F>(Box<FmtPrinterData<'a, 'tcx, F>>);
1262 pub struct FmtPrinterData<'a, 'tcx, F> {
1268 pub print_alloc_ids: bool,
1270 used_region_names: FxHashSet<Symbol>,
1271 region_index: usize,
1272 binder_depth: usize,
1273 printed_type_count: usize,
1275 pub region_highlight_mode: RegionHighlightMode,
1277 pub name_resolver: Option<Box<&'a dyn Fn(ty::TyVid) -> Option<String>>>,
1280 impl<F> Deref for FmtPrinter<'a, 'tcx, F> {
1281 type Target = FmtPrinterData<'a, 'tcx, F>;
1282 fn deref(&self) -> &Self::Target {
1287 impl<F> DerefMut for FmtPrinter<'_, '_, F> {
1288 fn deref_mut(&mut self) -> &mut Self::Target {
1293 impl<F> FmtPrinter<'a, 'tcx, F> {
1294 pub fn new(tcx: TyCtxt<'tcx>, fmt: F, ns: Namespace) -> Self {
1295 FmtPrinter(Box::new(FmtPrinterData {
1299 in_value: ns == Namespace::ValueNS,
1300 print_alloc_ids: false,
1301 used_region_names: Default::default(),
1304 printed_type_count: 0,
1305 region_highlight_mode: RegionHighlightMode::default(),
1306 name_resolver: None,
1311 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1312 // (but also some things just print a `DefId` generally so maybe we need this?)
1313 fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
1314 match tcx.def_key(def_id).disambiguated_data.data {
1315 DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::ImplTrait => {
1319 DefPathData::ValueNs(..)
1320 | DefPathData::AnonConst
1321 | DefPathData::ClosureExpr
1322 | DefPathData::Ctor => Namespace::ValueNS,
1324 DefPathData::MacroNs(..) => Namespace::MacroNS,
1326 _ => Namespace::TypeNS,
1331 /// Returns a string identifying this `DefId`. This string is
1332 /// suitable for user output.
1333 pub fn def_path_str(self, def_id: DefId) -> String {
1334 self.def_path_str_with_substs(def_id, &[])
1337 pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1338 let ns = guess_def_namespace(self, def_id);
1339 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1340 let mut s = String::new();
1341 let _ = FmtPrinter::new(self, &mut s, ns).print_def_path(def_id, substs);
1346 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, F> {
1347 fn write_str(&mut self, s: &str) -> fmt::Result {
1348 self.fmt.write_str(s)
1352 impl<F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
1353 type Error = fmt::Error;
1358 type DynExistential = Self;
1361 fn tcx(&'a self) -> TyCtxt<'tcx> {
1368 substs: &'tcx [GenericArg<'tcx>],
1369 ) -> Result<Self::Path, Self::Error> {
1370 define_scoped_cx!(self);
1372 if substs.is_empty() {
1373 match self.try_print_trimmed_def_path(def_id)? {
1374 (cx, true) => return Ok(cx),
1375 (cx, false) => self = cx,
1378 match self.try_print_visible_def_path(def_id)? {
1379 (cx, true) => return Ok(cx),
1380 (cx, false) => self = cx,
1384 let key = self.tcx.def_key(def_id);
1385 if let DefPathData::Impl = key.disambiguated_data.data {
1386 // Always use types for non-local impls, where types are always
1387 // available, and filename/line-number is mostly uninteresting.
1388 let use_types = !def_id.is_local() || {
1389 // Otherwise, use filename/line-number if forced.
1390 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1395 // If no type info is available, fall back to
1396 // pretty printing some span information. This should
1397 // only occur very early in the compiler pipeline.
1398 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1399 let span = self.tcx.def_span(def_id);
1401 self = self.print_def_path(parent_def_id, &[])?;
1403 // HACK(eddyb) copy of `path_append` to avoid
1404 // constructing a `DisambiguatedDefPathData`.
1405 if !self.empty_path {
1406 write!(self, "::")?;
1408 write!(self, "<impl at {}>", self.tcx.sess.source_map().span_to_string(span))?;
1409 self.empty_path = false;
1415 self.default_print_def_path(def_id, substs)
1418 fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
1419 self.pretty_print_region(region)
1422 fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1423 if self.tcx.sess.type_length_limit().value_within_limit(self.printed_type_count) {
1424 self.printed_type_count += 1;
1425 self.pretty_print_type(ty)
1427 write!(self, "...")?;
1432 fn print_dyn_existential(
1434 predicates: &'tcx ty::List<ty::Binder<ty::ExistentialPredicate<'tcx>>>,
1435 ) -> Result<Self::DynExistential, Self::Error> {
1436 self.pretty_print_dyn_existential(predicates)
1439 fn print_const(self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1440 self.pretty_print_const(ct, true)
1443 fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1444 self.empty_path = true;
1445 if cnum == LOCAL_CRATE {
1446 if self.tcx.sess.rust_2018() {
1447 // We add the `crate::` keyword on Rust 2018, only when desired.
1448 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1449 write!(self, "{}", kw::Crate)?;
1450 self.empty_path = false;
1454 write!(self, "{}", self.tcx.crate_name(cnum))?;
1455 self.empty_path = false;
1463 trait_ref: Option<ty::TraitRef<'tcx>>,
1464 ) -> Result<Self::Path, Self::Error> {
1465 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1466 self.empty_path = false;
1470 fn path_append_impl(
1472 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1473 _disambiguated_data: &DisambiguatedDefPathData,
1475 trait_ref: Option<ty::TraitRef<'tcx>>,
1476 ) -> Result<Self::Path, Self::Error> {
1477 self = self.pretty_path_append_impl(
1479 cx = print_prefix(cx)?;
1489 self.empty_path = false;
1495 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1496 disambiguated_data: &DisambiguatedDefPathData,
1497 ) -> Result<Self::Path, Self::Error> {
1498 self = print_prefix(self)?;
1500 // Skip `::{{constructor}}` on tuple/unit structs.
1501 if let DefPathData::Ctor = disambiguated_data.data {
1505 // FIXME(eddyb) `name` should never be empty, but it
1506 // currently is for `extern { ... }` "foreign modules".
1507 let name = disambiguated_data.data.name();
1508 if name != DefPathDataName::Named(kw::Empty) {
1509 if !self.empty_path {
1510 write!(self, "::")?;
1513 if let DefPathDataName::Named(name) = name {
1514 if Ident::with_dummy_span(name).is_raw_guess() {
1515 write!(self, "r#")?;
1519 let verbose = self.tcx.sess.verbose();
1520 disambiguated_data.fmt_maybe_verbose(&mut self, verbose)?;
1522 self.empty_path = false;
1528 fn path_generic_args(
1530 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1531 args: &[GenericArg<'tcx>],
1532 ) -> Result<Self::Path, Self::Error> {
1533 self = print_prefix(self)?;
1535 // Don't print `'_` if there's no unerased regions.
1536 let print_regions = args.iter().any(|arg| match arg.unpack() {
1537 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
1540 let args = args.iter().cloned().filter(|arg| match arg.unpack() {
1541 GenericArgKind::Lifetime(_) => print_regions,
1545 if args.clone().next().is_some() {
1547 write!(self, "::")?;
1549 self.generic_delimiters(|cx| cx.comma_sep(args))
1556 impl<F: fmt::Write> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx, F> {
1557 fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> {
1558 self.0.name_resolver.as_ref().and_then(|func| func(id))
1561 fn print_value_path(
1564 substs: &'tcx [GenericArg<'tcx>],
1565 ) -> Result<Self::Path, Self::Error> {
1566 let was_in_value = std::mem::replace(&mut self.in_value, true);
1567 self = self.print_def_path(def_id, substs)?;
1568 self.in_value = was_in_value;
1573 fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
1575 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1577 self.pretty_in_binder(value)
1580 fn wrap_binder<T, C: Fn(&T, Self) -> Result<Self, Self::Error>>(
1582 value: &ty::Binder<T>,
1584 ) -> Result<Self, Self::Error>
1586 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1588 self.pretty_wrap_binder(value, f)
1593 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1594 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
1596 ) -> Result<Self::Const, Self::Error> {
1597 self.write_str("{")?;
1599 self.write_str(conversion)?;
1600 let was_in_value = std::mem::replace(&mut self.in_value, false);
1602 self.in_value = was_in_value;
1603 self.write_str("}")?;
1607 fn generic_delimiters(
1609 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1610 ) -> Result<Self, Self::Error> {
1613 let was_in_value = std::mem::replace(&mut self.in_value, false);
1614 let mut inner = f(self)?;
1615 inner.in_value = was_in_value;
1617 write!(inner, ">")?;
1621 fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool {
1622 let highlight = self.region_highlight_mode;
1623 if highlight.region_highlighted(region).is_some() {
1627 if self.tcx.sess.verbose() {
1631 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1634 ty::ReEarlyBound(ref data) => {
1635 data.name != kw::Empty && data.name != kw::UnderscoreLifetime
1638 ty::ReLateBound(_, ty::BoundRegion { kind: br })
1639 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1640 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1641 if let ty::BrNamed(_, name) = br {
1642 if name != kw::Empty && name != kw::UnderscoreLifetime {
1647 if let Some((region, _)) = highlight.highlight_bound_region {
1656 ty::ReVar(_) if identify_regions => true,
1658 ty::ReVar(_) | ty::ReErased => false,
1660 ty::ReStatic | ty::ReEmpty(_) => true,
1664 fn pretty_print_const_pointer(
1669 ) -> Result<Self::Const, Self::Error> {
1670 let print = |mut this: Self| {
1671 define_scoped_cx!(this);
1672 if this.print_alloc_ids {
1673 p!(write("{:?}", p));
1680 self.typed_value(print, |this| this.print_type(ty), ": ")
1687 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1688 impl<F: fmt::Write> FmtPrinter<'_, '_, F> {
1689 pub fn pretty_print_region(mut self, region: ty::Region<'_>) -> Result<Self, fmt::Error> {
1690 define_scoped_cx!(self);
1692 // Watch out for region highlights.
1693 let highlight = self.region_highlight_mode;
1694 if let Some(n) = highlight.region_highlighted(region) {
1695 p!(write("'{}", n));
1699 if self.tcx.sess.verbose() {
1700 p!(write("{:?}", region));
1704 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1706 // These printouts are concise. They do not contain all the information
1707 // the user might want to diagnose an error, but there is basically no way
1708 // to fit that into a short string. Hence the recommendation to use
1709 // `explain_region()` or `note_and_explain_region()`.
1711 ty::ReEarlyBound(ref data) => {
1712 if data.name != kw::Empty {
1713 p!(write("{}", data.name));
1717 ty::ReLateBound(_, ty::BoundRegion { kind: br })
1718 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1719 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1720 if let ty::BrNamed(_, name) = br {
1721 if name != kw::Empty && name != kw::UnderscoreLifetime {
1722 p!(write("{}", name));
1727 if let Some((region, counter)) = highlight.highlight_bound_region {
1729 p!(write("'{}", counter));
1734 ty::ReVar(region_vid) if identify_regions => {
1735 p!(write("{:?}", region_vid));
1744 ty::ReEmpty(ty::UniverseIndex::ROOT) => {
1748 ty::ReEmpty(ui) => {
1749 p!(write("'<empty:{:?}>", ui));
1760 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1761 // `region_index` and `used_region_names`.
1762 impl<F: fmt::Write> FmtPrinter<'_, 'tcx, F> {
1763 pub fn name_all_regions<T>(
1765 value: &ty::Binder<T>,
1766 ) -> Result<(Self, (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)), fmt::Error>
1768 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1770 fn name_by_region_index(index: usize) -> Symbol {
1772 0 => Symbol::intern("'r"),
1773 1 => Symbol::intern("'s"),
1774 i => Symbol::intern(&format!("'t{}", i - 2)),
1778 // Replace any anonymous late-bound regions with named
1779 // variants, using new unique identifiers, so that we can
1780 // clearly differentiate between named and unnamed regions in
1781 // the output. We'll probably want to tweak this over time to
1782 // decide just how much information to give.
1783 if self.binder_depth == 0 {
1784 self.prepare_late_bound_region_info(value);
1787 let mut empty = true;
1788 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1801 define_scoped_cx!(self);
1803 let mut region_index = self.region_index;
1804 let new_value = self.tcx.replace_late_bound_regions(value.clone(), |br| {
1805 let _ = start_or_continue(&mut self, "for<", ", ");
1806 let kind = match br.kind {
1807 ty::BrNamed(_, name) => {
1808 let _ = write!(self, "{}", name);
1811 ty::BrAnon(_) | ty::BrEnv => {
1813 let name = name_by_region_index(region_index);
1815 if !self.used_region_names.contains(&name) {
1819 let _ = write!(self, "{}", name);
1820 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1823 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BoundRegion { kind }))
1825 start_or_continue(&mut self, "", "> ")?;
1827 self.binder_depth += 1;
1828 self.region_index = region_index;
1829 Ok((self, new_value))
1832 pub fn pretty_in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, fmt::Error>
1834 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1836 let old_region_index = self.region_index;
1837 let (new, new_value) = self.name_all_regions(value)?;
1838 let mut inner = new_value.0.print(new)?;
1839 inner.region_index = old_region_index;
1840 inner.binder_depth -= 1;
1844 pub fn pretty_wrap_binder<T, C: Fn(&T, Self) -> Result<Self, fmt::Error>>(
1846 value: &ty::Binder<T>,
1848 ) -> Result<Self, fmt::Error>
1850 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1852 let old_region_index = self.region_index;
1853 let (new, new_value) = self.name_all_regions(value)?;
1854 let mut inner = f(&new_value.0, new)?;
1855 inner.region_index = old_region_index;
1856 inner.binder_depth -= 1;
1860 fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
1862 T: TypeFoldable<'tcx>,
1864 struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet<Symbol>);
1865 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> {
1866 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1867 if let ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name) }) = *r {
1868 self.0.insert(name);
1870 r.super_visit_with(self)
1874 self.used_region_names.clear();
1875 let mut collector = LateBoundRegionNameCollector(&mut self.used_region_names);
1876 value.visit_with(&mut collector);
1877 self.region_index = 0;
1881 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<T>
1883 T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
1886 type Error = P::Error;
1887 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
1892 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
1894 T: Print<'tcx, P, Output = P, Error = P::Error>,
1895 U: Print<'tcx, P, Output = P, Error = P::Error>,
1898 type Error = P::Error;
1899 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
1900 define_scoped_cx!(cx);
1901 p!(print(self.0), ": ", print(self.1));
1906 macro_rules! forward_display_to_print {
1908 $(impl fmt::Display for $ty {
1909 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1910 ty::tls::with(|tcx| {
1912 .expect("could not lift for printing")
1913 .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1921 macro_rules! define_print_and_forward_display {
1922 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
1923 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
1925 type Error = fmt::Error;
1926 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
1927 #[allow(unused_mut)]
1929 define_scoped_cx!($cx);
1931 #[allow(unreachable_code)]
1936 forward_display_to_print!($($ty),+);
1940 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
1941 impl fmt::Display for ty::RegionKind {
1942 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1943 ty::tls::with(|tcx| {
1944 self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1950 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
1951 /// the trait path. That is, it will print `Trait<U>` instead of
1952 /// `<T as Trait<U>>`.
1953 #[derive(Copy, Clone, TypeFoldable, Lift)]
1954 pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
1956 impl fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
1957 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1958 fmt::Display::fmt(self, f)
1962 impl ty::TraitRef<'tcx> {
1963 pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
1964 TraitRefPrintOnlyTraitPath(self)
1968 impl ty::Binder<ty::TraitRef<'tcx>> {
1969 pub fn print_only_trait_path(self) -> ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>> {
1970 self.map_bound(|tr| tr.print_only_trait_path())
1974 forward_display_to_print! {
1976 &'tcx ty::List<ty::Binder<ty::ExistentialPredicate<'tcx>>>,
1977 &'tcx ty::Const<'tcx>,
1979 // HACK(eddyb) these are exhaustive instead of generic,
1980 // because `for<'tcx>` isn't possible yet.
1981 ty::Binder<ty::ExistentialPredicate<'tcx>>,
1982 ty::Binder<ty::TraitRef<'tcx>>,
1983 ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>>,
1984 ty::Binder<ty::FnSig<'tcx>>,
1985 ty::Binder<ty::TraitPredicate<'tcx>>,
1986 ty::Binder<ty::SubtypePredicate<'tcx>>,
1987 ty::Binder<ty::ProjectionPredicate<'tcx>>,
1988 ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1989 ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
1991 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1992 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1995 define_print_and_forward_display! {
1998 &'tcx ty::List<Ty<'tcx>> {
1999 p!("{{", comma_sep(self.iter()), "}}")
2002 ty::TypeAndMut<'tcx> {
2003 p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
2006 ty::ExistentialTraitRef<'tcx> {
2007 // Use a type that can't appear in defaults of type parameters.
2008 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
2009 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
2010 p!(print(trait_ref.print_only_trait_path()))
2013 ty::ExistentialProjection<'tcx> {
2014 let name = cx.tcx().associated_item(self.item_def_id).ident;
2015 p!(write("{} = ", name), print(self.ty))
2018 ty::ExistentialPredicate<'tcx> {
2020 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
2021 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
2022 ty::ExistentialPredicate::AutoTrait(def_id) => {
2023 p!(print_def_path(def_id, &[]));
2029 p!(write("{}", self.unsafety.prefix_str()));
2031 if self.abi != Abi::Rust {
2032 p!(write("extern {} ", self.abi));
2035 p!("fn", pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
2038 ty::TraitRef<'tcx> {
2039 p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
2042 TraitRefPrintOnlyTraitPath<'tcx> {
2043 p!(print_def_path(self.0.def_id, self.0.substs));
2047 p!(write("{}", self.name))
2051 p!(write("{}", self.name))
2054 ty::SubtypePredicate<'tcx> {
2055 p!(print(self.a), " <: ", print(self.b))
2058 ty::TraitPredicate<'tcx> {
2059 p!(print(self.trait_ref.self_ty()), ": ",
2060 print(self.trait_ref.print_only_trait_path()))
2063 ty::ProjectionPredicate<'tcx> {
2064 p!(print(self.projection_ty), " == ", print(self.ty))
2067 ty::ProjectionTy<'tcx> {
2068 p!(print_def_path(self.item_def_id, self.substs));
2073 ty::ClosureKind::Fn => p!("Fn"),
2074 ty::ClosureKind::FnMut => p!("FnMut"),
2075 ty::ClosureKind::FnOnce => p!("FnOnce"),
2079 ty::Predicate<'tcx> {
2080 let binder = self.kind();
2084 ty::PredicateKind<'tcx> {
2086 ty::PredicateKind::Trait(ref data, constness) => {
2087 if let hir::Constness::Const = constness {
2092 ty::PredicateKind::Subtype(predicate) => p!(print(predicate)),
2093 ty::PredicateKind::RegionOutlives(predicate) => p!(print(predicate)),
2094 ty::PredicateKind::TypeOutlives(predicate) => p!(print(predicate)),
2095 ty::PredicateKind::Projection(predicate) => p!(print(predicate)),
2096 ty::PredicateKind::WellFormed(arg) => p!(print(arg), " well-formed"),
2097 ty::PredicateKind::ObjectSafe(trait_def_id) => {
2098 p!("the trait `", print_def_path(trait_def_id, &[]), "` is object-safe")
2100 ty::PredicateKind::ClosureKind(closure_def_id, _closure_substs, kind) => {
2102 print_value_path(closure_def_id, &[]),
2103 write("` implements the trait `{}`", kind))
2105 ty::PredicateKind::ConstEvaluatable(def, substs) => {
2106 p!("the constant `", print_value_path(def.did, substs), "` can be evaluated")
2108 ty::PredicateKind::ConstEquate(c1, c2) => {
2109 p!("the constant `", print(c1), "` equals `", print(c2), "`")
2111 ty::PredicateKind::TypeWellFormedFromEnv(ty) => {
2112 p!("the type `", print(ty), "` is found in the environment")
2118 match self.unpack() {
2119 GenericArgKind::Lifetime(lt) => p!(print(lt)),
2120 GenericArgKind::Type(ty) => p!(print(ty)),
2121 GenericArgKind::Const(ct) => p!(print(ct)),
2126 fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
2127 // Iterate all local crate items no matter where they are defined.
2128 let hir = tcx.hir();
2129 for item in hir.krate().items.values() {
2130 if item.ident.name.as_str().is_empty() || matches!(item.kind, ItemKind::Use(_, _)) {
2134 let def_id = item.def_id.to_def_id();
2135 let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
2136 collect_fn(&item.ident, ns, def_id);
2139 // Now take care of extern crate items.
2140 let queue = &mut Vec::new();
2141 let mut seen_defs: DefIdSet = Default::default();
2143 for &cnum in tcx.crates().iter() {
2144 let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
2146 // Ignore crates that are not direct dependencies.
2147 match tcx.extern_crate(def_id) {
2149 Some(extern_crate) => {
2150 if !extern_crate.is_direct() {
2159 // Iterate external crate defs but be mindful about visibility
2160 while let Some(def) = queue.pop() {
2161 for child in tcx.item_children(def).iter() {
2162 if child.vis != ty::Visibility::Public {
2167 def::Res::Def(DefKind::AssocTy, _) => {}
2168 def::Res::Def(DefKind::TyAlias, _) => {}
2169 def::Res::Def(defkind, def_id) => {
2170 if let Some(ns) = defkind.ns() {
2171 collect_fn(&child.ident, ns, def_id);
2174 if seen_defs.insert(def_id) {
2184 /// The purpose of this function is to collect public symbols names that are unique across all
2185 /// crates in the build. Later, when printing about types we can use those names instead of the
2186 /// full exported path to them.
2188 /// So essentially, if a symbol name can only be imported from one place for a type, and as
2189 /// long as it was not glob-imported anywhere in the current crate, we can trim its printed
2190 /// path and print only the name.
2192 /// This has wide implications on error messages with types, for example, shortening
2193 /// `std::vec::Vec` to just `Vec`, as long as there is no other `Vec` importable anywhere.
2195 /// The implementation uses similar import discovery logic to that of 'use' suggestions.
2196 fn trimmed_def_paths(tcx: TyCtxt<'_>, crate_num: CrateNum) -> FxHashMap<DefId, Symbol> {
2197 assert_eq!(crate_num, LOCAL_CRATE);
2199 let mut map = FxHashMap::default();
2201 if let TrimmedDefPaths::GoodPath = tcx.sess.opts.trimmed_def_paths {
2202 // For good paths causing this bug, the `rustc_middle::ty::print::with_no_trimmed_paths`
2203 // wrapper can be used to suppress this query, in exchange for full paths being formatted.
2204 tcx.sess.delay_good_path_bug("trimmed_def_paths constructed");
2207 let unique_symbols_rev: &mut FxHashMap<(Namespace, Symbol), Option<DefId>> =
2208 &mut FxHashMap::default();
2210 for symbol_set in tcx.glob_map.values() {
2211 for symbol in symbol_set {
2212 unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
2213 unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
2214 unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
2218 for_each_def(tcx, |ident, ns, def_id| {
2219 use std::collections::hash_map::Entry::{Occupied, Vacant};
2221 match unique_symbols_rev.entry((ns, ident.name)) {
2222 Occupied(mut v) => match v.get() {
2225 if *existing != def_id {
2231 v.insert(Some(def_id));
2236 for ((_, symbol), opt_def_id) in unique_symbols_rev.drain() {
2237 if let Some(def_id) = opt_def_id {
2238 map.insert(def_id, symbol);
2245 pub fn provide(providers: &mut ty::query::Providers) {
2246 *providers = ty::query::Providers { trimmed_def_paths, ..*providers };