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};
7 use rustc_data_structures::fx::FxHashMap;
9 use rustc_hir::def::{self, CtorKind, DefKind, Namespace};
10 use rustc_hir::def_id::{CrateNum, 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 _};
23 use std::ops::{ControlFlow, Deref, DerefMut};
25 // `pretty` is a separate module only for organization.
30 write!(scoped_cx!(), $lit)?
32 (@write($($data:expr),+)) => {
33 write!(scoped_cx!(), $($data),+)?
35 (@print($x:expr)) => {
36 scoped_cx!() = $x.print(scoped_cx!())?
38 (@$method:ident($($arg:expr),*)) => {
39 scoped_cx!() = scoped_cx!().$method($($arg),*)?
41 ($($elem:tt $(($($args:tt)*))?),+) => {{
42 $(p!(@ $elem $(($($args)*))?);)+
45 macro_rules! define_scoped_cx {
47 #[allow(unused_macros)]
48 macro_rules! scoped_cx {
57 static FORCE_IMPL_FILENAME_LINE: Cell<bool> = Cell::new(false);
58 static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = Cell::new(false);
59 static NO_TRIMMED_PATH: Cell<bool> = Cell::new(false);
60 static NO_QUERIES: Cell<bool> = Cell::new(false);
63 /// Avoids running any queries during any prints that occur
64 /// during the closure. This may alter the appearance of some
65 /// types (e.g. forcing verbose printing for opaque types).
66 /// This method is used during some queries (e.g. `explicit_item_bounds`
67 /// for opaque types), to ensure that any debug printing that
68 /// occurs during the query computation does not end up recursively
69 /// calling the same query.
70 pub fn with_no_queries<F: FnOnce() -> R, R>(f: F) -> R {
71 NO_QUERIES.with(|no_queries| {
72 let old = no_queries.replace(true);
79 /// Force us to name impls with just the filename/line number. We
80 /// normally try to use types. But at some points, notably while printing
81 /// cycle errors, this can result in extra or suboptimal error output,
82 /// so this variable disables that check.
83 pub fn with_forced_impl_filename_line<F: FnOnce() -> R, R>(f: F) -> R {
84 FORCE_IMPL_FILENAME_LINE.with(|force| {
85 let old = force.replace(true);
92 /// Adds the `crate::` prefix to paths where appropriate.
93 pub fn with_crate_prefix<F: FnOnce() -> R, R>(f: F) -> R {
94 SHOULD_PREFIX_WITH_CRATE.with(|flag| {
95 let old = flag.replace(true);
102 /// Prevent path trimming if it is turned on. Path trimming affects `Display` impl
103 /// of various rustc types, for example `std::vec::Vec` would be trimmed to `Vec`,
104 /// if no other `Vec` is found.
105 pub fn with_no_trimmed_paths<F: FnOnce() -> R, R>(f: F) -> R {
106 NO_TRIMMED_PATH.with(|flag| {
107 let old = flag.replace(true);
114 /// The "region highlights" are used to control region printing during
115 /// specific error messages. When a "region highlight" is enabled, it
116 /// gives an alternate way to print specific regions. For now, we
117 /// always print those regions using a number, so something like "`'0`".
119 /// Regions not selected by the region highlight mode are presently
121 #[derive(Copy, Clone, Default)]
122 pub struct RegionHighlightMode {
123 /// If enabled, when we see the selected region, use "`'N`"
124 /// instead of the ordinary behavior.
125 highlight_regions: [Option<(ty::RegionKind, usize)>; 3],
127 /// If enabled, when printing a "free region" that originated from
128 /// the given `ty::BoundRegionKind`, print it as "`'1`". Free regions that would ordinarily
129 /// have names print as normal.
131 /// This is used when you have a signature like `fn foo(x: &u32,
132 /// y: &'a u32)` and we want to give a name to the region of the
134 highlight_bound_region: Option<(ty::BoundRegionKind, usize)>,
137 impl RegionHighlightMode {
138 /// If `region` and `number` are both `Some`, invokes
139 /// `highlighting_region`.
140 pub fn maybe_highlighting_region(
142 region: Option<ty::Region<'_>>,
143 number: Option<usize>,
145 if let Some(k) = region {
146 if let Some(n) = number {
147 self.highlighting_region(k, n);
152 /// Highlights the region inference variable `vid` as `'N`.
153 pub fn highlighting_region(&mut self, region: ty::Region<'_>, number: usize) {
154 let num_slots = self.highlight_regions.len();
155 let first_avail_slot =
156 self.highlight_regions.iter_mut().find(|s| s.is_none()).unwrap_or_else(|| {
157 bug!("can only highlight {} placeholders at a time", num_slots,)
159 *first_avail_slot = Some((*region, number));
162 /// Convenience wrapper for `highlighting_region`.
163 pub fn highlighting_region_vid(&mut self, vid: ty::RegionVid, number: usize) {
164 self.highlighting_region(&ty::ReVar(vid), number)
167 /// Returns `Some(n)` with the number to use for the given region, if any.
168 fn region_highlighted(&self, region: ty::Region<'_>) -> Option<usize> {
169 self.highlight_regions.iter().find_map(|h| match h {
170 Some((r, n)) if r == region => Some(*n),
175 /// Highlight the given bound region.
176 /// We can only highlight one bound region at a time. See
177 /// the field `highlight_bound_region` for more detailed notes.
178 pub fn highlighting_bound_region(&mut self, br: ty::BoundRegionKind, number: usize) {
179 assert!(self.highlight_bound_region.is_none());
180 self.highlight_bound_region = Some((br, number));
184 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
185 pub trait PrettyPrinter<'tcx>:
192 DynExistential = Self,
196 /// Like `print_def_path` but for value paths.
200 substs: &'tcx [GenericArg<'tcx>],
201 ) -> Result<Self::Path, Self::Error> {
202 self.print_def_path(def_id, substs)
205 fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
207 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
209 value.as_ref().skip_binder().print(self)
212 fn wrap_binder<T, F: Fn(&T, Self) -> Result<Self, fmt::Error>>(
214 value: &ty::Binder<T>,
216 ) -> Result<Self, Self::Error>
218 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
220 f(value.as_ref().skip_binder(), self)
223 /// Prints comma-separated elements.
224 fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
226 T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
228 if let Some(first) = elems.next() {
229 self = first.print(self)?;
231 self.write_str(", ")?;
232 self = elem.print(self)?;
238 /// Prints `{f: t}` or `{f as t}` depending on the `cast` argument
241 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
242 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
244 ) -> Result<Self::Const, Self::Error> {
245 self.write_str("{")?;
247 self.write_str(conversion)?;
249 self.write_str("}")?;
253 /// Prints `<...>` around what `f` prints.
254 fn generic_delimiters(
256 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
257 ) -> Result<Self, Self::Error>;
259 /// Returns `true` if the region should be printed in
260 /// optional positions, e.g., `&'a T` or `dyn Tr + 'b`.
261 /// This is typically the case for all non-`'_` regions.
262 fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool;
264 // Defaults (should not be overridden):
266 /// If possible, this returns a global path resolving to `def_id` that is visible
267 /// from at least one local module, and returns `true`. If the crate defining `def_id` is
268 /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
269 fn try_print_visible_def_path(self, def_id: DefId) -> Result<(Self, bool), Self::Error> {
270 let mut callers = Vec::new();
271 self.try_print_visible_def_path_recur(def_id, &mut callers)
274 /// Try to see if this path can be trimmed to a unique symbol name.
275 fn try_print_trimmed_def_path(
278 ) -> Result<(Self::Path, bool), Self::Error> {
279 if !self.tcx().sess.opts.debugging_opts.trim_diagnostic_paths
280 || matches!(self.tcx().sess.opts.trimmed_def_paths, TrimmedDefPaths::Never)
281 || NO_TRIMMED_PATH.with(|flag| flag.get())
282 || SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get())
284 return Ok((self, false));
287 match self.tcx().trimmed_def_paths(LOCAL_CRATE).get(&def_id) {
288 None => Ok((self, false)),
290 self.write_str(&symbol.as_str())?;
296 /// Does the work of `try_print_visible_def_path`, building the
297 /// full definition path recursively before attempting to
298 /// post-process it into the valid and visible version that
299 /// accounts for re-exports.
301 /// This method should only be called by itself or
302 /// `try_print_visible_def_path`.
304 /// `callers` is a chain of visible_parent's leading to `def_id`,
305 /// to support cycle detection during recursion.
306 fn try_print_visible_def_path_recur(
309 callers: &mut Vec<DefId>,
310 ) -> Result<(Self, bool), Self::Error> {
311 define_scoped_cx!(self);
313 debug!("try_print_visible_def_path: def_id={:?}", def_id);
315 // If `def_id` is a direct or injected extern crate, return the
316 // path to the crate followed by the path to the item within the crate.
317 if def_id.index == CRATE_DEF_INDEX {
318 let cnum = def_id.krate;
320 if cnum == LOCAL_CRATE {
321 return Ok((self.path_crate(cnum)?, true));
324 // In local mode, when we encounter a crate other than
325 // LOCAL_CRATE, execution proceeds in one of two ways:
327 // 1. For a direct dependency, where user added an
328 // `extern crate` manually, we put the `extern
329 // crate` as the parent. So you wind up with
330 // something relative to the current crate.
331 // 2. For an extern inferred from a path or an indirect crate,
332 // where there is no explicit `extern crate`, we just prepend
334 match self.tcx().extern_crate(def_id) {
335 Some(&ExternCrate { src, dependency_of, span, .. }) => match (src, dependency_of) {
336 (ExternCrateSource::Extern(def_id), LOCAL_CRATE) => {
337 debug!("try_print_visible_def_path: def_id={:?}", def_id);
339 if !span.is_dummy() {
340 self.print_def_path(def_id, &[])?
342 self.path_crate(cnum)?
347 (ExternCrateSource::Path, LOCAL_CRATE) => {
348 debug!("try_print_visible_def_path: def_id={:?}", def_id);
349 return Ok((self.path_crate(cnum)?, true));
354 return Ok((self.path_crate(cnum)?, true));
359 if def_id.is_local() {
360 return Ok((self, false));
363 let visible_parent_map = self.tcx().visible_parent_map(LOCAL_CRATE);
365 let mut cur_def_key = self.tcx().def_key(def_id);
366 debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
368 // For a constructor, we want the name of its parent rather than <unnamed>.
369 if let DefPathData::Ctor = cur_def_key.disambiguated_data.data {
374 .expect("`DefPathData::Ctor` / `VariantData` missing a parent"),
377 cur_def_key = self.tcx().def_key(parent);
380 let visible_parent = match visible_parent_map.get(&def_id).cloned() {
381 Some(parent) => parent,
382 None => return Ok((self, false)),
384 if callers.contains(&visible_parent) {
385 return Ok((self, false));
387 callers.push(visible_parent);
388 // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
389 // knowing ahead of time whether the entire path will succeed or not.
390 // To support printers that do not implement `PrettyPrinter`, a `Vec` or
391 // linked list on the stack would need to be built, before any printing.
392 match self.try_print_visible_def_path_recur(visible_parent, callers)? {
393 (cx, false) => return Ok((cx, false)),
394 (cx, true) => self = cx,
397 let actual_parent = self.tcx().parent(def_id);
399 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
400 visible_parent, actual_parent,
403 let mut data = cur_def_key.disambiguated_data.data;
405 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
406 data, visible_parent, actual_parent,
410 // In order to output a path that could actually be imported (valid and visible),
411 // we need to handle re-exports correctly.
413 // For example, take `std::os::unix::process::CommandExt`, this trait is actually
414 // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
416 // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is
417 // private so the "true" path to `CommandExt` isn't accessible.
419 // In this case, the `visible_parent_map` will look something like this:
421 // (child) -> (parent)
422 // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
423 // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
424 // `std::sys::unix::ext` -> `std::os`
426 // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
429 // When printing the path to `CommandExt` and looking at the `cur_def_key` that
430 // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
431 // to the parent - resulting in a mangled path like
432 // `std::os::ext::process::CommandExt`.
434 // Instead, we must detect that there was a re-export and instead print `unix`
435 // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
436 // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
437 // the visible parent (`std::os`). If these do not match, then we iterate over
438 // the children of the visible parent (as was done when computing
439 // `visible_parent_map`), looking for the specific child we currently have and then
440 // have access to the re-exported name.
441 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
444 .item_children(visible_parent)
446 .find(|child| child.res.opt_def_id() == Some(def_id))
447 .map(|child| child.ident.name);
448 if let Some(reexport) = reexport {
452 // Re-exported `extern crate` (#43189).
453 DefPathData::CrateRoot => {
454 data = DefPathData::TypeNs(self.tcx().original_crate_name(def_id.krate));
458 debug!("try_print_visible_def_path: data={:?}", data);
460 Ok((self.path_append(Ok, &DisambiguatedDefPathData { data, disambiguator: 0 })?, true))
463 fn pretty_path_qualified(
466 trait_ref: Option<ty::TraitRef<'tcx>>,
467 ) -> Result<Self::Path, Self::Error> {
468 if trait_ref.is_none() {
469 // Inherent impls. Try to print `Foo::bar` for an inherent
470 // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
471 // anything other than a simple path.
472 match self_ty.kind() {
481 return self_ty.print(self);
488 self.generic_delimiters(|mut cx| {
489 define_scoped_cx!(cx);
492 if let Some(trait_ref) = trait_ref {
493 p!(" as ", print(trait_ref.print_only_trait_path()));
499 fn pretty_path_append_impl(
501 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
503 trait_ref: Option<ty::TraitRef<'tcx>>,
504 ) -> Result<Self::Path, Self::Error> {
505 self = print_prefix(self)?;
507 self.generic_delimiters(|mut cx| {
508 define_scoped_cx!(cx);
511 if let Some(trait_ref) = trait_ref {
512 p!(print(trait_ref.print_only_trait_path()), " for ");
520 fn pretty_print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
521 define_scoped_cx!(self);
524 ty::Bool => p!("bool"),
525 ty::Char => p!("char"),
526 ty::Int(t) => p!(write("{}", t.name_str())),
527 ty::Uint(t) => p!(write("{}", t.name_str())),
528 ty::Float(t) => p!(write("{}", t.name_str())),
529 ty::RawPtr(ref tm) => {
533 hir::Mutability::Mut => "mut",
534 hir::Mutability::Not => "const",
539 ty::Ref(r, ty, mutbl) => {
541 if self.region_should_not_be_omitted(r) {
544 p!(print(ty::TypeAndMut { ty, mutbl }))
546 ty::Never => p!("!"),
547 ty::Tuple(ref tys) => {
548 p!("(", comma_sep(tys.iter()));
554 ty::FnDef(def_id, substs) => {
555 let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs);
556 p!(print(sig), " {{", print_value_path(def_id, substs), "}}");
558 ty::FnPtr(ref bare_fn) => p!(print(bare_fn)),
559 ty::Infer(infer_ty) => {
560 if let ty::TyVar(ty_vid) = infer_ty {
561 if let Some(name) = self.infer_ty_name(ty_vid) {
562 p!(write("{}", name))
564 p!(write("{}", infer_ty))
567 p!(write("{}", infer_ty))
570 ty::Error(_) => p!("[type error]"),
571 ty::Param(ref param_ty) => p!(write("{}", param_ty)),
572 ty::Bound(debruijn, bound_ty) => match bound_ty.kind {
573 ty::BoundTyKind::Anon => self.pretty_print_bound_var(debruijn, bound_ty.var)?,
574 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
576 ty::Adt(def, substs) => {
577 p!(print_def_path(def.did, substs));
579 ty::Dynamic(data, r) => {
580 let print_r = self.region_should_not_be_omitted(r);
584 p!("dyn ", print(data));
586 p!(" + ", print(r), ")");
589 ty::Foreign(def_id) => {
590 p!(print_def_path(def_id, &[]));
592 ty::Projection(ref data) => p!(print(data)),
593 ty::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
594 ty::Opaque(def_id, substs) => {
595 // FIXME(eddyb) print this with `print_def_path`.
596 // We use verbose printing in 'NO_QUERIES' mode, to
597 // avoid needing to call `predicates_of`. This should
598 // only affect certain debug messages (e.g. messages printed
599 // from `rustc_middle::ty` during the computation of `tcx.predicates_of`),
600 // and should have no effect on any compiler output.
601 if self.tcx().sess.verbose() || NO_QUERIES.with(|q| q.get()) {
602 p!(write("Opaque({:?}, {:?})", def_id, substs));
606 return Ok(with_no_queries(|| {
607 let def_key = self.tcx().def_key(def_id);
608 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
609 p!(write("{}", name));
610 // FIXME(eddyb) print this with `print_def_path`.
611 if !substs.is_empty() {
613 p!(generic_delimiters(|cx| cx.comma_sep(substs.iter())));
617 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
618 // by looking up the projections associated with the def_id.
619 let bounds = self.tcx().explicit_item_bounds(def_id);
621 let mut first = true;
622 let mut is_sized = false;
624 for (predicate, _) in bounds {
625 let predicate = predicate.subst(self.tcx(), substs);
626 // Note: We can't use `to_opt_poly_trait_ref` here as `predicate`
627 // may contain unbound variables. We therefore do this manually.
629 // FIXME(lcnr): Find out why exactly this is the case :)
630 let bound_predicate = predicate.bound_atom_with_opt_escaping(self.tcx());
631 if let ty::PredicateAtom::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(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> {
964 define_scoped_cx!(self);
966 match (scalar, &ty.kind()) {
967 // Byte strings (&[u8; N])
975 ty::TyS { kind: ty::Uint(ast::UintTy::U8), .. },
977 val: ty::ConstKind::Value(ConstValue::Scalar(int)),
985 ) => match self.tcx().get_global_alloc(ptr.alloc_id) {
986 Some(GlobalAlloc::Memory(alloc)) => {
987 let bytes = int.assert_bits(self.tcx().data_layout.pointer_size);
988 let size = Size::from_bytes(bytes);
989 if let Ok(byte_str) = alloc.get_bytes(&self.tcx(), ptr, size) {
990 p!(pretty_print_byte_str(byte_str))
992 p!("<too short allocation>")
995 // FIXME: for statics and functions, we could in principle print more detail.
996 Some(GlobalAlloc::Static(def_id)) => p!(write("<static({:?})>", def_id)),
997 Some(GlobalAlloc::Function(_)) => p!("<function>"),
998 None => p!("<dangling pointer>"),
1001 (Scalar::Int(int), ty::Bool) if int == ScalarInt::FALSE => p!("false"),
1002 (Scalar::Int(int), ty::Bool) if int == ScalarInt::TRUE => p!("true"),
1004 (Scalar::Int(int), ty::Float(ast::FloatTy::F32)) => {
1005 p!(write("{}f32", Single::try_from(int).unwrap()))
1007 (Scalar::Int(int), ty::Float(ast::FloatTy::F64)) => {
1008 p!(write("{}f64", Double::try_from(int).unwrap()))
1011 (Scalar::Int(int), ty::Uint(_) | ty::Int(_)) => {
1013 ConstInt::new(int, matches!(ty.kind(), ty::Int(_)), ty.is_ptr_sized_integral());
1014 if print_ty { p!(write("{:#?}", int)) } else { p!(write("{:?}", int)) }
1017 (Scalar::Int(int), ty::Char) if char::try_from(int).is_ok() => {
1018 p!(write("{:?}", char::try_from(int).unwrap()))
1021 (Scalar::Int(int), ty::RawPtr(_)) => {
1022 let data = int.assert_bits(self.tcx().data_layout.pointer_size);
1023 self = self.typed_value(
1025 write!(this, "0x{:x}", data)?;
1028 |this| this.print_type(ty),
1032 (Scalar::Ptr(ptr), ty::FnPtr(_)) => {
1033 // FIXME: this can ICE when the ptr is dangling or points to a non-function.
1034 // We should probably have a helper method to share code with the "Byte strings"
1035 // printing above (which also has to handle pointers to all sorts of things).
1036 let instance = self.tcx().global_alloc(ptr.alloc_id).unwrap_fn();
1037 self = self.typed_value(
1038 |this| this.print_value_path(instance.def_id(), instance.substs),
1039 |this| this.print_type(ty),
1043 // For function type zsts just printing the path is enough
1044 (Scalar::Int(int), ty::FnDef(d, s)) if int == ScalarInt::ZST => {
1045 p!(print_value_path(*d, s))
1047 // Nontrivial types with scalar bit representation
1048 (Scalar::Int(int), _) => {
1049 let print = |mut this: Self| {
1050 if int.size() == Size::ZERO {
1051 write!(this, "transmute(())")?;
1053 write!(this, "transmute(0x{:x})", int)?;
1057 self = if print_ty {
1058 self.typed_value(print, |this| this.print_type(ty), ": ")?
1063 // Any pointer values not covered by a branch above
1064 (Scalar::Ptr(p), _) => {
1065 self = self.pretty_print_const_pointer(p, ty, print_ty)?;
1071 /// This is overridden for MIR printing because we only want to hide alloc ids from users, not
1072 /// from MIR where it is actually useful.
1073 fn pretty_print_const_pointer(
1078 ) -> Result<Self::Const, Self::Error> {
1082 this.write_str("&_")?;
1085 |this| this.print_type(ty),
1089 self.write_str("&_")?;
1094 fn pretty_print_byte_str(mut self, byte_str: &'tcx [u8]) -> Result<Self::Const, Self::Error> {
1095 define_scoped_cx!(self);
1097 for &c in byte_str {
1098 for e in std::ascii::escape_default(c) {
1099 self.write_char(e as char)?;
1106 fn pretty_print_const_value(
1108 ct: ConstValue<'tcx>,
1111 ) -> Result<Self::Const, Self::Error> {
1112 define_scoped_cx!(self);
1114 if self.tcx().sess.verbose() {
1115 p!(write("ConstValue({:?}: ", ct), print(ty), ")");
1119 let u8_type = self.tcx().types.u8;
1121 match (ct, ty.kind()) {
1122 // Byte/string slices, printed as (byte) string literals.
1124 ConstValue::Slice { data, start, end },
1125 ty::Ref(_, ty::TyS { kind: ty::Slice(t), .. }, _),
1126 ) if *t == u8_type => {
1127 // The `inspect` here is okay since we checked the bounds, and there are
1128 // no relocations (we have an active slice reference here). We don't use
1129 // this result to affect interpreter execution.
1130 let byte_str = data.inspect_with_uninit_and_ptr_outside_interpreter(start..end);
1131 self.pretty_print_byte_str(byte_str)
1134 ConstValue::Slice { data, start, end },
1135 ty::Ref(_, ty::TyS { kind: ty::Str, .. }, _),
1137 // The `inspect` here is okay since we checked the bounds, and there are no
1138 // relocations (we have an active `str` reference here). We don't use this
1139 // result to affect interpreter execution.
1140 let slice = data.inspect_with_uninit_and_ptr_outside_interpreter(start..end);
1141 let s = std::str::from_utf8(slice).expect("non utf8 str from miri");
1142 p!(write("{:?}", s));
1145 (ConstValue::ByRef { alloc, offset }, ty::Array(t, n)) if *t == u8_type => {
1146 let n = n.val.try_to_bits(self.tcx().data_layout.pointer_size).unwrap();
1147 // cast is ok because we already checked for pointer size (32 or 64 bit) above
1148 let n = Size::from_bytes(n);
1149 let ptr = Pointer::new(AllocId(0), offset);
1151 let byte_str = alloc.get_bytes(&self.tcx(), ptr, n).unwrap();
1153 p!(pretty_print_byte_str(byte_str));
1157 // Aggregates, printed as array/tuple/struct/variant construction syntax.
1159 // NB: the `has_param_types_or_consts` check ensures that we can use
1160 // the `destructure_const` query with an empty `ty::ParamEnv` without
1161 // introducing ICEs (e.g. via `layout_of`) from missing bounds.
1162 // E.g. `transmute([0usize; 2]): (u8, *mut T)` needs to know `T: Sized`
1163 // to be able to destructure the tuple into `(0u8, *mut T)
1165 // FIXME(eddyb) for `--emit=mir`/`-Z dump-mir`, we should provide the
1166 // correct `ty::ParamEnv` to allow printing *all* constant values.
1167 (_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) if !ty.has_param_types_or_consts() => {
1168 let contents = self.tcx().destructure_const(
1169 ty::ParamEnv::reveal_all()
1170 .and(self.tcx().mk_const(ty::Const { val: ty::ConstKind::Value(ct), ty })),
1172 let fields = contents.fields.iter().copied();
1176 p!("[", comma_sep(fields), "]");
1179 p!("(", comma_sep(fields));
1180 if contents.fields.len() == 1 {
1185 ty::Adt(def, substs) if def.variants.is_empty() => {
1186 p!(print_value_path(def.did, substs));
1188 ty::Adt(def, substs) => {
1190 contents.variant.expect("destructed const of adt without variant id");
1191 let variant_def = &def.variants[variant_id];
1192 p!(print_value_path(variant_def.def_id, substs));
1194 match variant_def.ctor_kind {
1195 CtorKind::Const => {}
1197 p!("(", comma_sep(fields), ")");
1199 CtorKind::Fictive => {
1201 let mut first = true;
1202 for (field_def, field) in variant_def.fields.iter().zip(fields) {
1206 p!(write("{}: ", field_def.ident), print(field));
1213 _ => unreachable!(),
1219 (ConstValue::Scalar(scalar), _) => self.pretty_print_const_scalar(scalar, ty, print_ty),
1221 // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
1222 // their fields instead of just dumping the memory.
1225 p!(write("{:?}", ct));
1227 p!(": ", print(ty));
1235 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
1236 pub struct FmtPrinter<'a, 'tcx, F>(Box<FmtPrinterData<'a, 'tcx, F>>);
1238 pub struct FmtPrinterData<'a, 'tcx, F> {
1244 pub print_alloc_ids: bool,
1246 used_region_names: FxHashSet<Symbol>,
1247 region_index: usize,
1248 binder_depth: usize,
1249 printed_type_count: usize,
1251 pub region_highlight_mode: RegionHighlightMode,
1253 pub name_resolver: Option<Box<&'a dyn Fn(ty::sty::TyVid) -> Option<String>>>,
1256 impl<F> Deref for FmtPrinter<'a, 'tcx, F> {
1257 type Target = FmtPrinterData<'a, 'tcx, F>;
1258 fn deref(&self) -> &Self::Target {
1263 impl<F> DerefMut for FmtPrinter<'_, '_, F> {
1264 fn deref_mut(&mut self) -> &mut Self::Target {
1269 impl<F> FmtPrinter<'a, 'tcx, F> {
1270 pub fn new(tcx: TyCtxt<'tcx>, fmt: F, ns: Namespace) -> Self {
1271 FmtPrinter(Box::new(FmtPrinterData {
1275 in_value: ns == Namespace::ValueNS,
1276 print_alloc_ids: false,
1277 used_region_names: Default::default(),
1280 printed_type_count: 0,
1281 region_highlight_mode: RegionHighlightMode::default(),
1282 name_resolver: None,
1287 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1288 // (but also some things just print a `DefId` generally so maybe we need this?)
1289 fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
1290 match tcx.def_key(def_id).disambiguated_data.data {
1291 DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::ImplTrait => {
1295 DefPathData::ValueNs(..)
1296 | DefPathData::AnonConst
1297 | DefPathData::ClosureExpr
1298 | DefPathData::Ctor => Namespace::ValueNS,
1300 DefPathData::MacroNs(..) => Namespace::MacroNS,
1302 _ => Namespace::TypeNS,
1307 /// Returns a string identifying this `DefId`. This string is
1308 /// suitable for user output.
1309 pub fn def_path_str(self, def_id: DefId) -> String {
1310 self.def_path_str_with_substs(def_id, &[])
1313 pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1314 let ns = guess_def_namespace(self, def_id);
1315 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1316 let mut s = String::new();
1317 let _ = FmtPrinter::new(self, &mut s, ns).print_def_path(def_id, substs);
1322 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, F> {
1323 fn write_str(&mut self, s: &str) -> fmt::Result {
1324 self.fmt.write_str(s)
1328 impl<F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
1329 type Error = fmt::Error;
1334 type DynExistential = Self;
1337 fn tcx(&'a self) -> TyCtxt<'tcx> {
1344 substs: &'tcx [GenericArg<'tcx>],
1345 ) -> Result<Self::Path, Self::Error> {
1346 define_scoped_cx!(self);
1348 if substs.is_empty() {
1349 match self.try_print_trimmed_def_path(def_id)? {
1350 (cx, true) => return Ok(cx),
1351 (cx, false) => self = cx,
1354 match self.try_print_visible_def_path(def_id)? {
1355 (cx, true) => return Ok(cx),
1356 (cx, false) => self = cx,
1360 let key = self.tcx.def_key(def_id);
1361 if let DefPathData::Impl = key.disambiguated_data.data {
1362 // Always use types for non-local impls, where types are always
1363 // available, and filename/line-number is mostly uninteresting.
1364 let use_types = !def_id.is_local() || {
1365 // Otherwise, use filename/line-number if forced.
1366 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1371 // If no type info is available, fall back to
1372 // pretty printing some span information. This should
1373 // only occur very early in the compiler pipeline.
1374 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1375 let span = self.tcx.def_span(def_id);
1377 self = self.print_def_path(parent_def_id, &[])?;
1379 // HACK(eddyb) copy of `path_append` to avoid
1380 // constructing a `DisambiguatedDefPathData`.
1381 if !self.empty_path {
1382 write!(self, "::")?;
1384 write!(self, "<impl at {}>", self.tcx.sess.source_map().span_to_string(span))?;
1385 self.empty_path = false;
1391 self.default_print_def_path(def_id, substs)
1394 fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
1395 self.pretty_print_region(region)
1398 fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1399 if self.tcx.sess.type_length_limit().value_within_limit(self.printed_type_count) {
1400 self.printed_type_count += 1;
1401 self.pretty_print_type(ty)
1403 write!(self, "...")?;
1408 fn print_dyn_existential(
1410 predicates: &'tcx ty::List<ty::Binder<ty::ExistentialPredicate<'tcx>>>,
1411 ) -> Result<Self::DynExistential, Self::Error> {
1412 self.pretty_print_dyn_existential(predicates)
1415 fn print_const(self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1416 self.pretty_print_const(ct, true)
1419 fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1420 self.empty_path = true;
1421 if cnum == LOCAL_CRATE {
1422 if self.tcx.sess.rust_2018() {
1423 // We add the `crate::` keyword on Rust 2018, only when desired.
1424 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1425 write!(self, "{}", kw::Crate)?;
1426 self.empty_path = false;
1430 write!(self, "{}", self.tcx.crate_name(cnum))?;
1431 self.empty_path = false;
1439 trait_ref: Option<ty::TraitRef<'tcx>>,
1440 ) -> Result<Self::Path, Self::Error> {
1441 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1442 self.empty_path = false;
1446 fn path_append_impl(
1448 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1449 _disambiguated_data: &DisambiguatedDefPathData,
1451 trait_ref: Option<ty::TraitRef<'tcx>>,
1452 ) -> Result<Self::Path, Self::Error> {
1453 self = self.pretty_path_append_impl(
1455 cx = print_prefix(cx)?;
1465 self.empty_path = false;
1471 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1472 disambiguated_data: &DisambiguatedDefPathData,
1473 ) -> Result<Self::Path, Self::Error> {
1474 self = print_prefix(self)?;
1476 // Skip `::{{constructor}}` on tuple/unit structs.
1477 if let DefPathData::Ctor = disambiguated_data.data {
1481 // FIXME(eddyb) `name` should never be empty, but it
1482 // currently is for `extern { ... }` "foreign modules".
1483 let name = disambiguated_data.data.name();
1484 if name != DefPathDataName::Named(kw::Invalid) {
1485 if !self.empty_path {
1486 write!(self, "::")?;
1489 if let DefPathDataName::Named(name) = name {
1490 if Ident::with_dummy_span(name).is_raw_guess() {
1491 write!(self, "r#")?;
1495 let verbose = self.tcx.sess.verbose();
1496 disambiguated_data.fmt_maybe_verbose(&mut self, verbose)?;
1498 self.empty_path = false;
1504 fn path_generic_args(
1506 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1507 args: &[GenericArg<'tcx>],
1508 ) -> Result<Self::Path, Self::Error> {
1509 self = print_prefix(self)?;
1511 // Don't print `'_` if there's no unerased regions.
1512 let print_regions = args.iter().any(|arg| match arg.unpack() {
1513 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
1516 let args = args.iter().cloned().filter(|arg| match arg.unpack() {
1517 GenericArgKind::Lifetime(_) => print_regions,
1521 if args.clone().next().is_some() {
1523 write!(self, "::")?;
1525 self.generic_delimiters(|cx| cx.comma_sep(args))
1532 impl<F: fmt::Write> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx, F> {
1533 fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> {
1534 self.0.name_resolver.as_ref().and_then(|func| func(id))
1537 fn print_value_path(
1540 substs: &'tcx [GenericArg<'tcx>],
1541 ) -> Result<Self::Path, Self::Error> {
1542 let was_in_value = std::mem::replace(&mut self.in_value, true);
1543 self = self.print_def_path(def_id, substs)?;
1544 self.in_value = was_in_value;
1549 fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
1551 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1553 self.pretty_in_binder(value)
1556 fn wrap_binder<T, C: Fn(&T, Self) -> Result<Self, Self::Error>>(
1558 value: &ty::Binder<T>,
1560 ) -> Result<Self, Self::Error>
1562 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1564 self.pretty_wrap_binder(value, f)
1569 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1570 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
1572 ) -> Result<Self::Const, Self::Error> {
1573 self.write_str("{")?;
1575 self.write_str(conversion)?;
1576 let was_in_value = std::mem::replace(&mut self.in_value, false);
1578 self.in_value = was_in_value;
1579 self.write_str("}")?;
1583 fn generic_delimiters(
1585 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1586 ) -> Result<Self, Self::Error> {
1589 let was_in_value = std::mem::replace(&mut self.in_value, false);
1590 let mut inner = f(self)?;
1591 inner.in_value = was_in_value;
1593 write!(inner, ">")?;
1597 fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool {
1598 let highlight = self.region_highlight_mode;
1599 if highlight.region_highlighted(region).is_some() {
1603 if self.tcx.sess.verbose() {
1607 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1610 ty::ReEarlyBound(ref data) => {
1611 data.name != kw::Invalid && data.name != kw::UnderscoreLifetime
1614 ty::ReLateBound(_, ty::BoundRegion { kind: br })
1615 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1616 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1617 if let ty::BrNamed(_, name) = br {
1618 if name != kw::Invalid && name != kw::UnderscoreLifetime {
1623 if let Some((region, _)) = highlight.highlight_bound_region {
1632 ty::ReVar(_) if identify_regions => true,
1634 ty::ReVar(_) | ty::ReErased => false,
1636 ty::ReStatic | ty::ReEmpty(_) => true,
1640 fn pretty_print_const_pointer(
1645 ) -> Result<Self::Const, Self::Error> {
1646 let print = |mut this: Self| {
1647 define_scoped_cx!(this);
1648 if this.print_alloc_ids {
1649 p!(write("{:?}", p));
1656 self.typed_value(print, |this| this.print_type(ty), ": ")
1663 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1664 impl<F: fmt::Write> FmtPrinter<'_, '_, F> {
1665 pub fn pretty_print_region(mut self, region: ty::Region<'_>) -> Result<Self, fmt::Error> {
1666 define_scoped_cx!(self);
1668 // Watch out for region highlights.
1669 let highlight = self.region_highlight_mode;
1670 if let Some(n) = highlight.region_highlighted(region) {
1671 p!(write("'{}", n));
1675 if self.tcx.sess.verbose() {
1676 p!(write("{:?}", region));
1680 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1682 // These printouts are concise. They do not contain all the information
1683 // the user might want to diagnose an error, but there is basically no way
1684 // to fit that into a short string. Hence the recommendation to use
1685 // `explain_region()` or `note_and_explain_region()`.
1687 ty::ReEarlyBound(ref data) => {
1688 if data.name != kw::Invalid {
1689 p!(write("{}", data.name));
1693 ty::ReLateBound(_, ty::BoundRegion { kind: br })
1694 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1695 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1696 if let ty::BrNamed(_, name) = br {
1697 if name != kw::Invalid && name != kw::UnderscoreLifetime {
1698 p!(write("{}", name));
1703 if let Some((region, counter)) = highlight.highlight_bound_region {
1705 p!(write("'{}", counter));
1710 ty::ReVar(region_vid) if identify_regions => {
1711 p!(write("{:?}", region_vid));
1720 ty::ReEmpty(ty::UniverseIndex::ROOT) => {
1724 ty::ReEmpty(ui) => {
1725 p!(write("'<empty:{:?}>", ui));
1736 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1737 // `region_index` and `used_region_names`.
1738 impl<F: fmt::Write> FmtPrinter<'_, 'tcx, F> {
1739 pub fn name_all_regions<T>(
1741 value: &ty::Binder<T>,
1742 ) -> Result<(Self, (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)), fmt::Error>
1744 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1746 fn name_by_region_index(index: usize) -> Symbol {
1748 0 => Symbol::intern("'r"),
1749 1 => Symbol::intern("'s"),
1750 i => Symbol::intern(&format!("'t{}", i - 2)),
1754 // Replace any anonymous late-bound regions with named
1755 // variants, using new unique identifiers, so that we can
1756 // clearly differentiate between named and unnamed regions in
1757 // the output. We'll probably want to tweak this over time to
1758 // decide just how much information to give.
1759 if self.binder_depth == 0 {
1760 self.prepare_late_bound_region_info(value);
1763 let mut empty = true;
1764 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1777 define_scoped_cx!(self);
1779 let mut region_index = self.region_index;
1780 let new_value = self.tcx.replace_late_bound_regions(value.clone(), |br| {
1781 let _ = start_or_continue(&mut self, "for<", ", ");
1782 let kind = match br.kind {
1783 ty::BrNamed(_, name) => {
1784 let _ = write!(self, "{}", name);
1787 ty::BrAnon(_) | ty::BrEnv => {
1789 let name = name_by_region_index(region_index);
1791 if !self.used_region_names.contains(&name) {
1795 let _ = write!(self, "{}", name);
1796 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1799 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BoundRegion { kind }))
1801 start_or_continue(&mut self, "", "> ")?;
1803 self.binder_depth += 1;
1804 self.region_index = region_index;
1805 Ok((self, new_value))
1808 pub fn pretty_in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, fmt::Error>
1810 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1812 let old_region_index = self.region_index;
1813 let (new, new_value) = self.name_all_regions(value)?;
1814 let mut inner = new_value.0.print(new)?;
1815 inner.region_index = old_region_index;
1816 inner.binder_depth -= 1;
1820 pub fn pretty_wrap_binder<T, C: Fn(&T, Self) -> Result<Self, fmt::Error>>(
1822 value: &ty::Binder<T>,
1824 ) -> Result<Self, fmt::Error>
1826 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1828 let old_region_index = self.region_index;
1829 let (new, new_value) = self.name_all_regions(value)?;
1830 let mut inner = f(&new_value.0, new)?;
1831 inner.region_index = old_region_index;
1832 inner.binder_depth -= 1;
1836 fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
1838 T: TypeFoldable<'tcx>,
1840 struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet<Symbol>);
1841 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> {
1842 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1843 if let ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name) }) = *r {
1844 self.0.insert(name);
1846 r.super_visit_with(self)
1850 self.used_region_names.clear();
1851 let mut collector = LateBoundRegionNameCollector(&mut self.used_region_names);
1852 value.visit_with(&mut collector);
1853 self.region_index = 0;
1857 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<T>
1859 T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
1862 type Error = P::Error;
1863 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
1868 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
1870 T: Print<'tcx, P, Output = P, Error = P::Error>,
1871 U: Print<'tcx, P, Output = P, Error = P::Error>,
1874 type Error = P::Error;
1875 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
1876 define_scoped_cx!(cx);
1877 p!(print(self.0), ": ", print(self.1));
1882 macro_rules! forward_display_to_print {
1884 $(impl fmt::Display for $ty {
1885 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1886 ty::tls::with(|tcx| {
1888 .expect("could not lift for printing")
1889 .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1897 macro_rules! define_print_and_forward_display {
1898 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
1899 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
1901 type Error = fmt::Error;
1902 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
1903 #[allow(unused_mut)]
1905 define_scoped_cx!($cx);
1907 #[allow(unreachable_code)]
1912 forward_display_to_print!($($ty),+);
1916 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
1917 impl fmt::Display for ty::RegionKind {
1918 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1919 ty::tls::with(|tcx| {
1920 self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1926 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
1927 /// the trait path. That is, it will print `Trait<U>` instead of
1928 /// `<T as Trait<U>>`.
1929 #[derive(Copy, Clone, TypeFoldable, Lift)]
1930 pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
1932 impl fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
1933 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1934 fmt::Display::fmt(self, f)
1938 impl ty::TraitRef<'tcx> {
1939 pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
1940 TraitRefPrintOnlyTraitPath(self)
1944 impl ty::Binder<ty::TraitRef<'tcx>> {
1945 pub fn print_only_trait_path(self) -> ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>> {
1946 self.map_bound(|tr| tr.print_only_trait_path())
1950 forward_display_to_print! {
1952 &'tcx ty::List<ty::Binder<ty::ExistentialPredicate<'tcx>>>,
1953 &'tcx ty::Const<'tcx>,
1955 // HACK(eddyb) these are exhaustive instead of generic,
1956 // because `for<'tcx>` isn't possible yet.
1957 ty::Binder<ty::ExistentialPredicate<'tcx>>,
1958 ty::Binder<ty::TraitRef<'tcx>>,
1959 ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>>,
1960 ty::Binder<ty::FnSig<'tcx>>,
1961 ty::Binder<ty::TraitPredicate<'tcx>>,
1962 ty::Binder<ty::SubtypePredicate<'tcx>>,
1963 ty::Binder<ty::ProjectionPredicate<'tcx>>,
1964 ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1965 ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
1967 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1968 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1971 define_print_and_forward_display! {
1974 &'tcx ty::List<Ty<'tcx>> {
1975 p!("{{", comma_sep(self.iter()), "}}")
1978 ty::TypeAndMut<'tcx> {
1979 p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
1982 ty::ExistentialTraitRef<'tcx> {
1983 // Use a type that can't appear in defaults of type parameters.
1984 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1985 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
1986 p!(print(trait_ref.print_only_trait_path()))
1989 ty::ExistentialProjection<'tcx> {
1990 let name = cx.tcx().associated_item(self.item_def_id).ident;
1991 p!(write("{} = ", name), print(self.ty))
1994 ty::ExistentialPredicate<'tcx> {
1996 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
1997 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
1998 ty::ExistentialPredicate::AutoTrait(def_id) => {
1999 p!(print_def_path(def_id, &[]));
2005 p!(write("{}", self.unsafety.prefix_str()));
2007 if self.abi != Abi::Rust {
2008 p!(write("extern {} ", self.abi));
2011 p!("fn", pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
2015 if cx.tcx().sess.verbose() {
2016 p!(write("{:?}", self));
2020 ty::TyVar(_) => p!("_"),
2021 ty::IntVar(_) => p!(write("{}", "{integer}")),
2022 ty::FloatVar(_) => p!(write("{}", "{float}")),
2023 ty::FreshTy(v) => p!(write("FreshTy({})", v)),
2024 ty::FreshIntTy(v) => p!(write("FreshIntTy({})", v)),
2025 ty::FreshFloatTy(v) => p!(write("FreshFloatTy({})", v))
2029 ty::TraitRef<'tcx> {
2030 p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
2033 TraitRefPrintOnlyTraitPath<'tcx> {
2034 p!(print_def_path(self.0.def_id, self.0.substs));
2038 p!(write("{}", self.name))
2042 p!(write("{}", self.name))
2045 ty::SubtypePredicate<'tcx> {
2046 p!(print(self.a), " <: ", print(self.b))
2049 ty::TraitPredicate<'tcx> {
2050 p!(print(self.trait_ref.self_ty()), ": ",
2051 print(self.trait_ref.print_only_trait_path()))
2054 ty::ProjectionPredicate<'tcx> {
2055 p!(print(self.projection_ty), " == ", print(self.ty))
2058 ty::ProjectionTy<'tcx> {
2059 p!(print_def_path(self.item_def_id, self.substs));
2064 ty::ClosureKind::Fn => p!("Fn"),
2065 ty::ClosureKind::FnMut => p!("FnMut"),
2066 ty::ClosureKind::FnOnce => p!("FnOnce"),
2070 ty::Predicate<'tcx> {
2072 &ty::PredicateKind::Atom(atom) => p!(print(atom)),
2073 ty::PredicateKind::ForAll(binder) => p!(print(binder)),
2077 ty::PredicateAtom<'tcx> {
2079 ty::PredicateAtom::Trait(ref data, constness) => {
2080 if let hir::Constness::Const = constness {
2085 ty::PredicateAtom::Subtype(predicate) => p!(print(predicate)),
2086 ty::PredicateAtom::RegionOutlives(predicate) => p!(print(predicate)),
2087 ty::PredicateAtom::TypeOutlives(predicate) => p!(print(predicate)),
2088 ty::PredicateAtom::Projection(predicate) => p!(print(predicate)),
2089 ty::PredicateAtom::WellFormed(arg) => p!(print(arg), " well-formed"),
2090 ty::PredicateAtom::ObjectSafe(trait_def_id) => {
2091 p!("the trait `", print_def_path(trait_def_id, &[]), "` is object-safe")
2093 ty::PredicateAtom::ClosureKind(closure_def_id, _closure_substs, kind) => {
2095 print_value_path(closure_def_id, &[]),
2096 write("` implements the trait `{}`", kind))
2098 ty::PredicateAtom::ConstEvaluatable(def, substs) => {
2099 p!("the constant `", print_value_path(def.did, substs), "` can be evaluated")
2101 ty::PredicateAtom::ConstEquate(c1, c2) => {
2102 p!("the constant `", print(c1), "` equals `", print(c2), "`")
2104 ty::PredicateAtom::TypeWellFormedFromEnv(ty) => {
2105 p!("the type `", print(ty), "` is found in the environment")
2111 match self.unpack() {
2112 GenericArgKind::Lifetime(lt) => p!(print(lt)),
2113 GenericArgKind::Type(ty) => p!(print(ty)),
2114 GenericArgKind::Const(ct) => p!(print(ct)),
2119 fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
2120 // Iterate all local crate items no matter where they are defined.
2121 let hir = tcx.hir();
2122 for item in hir.krate().items.values() {
2123 if item.ident.name.as_str().is_empty() || matches!(item.kind, ItemKind::Use(_, _)) {
2127 if let Some(local_def_id) = hir.definitions().opt_hir_id_to_local_def_id(item.hir_id) {
2128 let def_id = local_def_id.to_def_id();
2129 let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
2130 collect_fn(&item.ident, ns, def_id);
2134 // Now take care of extern crate items.
2135 let queue = &mut Vec::new();
2136 let mut seen_defs: DefIdSet = Default::default();
2138 for &cnum in tcx.crates().iter() {
2139 let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
2141 // Ignore crates that are not direct dependencies.
2142 match tcx.extern_crate(def_id) {
2144 Some(extern_crate) => {
2145 if !extern_crate.is_direct() {
2154 // Iterate external crate defs but be mindful about visibility
2155 while let Some(def) = queue.pop() {
2156 for child in tcx.item_children(def).iter() {
2157 if child.vis != ty::Visibility::Public {
2162 def::Res::Def(DefKind::AssocTy, _) => {}
2163 def::Res::Def(defkind, def_id) => {
2164 if let Some(ns) = defkind.ns() {
2165 collect_fn(&child.ident, ns, def_id);
2168 if seen_defs.insert(def_id) {
2178 /// The purpose of this function is to collect public symbols names that are unique across all
2179 /// crates in the build. Later, when printing about types we can use those names instead of the
2180 /// full exported path to them.
2182 /// So essentially, if a symbol name can only be imported from one place for a type, and as
2183 /// long as it was not glob-imported anywhere in the current crate, we can trim its printed
2184 /// path and print only the name.
2186 /// This has wide implications on error messages with types, for example, shortening
2187 /// `std::vec::Vec` to just `Vec`, as long as there is no other `Vec` importable anywhere.
2189 /// The implementation uses similar import discovery logic to that of 'use' suggestions.
2190 fn trimmed_def_paths(tcx: TyCtxt<'_>, crate_num: CrateNum) -> FxHashMap<DefId, Symbol> {
2191 assert_eq!(crate_num, LOCAL_CRATE);
2193 let mut map = FxHashMap::default();
2195 if let TrimmedDefPaths::GoodPath = tcx.sess.opts.trimmed_def_paths {
2196 // For good paths causing this bug, the `rustc_middle::ty::print::with_no_trimmed_paths`
2197 // wrapper can be used to suppress this query, in exchange for full paths being formatted.
2198 tcx.sess.delay_good_path_bug("trimmed_def_paths constructed");
2201 let unique_symbols_rev: &mut FxHashMap<(Namespace, Symbol), Option<DefId>> =
2202 &mut FxHashMap::default();
2204 for symbol_set in tcx.glob_map.values() {
2205 for symbol in symbol_set {
2206 unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
2207 unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
2208 unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
2212 for_each_def(tcx, |ident, ns, def_id| {
2213 use std::collections::hash_map::Entry::{Occupied, Vacant};
2215 match unique_symbols_rev.entry((ns, ident.name)) {
2216 Occupied(mut v) => match v.get() {
2219 if *existing != def_id {
2225 v.insert(Some(def_id));
2230 for ((_, symbol), opt_def_id) in unique_symbols_rev.drain() {
2231 if let Some(def_id) = opt_def_id {
2232 map.insert(def_id, symbol);
2239 pub fn provide(providers: &mut ty::query::Providers) {
2240 *providers = ty::query::Providers { trimmed_def_paths, ..*providers };