1 use crate::middle::cstore::{ExternCrate, ExternCrateSource};
2 use crate::mir::interpret::{AllocId, ConstValue, GlobalAlloc, Pointer, Scalar};
3 use crate::ty::layout::IntegerExt;
4 use crate::ty::subst::{GenericArg, GenericArgKind, Subst};
5 use crate::ty::{self, ConstInt, DefIdTree, ParamConst, Ty, TyCtxt, TypeFoldable};
6 use rustc_apfloat::ieee::{Double, Single};
7 use rustc_apfloat::Float;
9 use rustc_attr::{SignedInt, UnsignedInt};
10 use rustc_data_structures::fx::FxHashMap;
12 use rustc_hir::def::{self, CtorKind, DefKind, Namespace};
13 use rustc_hir::def_id::{CrateNum, DefId, DefIdSet, CRATE_DEF_INDEX, LOCAL_CRATE};
14 use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
15 use rustc_hir::ItemKind;
16 use rustc_session::config::TrimmedDefPaths;
17 use rustc_span::symbol::{kw, Ident, Symbol};
18 use rustc_target::abi::{Integer, Size};
19 use rustc_target::spec::abi::Abi;
23 use std::collections::BTreeMap;
24 use std::fmt::{self, Write as _};
25 use std::ops::{Deref, DerefMut};
27 // `pretty` is a separate module only for organization.
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 ($($kind:ident $data:tt),+) => {{
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. `predicates_of`
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::BoundRegion`, 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::BoundRegion, 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::BoundRegion, 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 /// Prints comma-separated elements.
212 fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
214 T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
216 if let Some(first) = elems.next() {
217 self = first.print(self)?;
219 self.write_str(", ")?;
220 self = elem.print(self)?;
226 /// Prints `{f: t}` or `{f as t}` depending on the `cast` argument
229 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
230 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
232 ) -> Result<Self::Const, Self::Error> {
233 self.write_str("{")?;
235 self.write_str(conversion)?;
237 self.write_str("}")?;
241 /// Prints `<...>` around what `f` prints.
242 fn generic_delimiters(
244 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
245 ) -> Result<Self, Self::Error>;
247 /// Returns `true` if the region should be printed in
248 /// optional positions, e.g., `&'a T` or `dyn Tr + 'b`.
249 /// This is typically the case for all non-`'_` regions.
250 fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool;
252 // Defaults (should not be overridden):
254 /// If possible, this returns a global path resolving to `def_id` that is visible
255 /// from at least one local module, and returns `true`. If the crate defining `def_id` is
256 /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
257 fn try_print_visible_def_path(self, def_id: DefId) -> Result<(Self, bool), Self::Error> {
258 let mut callers = Vec::new();
259 self.try_print_visible_def_path_recur(def_id, &mut callers)
262 /// Try to see if this path can be trimmed to a unique symbol name.
263 fn try_print_trimmed_def_path(
266 ) -> Result<(Self::Path, bool), Self::Error> {
267 if !self.tcx().sess.opts.debugging_opts.trim_diagnostic_paths
268 || matches!(self.tcx().sess.opts.trimmed_def_paths, TrimmedDefPaths::Never)
269 || NO_TRIMMED_PATH.with(|flag| flag.get())
270 || SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get())
272 return Ok((self, false));
275 match self.tcx().trimmed_def_paths(LOCAL_CRATE).get(&def_id) {
276 None => Ok((self, false)),
278 self.write_str(&symbol.as_str())?;
284 /// Does the work of `try_print_visible_def_path`, building the
285 /// full definition path recursively before attempting to
286 /// post-process it into the valid and visible version that
287 /// accounts for re-exports.
289 /// This method should only be called by itself or
290 /// `try_print_visible_def_path`.
292 /// `callers` is a chain of visible_parent's leading to `def_id`,
293 /// to support cycle detection during recursion.
294 fn try_print_visible_def_path_recur(
297 callers: &mut Vec<DefId>,
298 ) -> Result<(Self, bool), Self::Error> {
299 define_scoped_cx!(self);
301 debug!("try_print_visible_def_path: def_id={:?}", def_id);
303 // If `def_id` is a direct or injected extern crate, return the
304 // path to the crate followed by the path to the item within the crate.
305 if def_id.index == CRATE_DEF_INDEX {
306 let cnum = def_id.krate;
308 if cnum == LOCAL_CRATE {
309 return Ok((self.path_crate(cnum)?, true));
312 // In local mode, when we encounter a crate other than
313 // LOCAL_CRATE, execution proceeds in one of two ways:
315 // 1. For a direct dependency, where user added an
316 // `extern crate` manually, we put the `extern
317 // crate` as the parent. So you wind up with
318 // something relative to the current crate.
319 // 2. For an extern inferred from a path or an indirect crate,
320 // where there is no explicit `extern crate`, we just prepend
322 match self.tcx().extern_crate(def_id) {
323 Some(&ExternCrate { src, dependency_of, span, .. }) => match (src, dependency_of) {
324 (ExternCrateSource::Extern(def_id), LOCAL_CRATE) => {
325 debug!("try_print_visible_def_path: def_id={:?}", def_id);
327 if !span.is_dummy() {
328 self.print_def_path(def_id, &[])?
330 self.path_crate(cnum)?
335 (ExternCrateSource::Path, LOCAL_CRATE) => {
336 debug!("try_print_visible_def_path: def_id={:?}", def_id);
337 return Ok((self.path_crate(cnum)?, true));
342 return Ok((self.path_crate(cnum)?, true));
347 if def_id.is_local() {
348 return Ok((self, false));
351 let visible_parent_map = self.tcx().visible_parent_map(LOCAL_CRATE);
353 let mut cur_def_key = self.tcx().def_key(def_id);
354 debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
356 // For a constructor, we want the name of its parent rather than <unnamed>.
357 if let DefPathData::Ctor = cur_def_key.disambiguated_data.data {
362 .expect("`DefPathData::Ctor` / `VariantData` missing a parent"),
365 cur_def_key = self.tcx().def_key(parent);
368 let visible_parent = match visible_parent_map.get(&def_id).cloned() {
369 Some(parent) => parent,
370 None => return Ok((self, false)),
372 if callers.contains(&visible_parent) {
373 return Ok((self, false));
375 callers.push(visible_parent);
376 // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
377 // knowing ahead of time whether the entire path will succeed or not.
378 // To support printers that do not implement `PrettyPrinter`, a `Vec` or
379 // linked list on the stack would need to be built, before any printing.
380 match self.try_print_visible_def_path_recur(visible_parent, callers)? {
381 (cx, false) => return Ok((cx, false)),
382 (cx, true) => self = cx,
385 let actual_parent = self.tcx().parent(def_id);
387 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
388 visible_parent, actual_parent,
391 let mut data = cur_def_key.disambiguated_data.data;
393 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
394 data, visible_parent, actual_parent,
398 // In order to output a path that could actually be imported (valid and visible),
399 // we need to handle re-exports correctly.
401 // For example, take `std::os::unix::process::CommandExt`, this trait is actually
402 // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
404 // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is
405 // private so the "true" path to `CommandExt` isn't accessible.
407 // In this case, the `visible_parent_map` will look something like this:
409 // (child) -> (parent)
410 // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
411 // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
412 // `std::sys::unix::ext` -> `std::os`
414 // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
417 // When printing the path to `CommandExt` and looking at the `cur_def_key` that
418 // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
419 // to the parent - resulting in a mangled path like
420 // `std::os::ext::process::CommandExt`.
422 // Instead, we must detect that there was a re-export and instead print `unix`
423 // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
424 // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
425 // the visible parent (`std::os`). If these do not match, then we iterate over
426 // the children of the visible parent (as was done when computing
427 // `visible_parent_map`), looking for the specific child we currently have and then
428 // have access to the re-exported name.
429 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
432 .item_children(visible_parent)
434 .find(|child| child.res.opt_def_id() == Some(def_id))
435 .map(|child| child.ident.name);
436 if let Some(reexport) = reexport {
440 // Re-exported `extern crate` (#43189).
441 DefPathData::CrateRoot => {
442 data = DefPathData::TypeNs(self.tcx().original_crate_name(def_id.krate));
446 debug!("try_print_visible_def_path: data={:?}", data);
448 Ok((self.path_append(Ok, &DisambiguatedDefPathData { data, disambiguator: 0 })?, true))
451 fn pretty_path_qualified(
454 trait_ref: Option<ty::TraitRef<'tcx>>,
455 ) -> Result<Self::Path, Self::Error> {
456 if trait_ref.is_none() {
457 // Inherent impls. Try to print `Foo::bar` for an inherent
458 // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
459 // anything other than a simple path.
460 match self_ty.kind() {
469 return self_ty.print(self);
476 self.generic_delimiters(|mut cx| {
477 define_scoped_cx!(cx);
480 if let Some(trait_ref) = trait_ref {
481 p!(write(" as "), print(trait_ref.print_only_trait_path()));
487 fn pretty_path_append_impl(
489 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
491 trait_ref: Option<ty::TraitRef<'tcx>>,
492 ) -> Result<Self::Path, Self::Error> {
493 self = print_prefix(self)?;
495 self.generic_delimiters(|mut cx| {
496 define_scoped_cx!(cx);
499 if let Some(trait_ref) = trait_ref {
500 p!(print(trait_ref.print_only_trait_path()), write(" for "));
508 fn pretty_print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
509 define_scoped_cx!(self);
512 ty::Bool => p!(write("bool")),
513 ty::Char => p!(write("char")),
514 ty::Int(t) => p!(write("{}", t.name_str())),
515 ty::Uint(t) => p!(write("{}", t.name_str())),
516 ty::Float(t) => p!(write("{}", t.name_str())),
517 ty::RawPtr(ref tm) => {
521 hir::Mutability::Mut => "mut",
522 hir::Mutability::Not => "const",
527 ty::Ref(r, ty, mutbl) => {
529 if self.region_should_not_be_omitted(r) {
530 p!(print(r), write(" "));
532 p!(print(ty::TypeAndMut { ty, mutbl }))
534 ty::Never => p!(write("!")),
535 ty::Tuple(ref tys) => {
536 p!(write("("), comma_sep(tys.iter()));
542 ty::FnDef(def_id, substs) => {
543 let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs);
544 p!(print(sig), write(" {{"), print_value_path(def_id, substs), write("}}"));
546 ty::FnPtr(ref bare_fn) => p!(print(bare_fn)),
547 ty::Infer(infer_ty) => {
548 if let ty::TyVar(ty_vid) = infer_ty {
549 if let Some(name) = self.infer_ty_name(ty_vid) {
550 p!(write("{}", name))
552 p!(write("{}", infer_ty))
555 p!(write("{}", infer_ty))
558 ty::Error(_) => p!(write("[type error]")),
559 ty::Param(ref param_ty) => p!(write("{}", param_ty)),
560 ty::Bound(debruijn, bound_ty) => match bound_ty.kind {
561 ty::BoundTyKind::Anon => self.pretty_print_bound_var(debruijn, bound_ty.var)?,
562 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
564 ty::Adt(def, substs) => {
565 p!(print_def_path(def.did, substs));
567 ty::Dynamic(data, r) => {
568 let print_r = self.region_should_not_be_omitted(r);
572 p!(write("dyn "), print(data));
574 p!(write(" + "), print(r), write(")"));
577 ty::Foreign(def_id) => {
578 p!(print_def_path(def_id, &[]));
580 ty::Projection(ref data) => p!(print(data)),
581 ty::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
582 ty::Opaque(def_id, substs) => {
583 // FIXME(eddyb) print this with `print_def_path`.
584 // We use verbose printing in 'NO_QUERIES' mode, to
585 // avoid needing to call `predicates_of`. This should
586 // only affect certain debug messages (e.g. messages printed
587 // from `rustc_middle::ty` during the computation of `tcx.predicates_of`),
588 // and should have no effect on any compiler output.
589 if self.tcx().sess.verbose() || NO_QUERIES.with(|q| q.get()) {
590 p!(write("Opaque({:?}, {:?})", def_id, substs));
594 return Ok(with_no_queries(|| {
595 let def_key = self.tcx().def_key(def_id);
596 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
597 p!(write("{}", name));
598 // FIXME(eddyb) print this with `print_def_path`.
599 if !substs.is_empty() {
601 p!(generic_delimiters(|cx| cx.comma_sep(substs.iter())));
605 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
606 // by looking up the projections associated with the def_id.
607 let bounds = self.tcx().predicates_of(def_id).instantiate(self.tcx(), substs);
609 let mut first = true;
610 let mut is_sized = false;
612 for predicate in bounds.predicates {
613 // Note: We can't use `to_opt_poly_trait_ref` here as `predicate`
614 // may contain unbound variables. We therefore do this manually.
616 // FIXME(lcnr): Find out why exactly this is the case :)
617 if let ty::PredicateAtom::Trait(pred, _) =
618 predicate.bound_atom(self.tcx()).skip_binder()
620 let trait_ref = ty::Binder::bind(pred.trait_ref);
621 // Don't print +Sized, but rather +?Sized if absent.
622 if Some(trait_ref.def_id()) == self.tcx().lang_items().sized_trait() {
628 write("{}", if first { " " } else { "+" }),
629 print(trait_ref.print_only_trait_path())
635 p!(write("{}?Sized", if first { " " } else { "+" }));
642 ty::Str => p!(write("str")),
643 ty::Generator(did, substs, movability) => {
645 hir::Movability::Movable => p!(write("[generator")),
646 hir::Movability::Static => p!(write("[static generator")),
649 // FIXME(eddyb) should use `def_span`.
650 if let Some(did) = did.as_local() {
651 let hir_id = self.tcx().hir().local_def_id_to_hir_id(did);
652 let span = self.tcx().hir().span(hir_id);
653 p!(write("@{}", self.tcx().sess.source_map().span_to_string(span)));
655 if substs.as_generator().is_valid() {
656 let upvar_tys = substs.as_generator().upvar_tys();
658 for (&var_id, upvar_ty) in self
660 .upvars_mentioned(did)
663 .flat_map(|v| v.keys())
666 p!(write("{}{}:", sep, self.tcx().hir().name(var_id)), print(upvar_ty));
671 p!(write("@{}", self.tcx().def_path_str(did)));
673 if substs.as_generator().is_valid() {
674 let upvar_tys = substs.as_generator().upvar_tys();
676 for (index, upvar_ty) in upvar_tys.enumerate() {
677 p!(write("{}{}:", sep, index), print(upvar_ty));
683 if substs.as_generator().is_valid() {
684 p!(write(" "), print(substs.as_generator().witness()));
689 ty::GeneratorWitness(types) => {
690 p!(in_binder(&types));
692 ty::Closure(did, substs) => {
693 p!(write("[closure"));
695 // FIXME(eddyb) should use `def_span`.
696 if let Some(did) = did.as_local() {
697 let hir_id = self.tcx().hir().local_def_id_to_hir_id(did);
698 if self.tcx().sess.opts.debugging_opts.span_free_formats {
699 p!(write("@"), print_def_path(did.to_def_id(), substs));
701 let span = self.tcx().hir().span(hir_id);
702 p!(write("@{}", self.tcx().sess.source_map().span_to_string(span)));
705 if substs.as_closure().is_valid() {
706 let upvar_tys = substs.as_closure().upvar_tys();
708 for (&var_id, upvar_ty) in self
710 .upvars_mentioned(did)
713 .flat_map(|v| v.keys())
716 p!(write("{}{}:", sep, self.tcx().hir().name(var_id)), print(upvar_ty));
721 p!(write("@{}", self.tcx().def_path_str(did)));
723 if substs.as_closure().is_valid() {
724 let upvar_tys = substs.as_closure().upvar_tys();
726 for (index, upvar_ty) in upvar_tys.enumerate() {
727 p!(write("{}{}:", sep, index), print(upvar_ty));
733 if self.tcx().sess.verbose() && substs.as_closure().is_valid() {
734 p!(write(" closure_kind_ty="), print(substs.as_closure().kind_ty()));
736 write(" closure_sig_as_fn_ptr_ty="),
737 print(substs.as_closure().sig_as_fn_ptr_ty())
743 ty::Array(ty, sz) => {
744 p!(write("["), print(ty), write("; "));
745 if self.tcx().sess.verbose() {
746 p!(write("{:?}", sz));
747 } else if let ty::ConstKind::Unevaluated(..) = sz.val {
748 // Do not try to evaluate unevaluated constants. If we are const evaluating an
749 // array length anon const, rustc will (with debug assertions) print the
750 // constant's path. Which will end up here again.
752 } else if let Some(n) = sz.val.try_to_bits(self.tcx().data_layout.pointer_size) {
754 } else if let ty::ConstKind::Param(param) = sz.val {
755 p!(write("{}", param));
761 ty::Slice(ty) => p!(write("["), print(ty), write("]")),
767 fn pretty_print_bound_var(
769 debruijn: ty::DebruijnIndex,
771 ) -> Result<(), Self::Error> {
772 if debruijn == ty::INNERMOST {
773 write!(self, "^{}", var.index())
775 write!(self, "^{}_{}", debruijn.index(), var.index())
779 fn infer_ty_name(&self, _: ty::TyVid) -> Option<String> {
783 fn pretty_print_dyn_existential(
785 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
786 ) -> Result<Self::DynExistential, Self::Error> {
787 define_scoped_cx!(self);
789 // Generate the main trait ref, including associated types.
790 let mut first = true;
792 if let Some(principal) = predicates.principal() {
793 p!(print_def_path(principal.def_id, &[]));
795 let mut resugared = false;
797 // Special-case `Fn(...) -> ...` and resugar it.
798 let fn_trait_kind = self.tcx().fn_trait_kind_from_lang_item(principal.def_id);
799 if !self.tcx().sess.verbose() && fn_trait_kind.is_some() {
800 if let ty::Tuple(ref args) = principal.substs.type_at(0).kind() {
801 let mut projections = predicates.projection_bounds();
802 if let (Some(proj), None) = (projections.next(), projections.next()) {
803 let tys: Vec<_> = args.iter().map(|k| k.expect_ty()).collect();
804 p!(pretty_fn_sig(&tys, false, proj.ty));
810 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
811 // in order to place the projections inside the `<...>`.
813 // Use a type that can't appear in defaults of type parameters.
814 let dummy_self = self.tcx().mk_ty_infer(ty::FreshTy(0));
815 let principal = principal.with_self_ty(self.tcx(), dummy_self);
817 let args = self.generic_args_to_print(
818 self.tcx().generics_of(principal.def_id),
822 // Don't print `'_` if there's no unerased regions.
823 let print_regions = args.iter().any(|arg| match arg.unpack() {
824 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
827 let mut args = args.iter().cloned().filter(|arg| match arg.unpack() {
828 GenericArgKind::Lifetime(_) => print_regions,
831 let mut projections = predicates.projection_bounds();
833 let arg0 = args.next();
834 let projection0 = projections.next();
835 if arg0.is_some() || projection0.is_some() {
836 let args = arg0.into_iter().chain(args);
837 let projections = projection0.into_iter().chain(projections);
839 p!(generic_delimiters(|mut cx| {
840 cx = cx.comma_sep(args)?;
841 if arg0.is_some() && projection0.is_some() {
844 cx.comma_sep(projections)
852 // FIXME(eddyb) avoid printing twice (needed to ensure
853 // that the auto traits are sorted *and* printed via cx).
854 let mut auto_traits: Vec<_> =
855 predicates.auto_traits().map(|did| (self.tcx().def_path_str(did), did)).collect();
857 // The auto traits come ordered by `DefPathHash`. While
858 // `DefPathHash` is *stable* in the sense that it depends on
859 // neither the host nor the phase of the moon, it depends
860 // "pseudorandomly" on the compiler version and the target.
862 // To avoid that causing instabilities in compiletest
863 // output, sort the auto-traits alphabetically.
866 for (_, def_id) in auto_traits {
872 p!(print_def_path(def_id, &[]));
883 ) -> Result<Self, Self::Error> {
884 define_scoped_cx!(self);
886 p!(write("("), comma_sep(inputs.iter().copied()));
888 if !inputs.is_empty() {
894 if !output.is_unit() {
895 p!(write(" -> "), print(output));
901 fn pretty_print_const(
903 ct: &'tcx ty::Const<'tcx>,
905 ) -> Result<Self::Const, Self::Error> {
906 define_scoped_cx!(self);
908 if self.tcx().sess.verbose() {
909 p!(write("Const({:?}: {:?})", ct.val, ct.ty));
913 macro_rules! print_underscore {
916 self = self.typed_value(
921 |this| this.print_type(ct.ty),
931 ty::ConstKind::Unevaluated(def, substs, promoted) => {
932 if let Some(promoted) = promoted {
933 p!(print_value_path(def.did, substs));
934 p!(write("::{:?}", promoted));
936 match self.tcx().def_kind(def.did) {
937 DefKind::Static | DefKind::Const | DefKind::AssocConst => {
938 p!(print_value_path(def.did, substs))
942 let span = self.tcx().def_span(def.did);
943 if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span)
945 p!(write("{}", snip))
956 ty::ConstKind::Infer(..) => print_underscore!(),
957 ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)),
958 ty::ConstKind::Value(value) => {
959 return self.pretty_print_const_value(value, ct.ty, print_ty);
962 ty::ConstKind::Bound(debruijn, bound_var) => {
963 self.pretty_print_bound_var(debruijn, bound_var)?
965 ty::ConstKind::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
966 ty::ConstKind::Error(_) => p!(write("[const error]")),
971 fn pretty_print_const_scalar(
976 ) -> Result<Self::Const, Self::Error> {
977 define_scoped_cx!(self);
979 match (scalar, &ty.kind()) {
980 // Byte strings (&[u8; N])
988 ty::TyS { kind: ty::Uint(ast::UintTy::U8), .. },
991 ty::ConstKind::Value(ConstValue::Scalar(Scalar::Raw {
1002 ) => match self.tcx().get_global_alloc(ptr.alloc_id) {
1003 Some(GlobalAlloc::Memory(alloc)) => {
1004 if let Ok(byte_str) = alloc.get_bytes(&self.tcx(), ptr, Size::from_bytes(*data))
1006 p!(pretty_print_byte_str(byte_str))
1008 p!(write("<too short allocation>"))
1011 // FIXME: for statics and functions, we could in principle print more detail.
1012 Some(GlobalAlloc::Static(def_id)) => p!(write("<static({:?})>", def_id)),
1013 Some(GlobalAlloc::Function(_)) => p!(write("<function>")),
1014 None => p!(write("<dangling pointer>")),
1017 (Scalar::Raw { data: 0, .. }, ty::Bool) => p!(write("false")),
1018 (Scalar::Raw { data: 1, .. }, ty::Bool) => p!(write("true")),
1020 (Scalar::Raw { data, .. }, ty::Float(ast::FloatTy::F32)) => {
1021 p!(write("{}f32", Single::from_bits(data)))
1023 (Scalar::Raw { data, .. }, ty::Float(ast::FloatTy::F64)) => {
1024 p!(write("{}f64", Double::from_bits(data)))
1027 (Scalar::Raw { data, .. }, ty::Uint(ui)) => {
1028 let size = Integer::from_attr(&self.tcx(), UnsignedInt(*ui)).size();
1029 let int = ConstInt::new(data, size, false, ty.is_ptr_sized_integral());
1030 if print_ty { p!(write("{:#?}", int)) } else { p!(write("{:?}", int)) }
1032 (Scalar::Raw { data, .. }, ty::Int(i)) => {
1033 let size = Integer::from_attr(&self.tcx(), SignedInt(*i)).size();
1034 let int = ConstInt::new(data, size, true, ty.is_ptr_sized_integral());
1035 if print_ty { p!(write("{:#?}", int)) } else { p!(write("{:?}", int)) }
1038 (Scalar::Raw { data, .. }, ty::Char) if char::from_u32(data as u32).is_some() => {
1039 p!(write("{:?}", char::from_u32(data as u32).unwrap()))
1042 (Scalar::Raw { data, .. }, ty::RawPtr(_)) => {
1043 self = self.typed_value(
1045 write!(this, "0x{:x}", data)?;
1048 |this| this.print_type(ty),
1052 (Scalar::Ptr(ptr), ty::FnPtr(_)) => {
1053 // FIXME: this can ICE when the ptr is dangling or points to a non-function.
1054 // We should probably have a helper method to share code with the "Byte strings"
1055 // printing above (which also has to handle pointers to all sorts of things).
1056 let instance = self.tcx().global_alloc(ptr.alloc_id).unwrap_fn();
1057 self = self.typed_value(
1058 |this| this.print_value_path(instance.def_id(), instance.substs),
1059 |this| this.print_type(ty),
1063 // For function type zsts just printing the path is enough
1064 (Scalar::Raw { size: 0, .. }, ty::FnDef(d, s)) => p!(print_value_path(*d, s)),
1065 // Nontrivial types with scalar bit representation
1066 (Scalar::Raw { data, size }, _) => {
1067 let print = |mut this: Self| {
1069 write!(this, "transmute(())")?;
1071 write!(this, "transmute(0x{:01$x})", data, size as usize * 2)?;
1075 self = if print_ty {
1076 self.typed_value(print, |this| this.print_type(ty), ": ")?
1081 // Any pointer values not covered by a branch above
1082 (Scalar::Ptr(p), _) => {
1083 self = self.pretty_print_const_pointer(p, ty, print_ty)?;
1089 /// This is overridden for MIR printing because we only want to hide alloc ids from users, not
1090 /// from MIR where it is actually useful.
1091 fn pretty_print_const_pointer(
1096 ) -> Result<Self::Const, Self::Error> {
1100 this.write_str("&_")?;
1103 |this| this.print_type(ty),
1107 self.write_str("&_")?;
1112 fn pretty_print_byte_str(mut self, byte_str: &'tcx [u8]) -> Result<Self::Const, Self::Error> {
1113 define_scoped_cx!(self);
1115 for &c in byte_str {
1116 for e in std::ascii::escape_default(c) {
1117 self.write_char(e as char)?;
1124 fn pretty_print_const_value(
1126 ct: ConstValue<'tcx>,
1129 ) -> Result<Self::Const, Self::Error> {
1130 define_scoped_cx!(self);
1132 if self.tcx().sess.verbose() {
1133 p!(write("ConstValue({:?}: ", ct), print(ty), write(")"));
1137 let u8_type = self.tcx().types.u8;
1139 match (ct, ty.kind()) {
1140 // Byte/string slices, printed as (byte) string literals.
1142 ConstValue::Slice { data, start, end },
1143 ty::Ref(_, ty::TyS { kind: ty::Slice(t), .. }, _),
1144 ) if *t == u8_type => {
1145 // The `inspect` here is okay since we checked the bounds, and there are
1146 // no relocations (we have an active slice reference here). We don't use
1147 // this result to affect interpreter execution.
1148 let byte_str = data.inspect_with_uninit_and_ptr_outside_interpreter(start..end);
1149 self.pretty_print_byte_str(byte_str)
1152 ConstValue::Slice { data, start, end },
1153 ty::Ref(_, ty::TyS { kind: ty::Str, .. }, _),
1155 // The `inspect` here is okay since we checked the bounds, and there are no
1156 // relocations (we have an active `str` reference here). We don't use this
1157 // result to affect interpreter execution.
1158 let slice = data.inspect_with_uninit_and_ptr_outside_interpreter(start..end);
1159 let s = ::std::str::from_utf8(slice).expect("non utf8 str from miri");
1160 p!(write("{:?}", s));
1163 (ConstValue::ByRef { alloc, offset }, ty::Array(t, n)) if *t == u8_type => {
1164 let n = n.val.try_to_bits(self.tcx().data_layout.pointer_size).unwrap();
1165 // cast is ok because we already checked for pointer size (32 or 64 bit) above
1166 let n = Size::from_bytes(n);
1167 let ptr = Pointer::new(AllocId(0), offset);
1169 let byte_str = alloc.get_bytes(&self.tcx(), ptr, n).unwrap();
1171 p!(pretty_print_byte_str(byte_str));
1175 // Aggregates, printed as array/tuple/struct/variant construction syntax.
1177 // NB: the `has_param_types_or_consts` check ensures that we can use
1178 // the `destructure_const` query with an empty `ty::ParamEnv` without
1179 // introducing ICEs (e.g. via `layout_of`) from missing bounds.
1180 // E.g. `transmute([0usize; 2]): (u8, *mut T)` needs to know `T: Sized`
1181 // to be able to destructure the tuple into `(0u8, *mut T)
1183 // FIXME(eddyb) for `--emit=mir`/`-Z dump-mir`, we should provide the
1184 // correct `ty::ParamEnv` to allow printing *all* constant values.
1185 (_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) if !ty.has_param_types_or_consts() => {
1186 let contents = self.tcx().destructure_const(
1187 ty::ParamEnv::reveal_all()
1188 .and(self.tcx().mk_const(ty::Const { val: ty::ConstKind::Value(ct), ty })),
1190 let fields = contents.fields.iter().copied();
1194 p!(write("["), comma_sep(fields), write("]"));
1197 p!(write("("), comma_sep(fields));
1198 if contents.fields.len() == 1 {
1203 ty::Adt(def, substs) if def.variants.is_empty() => {
1204 p!(print_value_path(def.did, substs));
1206 ty::Adt(def, substs) => {
1208 contents.variant.expect("destructed const of adt without variant id");
1209 let variant_def = &def.variants[variant_id];
1210 p!(print_value_path(variant_def.def_id, substs));
1212 match variant_def.ctor_kind {
1213 CtorKind::Const => {}
1215 p!(write("("), comma_sep(fields), write(")"));
1217 CtorKind::Fictive => {
1219 let mut first = true;
1220 for (field_def, field) in variant_def.fields.iter().zip(fields) {
1224 p!(write("{}: ", field_def.ident), print(field));
1231 _ => unreachable!(),
1237 (ConstValue::Scalar(scalar), _) => self.pretty_print_const_scalar(scalar, ty, print_ty),
1239 // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
1240 // their fields instead of just dumping the memory.
1243 p!(write("{:?}", ct));
1245 p!(write(": "), print(ty));
1253 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
1254 pub struct FmtPrinter<'a, 'tcx, F>(Box<FmtPrinterData<'a, 'tcx, F>>);
1256 pub struct FmtPrinterData<'a, 'tcx, F> {
1262 pub print_alloc_ids: bool,
1264 used_region_names: FxHashSet<Symbol>,
1265 region_index: usize,
1266 binder_depth: usize,
1268 pub region_highlight_mode: RegionHighlightMode,
1270 pub name_resolver: Option<Box<&'a dyn Fn(ty::sty::TyVid) -> Option<String>>>,
1273 impl<F> Deref for FmtPrinter<'a, 'tcx, F> {
1274 type Target = FmtPrinterData<'a, 'tcx, F>;
1275 fn deref(&self) -> &Self::Target {
1280 impl<F> DerefMut for FmtPrinter<'_, '_, F> {
1281 fn deref_mut(&mut self) -> &mut Self::Target {
1286 impl<F> FmtPrinter<'a, 'tcx, F> {
1287 pub fn new(tcx: TyCtxt<'tcx>, fmt: F, ns: Namespace) -> Self {
1288 FmtPrinter(Box::new(FmtPrinterData {
1292 in_value: ns == Namespace::ValueNS,
1293 print_alloc_ids: false,
1294 used_region_names: Default::default(),
1297 region_highlight_mode: RegionHighlightMode::default(),
1298 name_resolver: None,
1303 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1304 // (but also some things just print a `DefId` generally so maybe we need this?)
1305 fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
1306 match tcx.def_key(def_id).disambiguated_data.data {
1307 DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::ImplTrait => {
1311 DefPathData::ValueNs(..)
1312 | DefPathData::AnonConst
1313 | DefPathData::ClosureExpr
1314 | DefPathData::Ctor => Namespace::ValueNS,
1316 DefPathData::MacroNs(..) => Namespace::MacroNS,
1318 _ => Namespace::TypeNS,
1323 /// Returns a string identifying this `DefId`. This string is
1324 /// suitable for user output.
1325 pub fn def_path_str(self, def_id: DefId) -> String {
1326 self.def_path_str_with_substs(def_id, &[])
1329 pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1330 let ns = guess_def_namespace(self, def_id);
1331 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1332 let mut s = String::new();
1333 let _ = FmtPrinter::new(self, &mut s, ns).print_def_path(def_id, substs);
1338 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, F> {
1339 fn write_str(&mut self, s: &str) -> fmt::Result {
1340 self.fmt.write_str(s)
1344 impl<F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
1345 type Error = fmt::Error;
1350 type DynExistential = Self;
1353 fn tcx(&'a self) -> TyCtxt<'tcx> {
1360 substs: &'tcx [GenericArg<'tcx>],
1361 ) -> Result<Self::Path, Self::Error> {
1362 define_scoped_cx!(self);
1364 if substs.is_empty() {
1365 match self.try_print_trimmed_def_path(def_id)? {
1366 (cx, true) => return Ok(cx),
1367 (cx, false) => self = cx,
1370 match self.try_print_visible_def_path(def_id)? {
1371 (cx, true) => return Ok(cx),
1372 (cx, false) => self = cx,
1376 let key = self.tcx.def_key(def_id);
1377 if let DefPathData::Impl = key.disambiguated_data.data {
1378 // Always use types for non-local impls, where types are always
1379 // available, and filename/line-number is mostly uninteresting.
1380 let use_types = !def_id.is_local() || {
1381 // Otherwise, use filename/line-number if forced.
1382 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1387 // If no type info is available, fall back to
1388 // pretty printing some span information. This should
1389 // only occur very early in the compiler pipeline.
1390 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1391 let span = self.tcx.def_span(def_id);
1393 self = self.print_def_path(parent_def_id, &[])?;
1395 // HACK(eddyb) copy of `path_append` to avoid
1396 // constructing a `DisambiguatedDefPathData`.
1397 if !self.empty_path {
1398 write!(self, "::")?;
1400 write!(self, "<impl at {}>", self.tcx.sess.source_map().span_to_string(span))?;
1401 self.empty_path = false;
1407 self.default_print_def_path(def_id, substs)
1410 fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
1411 self.pretty_print_region(region)
1414 fn print_type(self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1415 self.pretty_print_type(ty)
1418 fn print_dyn_existential(
1420 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1421 ) -> Result<Self::DynExistential, Self::Error> {
1422 self.pretty_print_dyn_existential(predicates)
1425 fn print_const(self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1426 self.pretty_print_const(ct, true)
1429 fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1430 self.empty_path = true;
1431 if cnum == LOCAL_CRATE {
1432 if self.tcx.sess.rust_2018() {
1433 // We add the `crate::` keyword on Rust 2018, only when desired.
1434 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1435 write!(self, "{}", kw::Crate)?;
1436 self.empty_path = false;
1440 write!(self, "{}", self.tcx.crate_name(cnum))?;
1441 self.empty_path = false;
1449 trait_ref: Option<ty::TraitRef<'tcx>>,
1450 ) -> Result<Self::Path, Self::Error> {
1451 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1452 self.empty_path = false;
1456 fn path_append_impl(
1458 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1459 _disambiguated_data: &DisambiguatedDefPathData,
1461 trait_ref: Option<ty::TraitRef<'tcx>>,
1462 ) -> Result<Self::Path, Self::Error> {
1463 self = self.pretty_path_append_impl(
1465 cx = print_prefix(cx)?;
1475 self.empty_path = false;
1481 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1482 disambiguated_data: &DisambiguatedDefPathData,
1483 ) -> Result<Self::Path, Self::Error> {
1484 self = print_prefix(self)?;
1486 // Skip `::{{constructor}}` on tuple/unit structs.
1487 if let DefPathData::Ctor = disambiguated_data.data {
1491 // FIXME(eddyb) `name` should never be empty, but it
1492 // currently is for `extern { ... }` "foreign modules".
1493 let name = disambiguated_data.data.as_symbol();
1494 if name != kw::Invalid {
1495 if !self.empty_path {
1496 write!(self, "::")?;
1498 if Ident::with_dummy_span(name).is_raw_guess() {
1499 write!(self, "r#")?;
1501 write!(self, "{}", name)?;
1503 // FIXME(eddyb) this will print e.g. `{{closure}}#3`, but it
1504 // might be nicer to use something else, e.g. `{closure#3}`.
1505 let dis = disambiguated_data.disambiguator;
1506 let print_dis = disambiguated_data.data.get_opt_name().is_none()
1507 || dis != 0 && self.tcx.sess.verbose();
1509 write!(self, "#{}", dis)?;
1512 self.empty_path = false;
1518 fn path_generic_args(
1520 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1521 args: &[GenericArg<'tcx>],
1522 ) -> Result<Self::Path, Self::Error> {
1523 self = print_prefix(self)?;
1525 // Don't print `'_` if there's no unerased regions.
1526 let print_regions = args.iter().any(|arg| match arg.unpack() {
1527 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
1530 let args = args.iter().cloned().filter(|arg| match arg.unpack() {
1531 GenericArgKind::Lifetime(_) => print_regions,
1535 if args.clone().next().is_some() {
1537 write!(self, "::")?;
1539 self.generic_delimiters(|cx| cx.comma_sep(args))
1546 impl<F: fmt::Write> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx, F> {
1547 fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> {
1548 self.0.name_resolver.as_ref().and_then(|func| func(id))
1551 fn print_value_path(
1554 substs: &'tcx [GenericArg<'tcx>],
1555 ) -> Result<Self::Path, Self::Error> {
1556 let was_in_value = std::mem::replace(&mut self.in_value, true);
1557 self = self.print_def_path(def_id, substs)?;
1558 self.in_value = was_in_value;
1563 fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
1565 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1567 self.pretty_in_binder(value)
1572 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1573 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
1575 ) -> Result<Self::Const, Self::Error> {
1576 self.write_str("{")?;
1578 self.write_str(conversion)?;
1579 let was_in_value = std::mem::replace(&mut self.in_value, false);
1581 self.in_value = was_in_value;
1582 self.write_str("}")?;
1586 fn generic_delimiters(
1588 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1589 ) -> Result<Self, Self::Error> {
1592 let was_in_value = std::mem::replace(&mut self.in_value, false);
1593 let mut inner = f(self)?;
1594 inner.in_value = was_in_value;
1596 write!(inner, ">")?;
1600 fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool {
1601 let highlight = self.region_highlight_mode;
1602 if highlight.region_highlighted(region).is_some() {
1606 if self.tcx.sess.verbose() {
1610 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1613 ty::ReEarlyBound(ref data) => {
1614 data.name != kw::Invalid && data.name != kw::UnderscoreLifetime
1617 ty::ReLateBound(_, br)
1618 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1619 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1620 if let ty::BrNamed(_, name) = br {
1621 if name != kw::Invalid && name != kw::UnderscoreLifetime {
1626 if let Some((region, _)) = highlight.highlight_bound_region {
1635 ty::ReVar(_) if identify_regions => true,
1637 ty::ReVar(_) | ty::ReErased => false,
1639 ty::ReStatic | ty::ReEmpty(_) => true,
1643 fn pretty_print_const_pointer(
1648 ) -> Result<Self::Const, Self::Error> {
1649 let print = |mut this: Self| {
1650 define_scoped_cx!(this);
1651 if this.print_alloc_ids {
1652 p!(write("{:?}", p));
1659 self.typed_value(print, |this| this.print_type(ty), ": ")
1666 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1667 impl<F: fmt::Write> FmtPrinter<'_, '_, F> {
1668 pub fn pretty_print_region(mut self, region: ty::Region<'_>) -> Result<Self, fmt::Error> {
1669 define_scoped_cx!(self);
1671 // Watch out for region highlights.
1672 let highlight = self.region_highlight_mode;
1673 if let Some(n) = highlight.region_highlighted(region) {
1674 p!(write("'{}", n));
1678 if self.tcx.sess.verbose() {
1679 p!(write("{:?}", region));
1683 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1685 // These printouts are concise. They do not contain all the information
1686 // the user might want to diagnose an error, but there is basically no way
1687 // to fit that into a short string. Hence the recommendation to use
1688 // `explain_region()` or `note_and_explain_region()`.
1690 ty::ReEarlyBound(ref data) => {
1691 if data.name != kw::Invalid {
1692 p!(write("{}", data.name));
1696 ty::ReLateBound(_, br)
1697 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1698 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1699 if let ty::BrNamed(_, name) = br {
1700 if name != kw::Invalid && name != kw::UnderscoreLifetime {
1701 p!(write("{}", name));
1706 if let Some((region, counter)) = highlight.highlight_bound_region {
1708 p!(write("'{}", counter));
1713 ty::ReVar(region_vid) if identify_regions => {
1714 p!(write("{:?}", region_vid));
1720 p!(write("'static"));
1723 ty::ReEmpty(ty::UniverseIndex::ROOT) => {
1724 p!(write("'<empty>"));
1727 ty::ReEmpty(ui) => {
1728 p!(write("'<empty:{:?}>", ui));
1739 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1740 // `region_index` and `used_region_names`.
1741 impl<F: fmt::Write> FmtPrinter<'_, 'tcx, F> {
1742 pub fn name_all_regions<T>(
1744 value: &ty::Binder<T>,
1745 ) -> Result<(Self, (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)), fmt::Error>
1747 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1749 fn name_by_region_index(index: usize) -> Symbol {
1751 0 => Symbol::intern("'r"),
1752 1 => Symbol::intern("'s"),
1753 i => Symbol::intern(&format!("'t{}", i - 2)),
1757 // Replace any anonymous late-bound regions with named
1758 // variants, using new unique identifiers, so that we can
1759 // clearly differentiate between named and unnamed regions in
1760 // the output. We'll probably want to tweak this over time to
1761 // decide just how much information to give.
1762 if self.binder_depth == 0 {
1763 self.prepare_late_bound_region_info(value);
1766 let mut empty = true;
1767 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1780 define_scoped_cx!(self);
1782 let mut region_index = self.region_index;
1783 let new_value = self.tcx.replace_late_bound_regions(value, |br| {
1784 let _ = start_or_continue(&mut self, "for<", ", ");
1786 ty::BrNamed(_, name) => {
1787 let _ = write!(self, "{}", name);
1790 ty::BrAnon(_) | ty::BrEnv => {
1792 let name = name_by_region_index(region_index);
1794 if !self.used_region_names.contains(&name) {
1798 let _ = write!(self, "{}", name);
1799 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1802 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
1804 start_or_continue(&mut self, "", "> ")?;
1806 self.binder_depth += 1;
1807 self.region_index = region_index;
1808 Ok((self, new_value))
1811 pub fn pretty_in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, fmt::Error>
1813 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1815 let old_region_index = self.region_index;
1816 let (new, new_value) = self.name_all_regions(value)?;
1817 let mut inner = new_value.0.print(new)?;
1818 inner.region_index = old_region_index;
1819 inner.binder_depth -= 1;
1823 fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
1825 T: TypeFoldable<'tcx>,
1827 struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet<Symbol>);
1828 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> {
1829 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
1830 if let ty::ReLateBound(_, ty::BrNamed(_, name)) = *r {
1831 self.0.insert(name);
1833 r.super_visit_with(self)
1837 self.used_region_names.clear();
1838 let mut collector = LateBoundRegionNameCollector(&mut self.used_region_names);
1839 value.visit_with(&mut collector);
1840 self.region_index = 0;
1844 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<T>
1846 T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
1849 type Error = P::Error;
1850 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
1855 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
1857 T: Print<'tcx, P, Output = P, Error = P::Error>,
1858 U: Print<'tcx, P, Output = P, Error = P::Error>,
1861 type Error = P::Error;
1862 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
1863 define_scoped_cx!(cx);
1864 p!(print(self.0), write(": "), print(self.1));
1869 macro_rules! forward_display_to_print {
1871 $(impl fmt::Display for $ty {
1872 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1873 ty::tls::with(|tcx| {
1875 .expect("could not lift for printing")
1876 .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1884 macro_rules! define_print_and_forward_display {
1885 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
1886 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
1888 type Error = fmt::Error;
1889 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
1890 #[allow(unused_mut)]
1892 define_scoped_cx!($cx);
1894 #[allow(unreachable_code)]
1899 forward_display_to_print!($($ty),+);
1903 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
1904 impl fmt::Display for ty::RegionKind {
1905 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1906 ty::tls::with(|tcx| {
1907 self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1913 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
1914 /// the trait path. That is, it will print `Trait<U>` instead of
1915 /// `<T as Trait<U>>`.
1916 #[derive(Copy, Clone, TypeFoldable, Lift)]
1917 pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
1919 impl fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
1920 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1921 fmt::Display::fmt(self, f)
1925 impl ty::TraitRef<'tcx> {
1926 pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
1927 TraitRefPrintOnlyTraitPath(self)
1931 impl ty::Binder<ty::TraitRef<'tcx>> {
1932 pub fn print_only_trait_path(self) -> ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>> {
1933 self.map_bound(|tr| tr.print_only_trait_path())
1937 forward_display_to_print! {
1939 &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1940 &'tcx ty::Const<'tcx>,
1942 // HACK(eddyb) these are exhaustive instead of generic,
1943 // because `for<'tcx>` isn't possible yet.
1944 ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
1945 ty::Binder<ty::TraitRef<'tcx>>,
1946 ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>>,
1947 ty::Binder<ty::FnSig<'tcx>>,
1948 ty::Binder<ty::TraitPredicate<'tcx>>,
1949 ty::Binder<ty::SubtypePredicate<'tcx>>,
1950 ty::Binder<ty::ProjectionPredicate<'tcx>>,
1951 ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1952 ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
1954 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1955 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1958 define_print_and_forward_display! {
1961 &'tcx ty::List<Ty<'tcx>> {
1962 p!(write("{{"), comma_sep(self.iter()), write("}}"))
1965 ty::TypeAndMut<'tcx> {
1966 p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
1969 ty::ExistentialTraitRef<'tcx> {
1970 // Use a type that can't appear in defaults of type parameters.
1971 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1972 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
1973 p!(print(trait_ref.print_only_trait_path()))
1976 ty::ExistentialProjection<'tcx> {
1977 let name = cx.tcx().associated_item(self.item_def_id).ident;
1978 p!(write("{} = ", name), print(self.ty))
1981 ty::ExistentialPredicate<'tcx> {
1983 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
1984 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
1985 ty::ExistentialPredicate::AutoTrait(def_id) => {
1986 p!(print_def_path(def_id, &[]));
1992 p!(write("{}", self.unsafety.prefix_str()));
1994 if self.abi != Abi::Rust {
1995 p!(write("extern {} ", self.abi));
1998 p!(write("fn"), pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
2002 if cx.tcx().sess.verbose() {
2003 p!(write("{:?}", self));
2007 ty::TyVar(_) => p!(write("_")),
2008 ty::IntVar(_) => p!(write("{}", "{integer}")),
2009 ty::FloatVar(_) => p!(write("{}", "{float}")),
2010 ty::FreshTy(v) => p!(write("FreshTy({})", v)),
2011 ty::FreshIntTy(v) => p!(write("FreshIntTy({})", v)),
2012 ty::FreshFloatTy(v) => p!(write("FreshFloatTy({})", v))
2016 ty::TraitRef<'tcx> {
2017 p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
2020 TraitRefPrintOnlyTraitPath<'tcx> {
2021 p!(print_def_path(self.0.def_id, self.0.substs));
2025 p!(write("{}", self.name))
2029 p!(write("{}", self.name))
2032 ty::SubtypePredicate<'tcx> {
2033 p!(print(self.a), write(" <: "), print(self.b))
2036 ty::TraitPredicate<'tcx> {
2037 p!(print(self.trait_ref.self_ty()), write(": "),
2038 print(self.trait_ref.print_only_trait_path()))
2041 ty::ProjectionPredicate<'tcx> {
2042 p!(print(self.projection_ty), write(" == "), print(self.ty))
2045 ty::ProjectionTy<'tcx> {
2046 p!(print_def_path(self.item_def_id, self.substs));
2051 ty::ClosureKind::Fn => p!(write("Fn")),
2052 ty::ClosureKind::FnMut => p!(write("FnMut")),
2053 ty::ClosureKind::FnOnce => p!(write("FnOnce")),
2057 ty::Predicate<'tcx> {
2059 &ty::PredicateKind::Atom(atom) => p!(print(atom)),
2060 ty::PredicateKind::ForAll(binder) => p!(print(binder)),
2064 ty::PredicateAtom<'tcx> {
2066 ty::PredicateAtom::Trait(ref data, constness) => {
2067 if let hir::Constness::Const = constness {
2068 p!(write("const "));
2072 ty::PredicateAtom::Subtype(predicate) => p!(print(predicate)),
2073 ty::PredicateAtom::RegionOutlives(predicate) => p!(print(predicate)),
2074 ty::PredicateAtom::TypeOutlives(predicate) => p!(print(predicate)),
2075 ty::PredicateAtom::Projection(predicate) => p!(print(predicate)),
2076 ty::PredicateAtom::WellFormed(arg) => p!(print(arg), write(" well-formed")),
2077 ty::PredicateAtom::ObjectSafe(trait_def_id) => {
2078 p!(write("the trait `"),
2079 print_def_path(trait_def_id, &[]),
2080 write("` is object-safe"))
2082 ty::PredicateAtom::ClosureKind(closure_def_id, _closure_substs, kind) => {
2083 p!(write("the closure `"),
2084 print_value_path(closure_def_id, &[]),
2085 write("` implements the trait `{}`", kind))
2087 ty::PredicateAtom::ConstEvaluatable(def, substs) => {
2088 p!(write("the constant `"),
2089 print_value_path(def.did, substs),
2090 write("` can be evaluated"))
2092 ty::PredicateAtom::ConstEquate(c1, c2) => {
2093 p!(write("the constant `"),
2095 write("` equals `"),
2099 ty::PredicateAtom::TypeWellFormedFromEnv(ty) => {
2100 p!(write("the type `"),
2102 write("` is found in the environment"))
2108 match self.unpack() {
2109 GenericArgKind::Lifetime(lt) => p!(print(lt)),
2110 GenericArgKind::Type(ty) => p!(print(ty)),
2111 GenericArgKind::Const(ct) => p!(print(ct)),
2116 fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
2117 // Iterate all local crate items no matter where they are defined.
2118 let hir = tcx.hir();
2119 for item in hir.krate().items.values() {
2120 if item.ident.name.as_str().is_empty() {
2125 ItemKind::Use(_, _) => {
2131 if let Some(local_def_id) = hir.definitions().opt_hir_id_to_local_def_id(item.hir_id) {
2132 let def_id = local_def_id.to_def_id();
2133 let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
2134 collect_fn(&item.ident, ns, def_id);
2138 // Now take care of extern crate items.
2139 let queue = &mut Vec::new();
2140 let mut seen_defs: DefIdSet = Default::default();
2142 for &cnum in tcx.crates().iter() {
2143 let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
2145 // Ignore crates that are not direct dependencies.
2146 match tcx.extern_crate(def_id) {
2148 Some(extern_crate) => {
2149 if !extern_crate.is_direct() {
2158 // Iterate external crate defs but be mindful about visibility
2159 while let Some(def) = queue.pop() {
2160 for child in tcx.item_children(def).iter() {
2161 if child.vis != ty::Visibility::Public {
2166 def::Res::Def(DefKind::AssocTy, _) => {}
2167 def::Res::Def(defkind, def_id) => {
2168 if let Some(ns) = defkind.ns() {
2169 collect_fn(&child.ident, ns, def_id);
2172 if seen_defs.insert(def_id) {
2182 /// The purpose of this function is to collect public symbols names that are unique across all
2183 /// crates in the build. Later, when printing about types we can use those names instead of the
2184 /// full exported path to them.
2186 /// So essentially, if a symbol name can only be imported from one place for a type, and as
2187 /// long as it was not glob-imported anywhere in the current crate, we can trim its printed
2188 /// path and print only the name.
2190 /// This has wide implications on error messages with types, for example, shortening
2191 /// `std::vec::Vec` to just `Vec`, as long as there is no other `Vec` importable anywhere.
2193 /// The implementation uses similar import discovery logic to that of 'use' suggestions.
2194 fn trimmed_def_paths(tcx: TyCtxt<'_>, crate_num: CrateNum) -> FxHashMap<DefId, Symbol> {
2195 assert_eq!(crate_num, LOCAL_CRATE);
2197 let mut map = FxHashMap::default();
2199 if let TrimmedDefPaths::GoodPath = tcx.sess.opts.trimmed_def_paths {
2200 // For good paths causing this bug, the `rustc_middle::ty::print::with_no_trimmed_paths`
2201 // wrapper can be used to suppress this query, in exchange for full paths being formatted.
2202 tcx.sess.delay_good_path_bug("trimmed_def_paths constructed");
2205 let unique_symbols_rev: &mut FxHashMap<(Namespace, Symbol), Option<DefId>> =
2206 &mut FxHashMap::default();
2208 for symbol_set in tcx.glob_map.values() {
2209 for symbol in symbol_set {
2210 unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
2211 unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
2212 unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
2216 for_each_def(tcx, |ident, ns, def_id| {
2217 use std::collections::hash_map::Entry::{Occupied, Vacant};
2219 match unique_symbols_rev.entry((ns, ident.name)) {
2220 Occupied(mut v) => match v.get() {
2223 if *existing != def_id {
2229 v.insert(Some(def_id));
2234 for ((_, symbol), opt_def_id) in unique_symbols_rev.drain() {
2235 if let Some(def_id) = opt_def_id {
2236 map.insert(def_id, symbol);
2243 pub fn provide(providers: &mut ty::query::Providers) {
2244 *providers = ty::query::Providers { trimmed_def_paths, ..*providers };