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 => return Ok((self, false)),
278 self.write_str(&symbol.as_str())?;
279 return Ok((self, true));
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,
1267 printed_type_count: usize,
1269 pub region_highlight_mode: RegionHighlightMode,
1271 pub name_resolver: Option<Box<&'a dyn Fn(ty::sty::TyVid) -> Option<String>>>,
1274 impl<F> Deref for FmtPrinter<'a, 'tcx, F> {
1275 type Target = FmtPrinterData<'a, 'tcx, F>;
1276 fn deref(&self) -> &Self::Target {
1281 impl<F> DerefMut for FmtPrinter<'_, '_, F> {
1282 fn deref_mut(&mut self) -> &mut Self::Target {
1287 impl<F> FmtPrinter<'a, 'tcx, F> {
1288 pub fn new(tcx: TyCtxt<'tcx>, fmt: F, ns: Namespace) -> Self {
1289 FmtPrinter(Box::new(FmtPrinterData {
1293 in_value: ns == Namespace::ValueNS,
1294 print_alloc_ids: false,
1295 used_region_names: Default::default(),
1298 printed_type_count: 0,
1299 region_highlight_mode: RegionHighlightMode::default(),
1300 name_resolver: None,
1305 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1306 // (but also some things just print a `DefId` generally so maybe we need this?)
1307 fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
1308 match tcx.def_key(def_id).disambiguated_data.data {
1309 DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::ImplTrait => {
1313 DefPathData::ValueNs(..)
1314 | DefPathData::AnonConst
1315 | DefPathData::ClosureExpr
1316 | DefPathData::Ctor => Namespace::ValueNS,
1318 DefPathData::MacroNs(..) => Namespace::MacroNS,
1320 _ => Namespace::TypeNS,
1325 /// Returns a string identifying this `DefId`. This string is
1326 /// suitable for user output.
1327 pub fn def_path_str(self, def_id: DefId) -> String {
1328 self.def_path_str_with_substs(def_id, &[])
1331 pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1332 let ns = guess_def_namespace(self, def_id);
1333 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1334 let mut s = String::new();
1335 let _ = FmtPrinter::new(self, &mut s, ns).print_def_path(def_id, substs);
1340 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, F> {
1341 fn write_str(&mut self, s: &str) -> fmt::Result {
1342 self.fmt.write_str(s)
1346 impl<F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
1347 type Error = fmt::Error;
1352 type DynExistential = Self;
1355 fn tcx(&'a self) -> TyCtxt<'tcx> {
1362 substs: &'tcx [GenericArg<'tcx>],
1363 ) -> Result<Self::Path, Self::Error> {
1364 define_scoped_cx!(self);
1366 if substs.is_empty() {
1367 match self.try_print_trimmed_def_path(def_id)? {
1368 (cx, true) => return Ok(cx),
1369 (cx, false) => self = cx,
1372 match self.try_print_visible_def_path(def_id)? {
1373 (cx, true) => return Ok(cx),
1374 (cx, false) => self = cx,
1378 let key = self.tcx.def_key(def_id);
1379 if let DefPathData::Impl = key.disambiguated_data.data {
1380 // Always use types for non-local impls, where types are always
1381 // available, and filename/line-number is mostly uninteresting.
1382 let use_types = !def_id.is_local() || {
1383 // Otherwise, use filename/line-number if forced.
1384 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1389 // If no type info is available, fall back to
1390 // pretty printing some span information. This should
1391 // only occur very early in the compiler pipeline.
1392 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1393 let span = self.tcx.def_span(def_id);
1395 self = self.print_def_path(parent_def_id, &[])?;
1397 // HACK(eddyb) copy of `path_append` to avoid
1398 // constructing a `DisambiguatedDefPathData`.
1399 if !self.empty_path {
1400 write!(self, "::")?;
1402 write!(self, "<impl at {}>", self.tcx.sess.source_map().span_to_string(span))?;
1403 self.empty_path = false;
1409 self.default_print_def_path(def_id, substs)
1412 fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
1413 self.pretty_print_region(region)
1416 fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1417 if self.tcx.sess.type_length_limit().value_within_limit(self.printed_type_count) {
1418 self.printed_type_count += 1;
1419 self.pretty_print_type(ty)
1421 write!(self, "...")?;
1426 fn print_dyn_existential(
1428 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1429 ) -> Result<Self::DynExistential, Self::Error> {
1430 self.pretty_print_dyn_existential(predicates)
1433 fn print_const(self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1434 self.pretty_print_const(ct, true)
1437 fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1438 self.empty_path = true;
1439 if cnum == LOCAL_CRATE {
1440 if self.tcx.sess.rust_2018() {
1441 // We add the `crate::` keyword on Rust 2018, only when desired.
1442 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1443 write!(self, "{}", kw::Crate)?;
1444 self.empty_path = false;
1448 write!(self, "{}", self.tcx.crate_name(cnum))?;
1449 self.empty_path = false;
1457 trait_ref: Option<ty::TraitRef<'tcx>>,
1458 ) -> Result<Self::Path, Self::Error> {
1459 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1460 self.empty_path = false;
1464 fn path_append_impl(
1466 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1467 _disambiguated_data: &DisambiguatedDefPathData,
1469 trait_ref: Option<ty::TraitRef<'tcx>>,
1470 ) -> Result<Self::Path, Self::Error> {
1471 self = self.pretty_path_append_impl(
1473 cx = print_prefix(cx)?;
1483 self.empty_path = false;
1489 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1490 disambiguated_data: &DisambiguatedDefPathData,
1491 ) -> Result<Self::Path, Self::Error> {
1492 self = print_prefix(self)?;
1494 // Skip `::{{constructor}}` on tuple/unit structs.
1495 if let DefPathData::Ctor = disambiguated_data.data {
1499 // FIXME(eddyb) `name` should never be empty, but it
1500 // currently is for `extern { ... }` "foreign modules".
1501 let name = disambiguated_data.data.as_symbol();
1502 if name != kw::Invalid {
1503 if !self.empty_path {
1504 write!(self, "::")?;
1506 if Ident::with_dummy_span(name).is_raw_guess() {
1507 write!(self, "r#")?;
1509 write!(self, "{}", name)?;
1511 // FIXME(eddyb) this will print e.g. `{{closure}}#3`, but it
1512 // might be nicer to use something else, e.g. `{closure#3}`.
1513 let dis = disambiguated_data.disambiguator;
1514 let print_dis = disambiguated_data.data.get_opt_name().is_none()
1515 || dis != 0 && self.tcx.sess.verbose();
1517 write!(self, "#{}", dis)?;
1520 self.empty_path = false;
1526 fn path_generic_args(
1528 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1529 args: &[GenericArg<'tcx>],
1530 ) -> Result<Self::Path, Self::Error> {
1531 self = print_prefix(self)?;
1533 // Don't print `'_` if there's no unerased regions.
1534 let print_regions = args.iter().any(|arg| match arg.unpack() {
1535 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
1538 let args = args.iter().cloned().filter(|arg| match arg.unpack() {
1539 GenericArgKind::Lifetime(_) => print_regions,
1543 if args.clone().next().is_some() {
1545 write!(self, "::")?;
1547 self.generic_delimiters(|cx| cx.comma_sep(args))
1554 impl<F: fmt::Write> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx, F> {
1555 fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> {
1556 self.0.name_resolver.as_ref().and_then(|func| func(id))
1559 fn print_value_path(
1562 substs: &'tcx [GenericArg<'tcx>],
1563 ) -> Result<Self::Path, Self::Error> {
1564 let was_in_value = std::mem::replace(&mut self.in_value, true);
1565 self = self.print_def_path(def_id, substs)?;
1566 self.in_value = was_in_value;
1571 fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
1573 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1575 self.pretty_in_binder(value)
1580 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1581 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
1583 ) -> Result<Self::Const, Self::Error> {
1584 self.write_str("{")?;
1586 self.write_str(conversion)?;
1587 let was_in_value = std::mem::replace(&mut self.in_value, false);
1589 self.in_value = was_in_value;
1590 self.write_str("}")?;
1594 fn generic_delimiters(
1596 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1597 ) -> Result<Self, Self::Error> {
1600 let was_in_value = std::mem::replace(&mut self.in_value, false);
1601 let mut inner = f(self)?;
1602 inner.in_value = was_in_value;
1604 write!(inner, ">")?;
1608 fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool {
1609 let highlight = self.region_highlight_mode;
1610 if highlight.region_highlighted(region).is_some() {
1614 if self.tcx.sess.verbose() {
1618 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1621 ty::ReEarlyBound(ref data) => {
1622 data.name != kw::Invalid && data.name != kw::UnderscoreLifetime
1625 ty::ReLateBound(_, br)
1626 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1627 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1628 if let ty::BrNamed(_, name) = br {
1629 if name != kw::Invalid && name != kw::UnderscoreLifetime {
1634 if let Some((region, _)) = highlight.highlight_bound_region {
1643 ty::ReVar(_) if identify_regions => true,
1645 ty::ReVar(_) | ty::ReErased => false,
1647 ty::ReStatic | ty::ReEmpty(_) => true,
1651 fn pretty_print_const_pointer(
1656 ) -> Result<Self::Const, Self::Error> {
1657 let print = |mut this: Self| {
1658 define_scoped_cx!(this);
1659 if this.print_alloc_ids {
1660 p!(write("{:?}", p));
1667 self.typed_value(print, |this| this.print_type(ty), ": ")
1674 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1675 impl<F: fmt::Write> FmtPrinter<'_, '_, F> {
1676 pub fn pretty_print_region(mut self, region: ty::Region<'_>) -> Result<Self, fmt::Error> {
1677 define_scoped_cx!(self);
1679 // Watch out for region highlights.
1680 let highlight = self.region_highlight_mode;
1681 if let Some(n) = highlight.region_highlighted(region) {
1682 p!(write("'{}", n));
1686 if self.tcx.sess.verbose() {
1687 p!(write("{:?}", region));
1691 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1693 // These printouts are concise. They do not contain all the information
1694 // the user might want to diagnose an error, but there is basically no way
1695 // to fit that into a short string. Hence the recommendation to use
1696 // `explain_region()` or `note_and_explain_region()`.
1698 ty::ReEarlyBound(ref data) => {
1699 if data.name != kw::Invalid {
1700 p!(write("{}", data.name));
1704 ty::ReLateBound(_, br)
1705 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1706 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1707 if let ty::BrNamed(_, name) = br {
1708 if name != kw::Invalid && name != kw::UnderscoreLifetime {
1709 p!(write("{}", name));
1714 if let Some((region, counter)) = highlight.highlight_bound_region {
1716 p!(write("'{}", counter));
1721 ty::ReVar(region_vid) if identify_regions => {
1722 p!(write("{:?}", region_vid));
1728 p!(write("'static"));
1731 ty::ReEmpty(ty::UniverseIndex::ROOT) => {
1732 p!(write("'<empty>"));
1735 ty::ReEmpty(ui) => {
1736 p!(write("'<empty:{:?}>", ui));
1747 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1748 // `region_index` and `used_region_names`.
1749 impl<F: fmt::Write> FmtPrinter<'_, 'tcx, F> {
1750 pub fn name_all_regions<T>(
1752 value: &ty::Binder<T>,
1753 ) -> Result<(Self, (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)), fmt::Error>
1755 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1757 fn name_by_region_index(index: usize) -> Symbol {
1759 0 => Symbol::intern("'r"),
1760 1 => Symbol::intern("'s"),
1761 i => Symbol::intern(&format!("'t{}", i - 2)),
1765 // Replace any anonymous late-bound regions with named
1766 // variants, using new unique identifiers, so that we can
1767 // clearly differentiate between named and unnamed regions in
1768 // the output. We'll probably want to tweak this over time to
1769 // decide just how much information to give.
1770 if self.binder_depth == 0 {
1771 self.prepare_late_bound_region_info(value);
1774 let mut empty = true;
1775 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1788 define_scoped_cx!(self);
1790 let mut region_index = self.region_index;
1791 let new_value = self.tcx.replace_late_bound_regions(value, |br| {
1792 let _ = start_or_continue(&mut self, "for<", ", ");
1794 ty::BrNamed(_, name) => {
1795 let _ = write!(self, "{}", name);
1798 ty::BrAnon(_) | ty::BrEnv => {
1800 let name = name_by_region_index(region_index);
1802 if !self.used_region_names.contains(&name) {
1806 let _ = write!(self, "{}", name);
1807 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1810 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
1812 start_or_continue(&mut self, "", "> ")?;
1814 self.binder_depth += 1;
1815 self.region_index = region_index;
1816 Ok((self, new_value))
1819 pub fn pretty_in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, fmt::Error>
1821 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1823 let old_region_index = self.region_index;
1824 let (new, new_value) = self.name_all_regions(value)?;
1825 let mut inner = new_value.0.print(new)?;
1826 inner.region_index = old_region_index;
1827 inner.binder_depth -= 1;
1831 fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
1833 T: TypeFoldable<'tcx>,
1835 struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet<Symbol>);
1836 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> {
1837 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
1838 if let ty::ReLateBound(_, ty::BrNamed(_, name)) = *r {
1839 self.0.insert(name);
1841 r.super_visit_with(self)
1845 self.used_region_names.clear();
1846 let mut collector = LateBoundRegionNameCollector(&mut self.used_region_names);
1847 value.visit_with(&mut collector);
1848 self.region_index = 0;
1852 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<T>
1854 T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
1857 type Error = P::Error;
1858 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
1863 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
1865 T: Print<'tcx, P, Output = P, Error = P::Error>,
1866 U: Print<'tcx, P, Output = P, Error = P::Error>,
1869 type Error = P::Error;
1870 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
1871 define_scoped_cx!(cx);
1872 p!(print(self.0), write(": "), print(self.1));
1877 macro_rules! forward_display_to_print {
1879 $(impl fmt::Display for $ty {
1880 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1881 ty::tls::with(|tcx| {
1883 .expect("could not lift for printing")
1884 .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1892 macro_rules! define_print_and_forward_display {
1893 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
1894 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
1896 type Error = fmt::Error;
1897 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
1898 #[allow(unused_mut)]
1900 define_scoped_cx!($cx);
1902 #[allow(unreachable_code)]
1907 forward_display_to_print!($($ty),+);
1911 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
1912 impl fmt::Display for ty::RegionKind {
1913 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1914 ty::tls::with(|tcx| {
1915 self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1921 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
1922 /// the trait path. That is, it will print `Trait<U>` instead of
1923 /// `<T as Trait<U>>`.
1924 #[derive(Copy, Clone, TypeFoldable, Lift)]
1925 pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
1927 impl fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
1928 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1929 fmt::Display::fmt(self, f)
1933 impl ty::TraitRef<'tcx> {
1934 pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
1935 TraitRefPrintOnlyTraitPath(self)
1939 impl ty::Binder<ty::TraitRef<'tcx>> {
1940 pub fn print_only_trait_path(self) -> ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>> {
1941 self.map_bound(|tr| tr.print_only_trait_path())
1945 forward_display_to_print! {
1947 &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1948 &'tcx ty::Const<'tcx>,
1950 // HACK(eddyb) these are exhaustive instead of generic,
1951 // because `for<'tcx>` isn't possible yet.
1952 ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
1953 ty::Binder<ty::TraitRef<'tcx>>,
1954 ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>>,
1955 ty::Binder<ty::FnSig<'tcx>>,
1956 ty::Binder<ty::TraitPredicate<'tcx>>,
1957 ty::Binder<ty::SubtypePredicate<'tcx>>,
1958 ty::Binder<ty::ProjectionPredicate<'tcx>>,
1959 ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1960 ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
1962 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1963 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1966 define_print_and_forward_display! {
1969 &'tcx ty::List<Ty<'tcx>> {
1970 p!(write("{{"), comma_sep(self.iter()), write("}}"))
1973 ty::TypeAndMut<'tcx> {
1974 p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
1977 ty::ExistentialTraitRef<'tcx> {
1978 // Use a type that can't appear in defaults of type parameters.
1979 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1980 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
1981 p!(print(trait_ref.print_only_trait_path()))
1984 ty::ExistentialProjection<'tcx> {
1985 let name = cx.tcx().associated_item(self.item_def_id).ident;
1986 p!(write("{} = ", name), print(self.ty))
1989 ty::ExistentialPredicate<'tcx> {
1991 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
1992 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
1993 ty::ExistentialPredicate::AutoTrait(def_id) => {
1994 p!(print_def_path(def_id, &[]));
2000 p!(write("{}", self.unsafety.prefix_str()));
2002 if self.abi != Abi::Rust {
2003 p!(write("extern {} ", self.abi));
2006 p!(write("fn"), pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
2010 if cx.tcx().sess.verbose() {
2011 p!(write("{:?}", self));
2015 ty::TyVar(_) => p!(write("_")),
2016 ty::IntVar(_) => p!(write("{}", "{integer}")),
2017 ty::FloatVar(_) => p!(write("{}", "{float}")),
2018 ty::FreshTy(v) => p!(write("FreshTy({})", v)),
2019 ty::FreshIntTy(v) => p!(write("FreshIntTy({})", v)),
2020 ty::FreshFloatTy(v) => p!(write("FreshFloatTy({})", v))
2024 ty::TraitRef<'tcx> {
2025 p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
2028 TraitRefPrintOnlyTraitPath<'tcx> {
2029 p!(print_def_path(self.0.def_id, self.0.substs));
2033 p!(write("{}", self.name))
2037 p!(write("{}", self.name))
2040 ty::SubtypePredicate<'tcx> {
2041 p!(print(self.a), write(" <: "), print(self.b))
2044 ty::TraitPredicate<'tcx> {
2045 p!(print(self.trait_ref.self_ty()), write(": "),
2046 print(self.trait_ref.print_only_trait_path()))
2049 ty::ProjectionPredicate<'tcx> {
2050 p!(print(self.projection_ty), write(" == "), print(self.ty))
2053 ty::ProjectionTy<'tcx> {
2054 p!(print_def_path(self.item_def_id, self.substs));
2059 ty::ClosureKind::Fn => p!(write("Fn")),
2060 ty::ClosureKind::FnMut => p!(write("FnMut")),
2061 ty::ClosureKind::FnOnce => p!(write("FnOnce")),
2065 ty::Predicate<'tcx> {
2067 &ty::PredicateKind::Atom(atom) => p!(print(atom)),
2068 ty::PredicateKind::ForAll(binder) => p!(print(binder)),
2072 ty::PredicateAtom<'tcx> {
2074 ty::PredicateAtom::Trait(ref data, constness) => {
2075 if let hir::Constness::Const = constness {
2076 p!(write("const "));
2080 ty::PredicateAtom::Subtype(predicate) => p!(print(predicate)),
2081 ty::PredicateAtom::RegionOutlives(predicate) => p!(print(predicate)),
2082 ty::PredicateAtom::TypeOutlives(predicate) => p!(print(predicate)),
2083 ty::PredicateAtom::Projection(predicate) => p!(print(predicate)),
2084 ty::PredicateAtom::WellFormed(arg) => p!(print(arg), write(" well-formed")),
2085 ty::PredicateAtom::ObjectSafe(trait_def_id) => {
2086 p!(write("the trait `"),
2087 print_def_path(trait_def_id, &[]),
2088 write("` is object-safe"))
2090 ty::PredicateAtom::ClosureKind(closure_def_id, _closure_substs, kind) => {
2091 p!(write("the closure `"),
2092 print_value_path(closure_def_id, &[]),
2093 write("` implements the trait `{}`", kind))
2095 ty::PredicateAtom::ConstEvaluatable(def, substs) => {
2096 p!(write("the constant `"),
2097 print_value_path(def.did, substs),
2098 write("` can be evaluated"))
2100 ty::PredicateAtom::ConstEquate(c1, c2) => {
2101 p!(write("the constant `"),
2103 write("` equals `"),
2107 ty::PredicateAtom::TypeWellFormedFromEnv(ty) => {
2108 p!(write("the type `"),
2110 write("` is found in the environment"))
2116 match self.unpack() {
2117 GenericArgKind::Lifetime(lt) => p!(print(lt)),
2118 GenericArgKind::Type(ty) => p!(print(ty)),
2119 GenericArgKind::Const(ct) => p!(print(ct)),
2124 fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
2125 // Iterate all local crate items no matter where they are defined.
2126 let hir = tcx.hir();
2127 for item in hir.krate().items.values() {
2128 if item.ident.name.as_str().is_empty() {
2133 ItemKind::Use(_, _) => {
2139 if let Some(local_def_id) = hir.definitions().opt_hir_id_to_local_def_id(item.hir_id) {
2140 let def_id = local_def_id.to_def_id();
2141 let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
2142 collect_fn(&item.ident, ns, def_id);
2146 // Now take care of extern crate items.
2147 let queue = &mut Vec::new();
2148 let mut seen_defs: DefIdSet = Default::default();
2150 for &cnum in tcx.crates().iter() {
2151 let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
2153 // Ignore crates that are not direct dependencies.
2154 match tcx.extern_crate(def_id) {
2156 Some(extern_crate) => {
2157 if !extern_crate.is_direct() {
2166 // Iterate external crate defs but be mindful about visibility
2167 while let Some(def) = queue.pop() {
2168 for child in tcx.item_children(def).iter() {
2169 if child.vis != ty::Visibility::Public {
2174 def::Res::Def(DefKind::AssocTy, _) => {}
2175 def::Res::Def(defkind, def_id) => {
2176 if let Some(ns) = defkind.ns() {
2177 collect_fn(&child.ident, ns, def_id);
2180 if seen_defs.insert(def_id) {
2190 /// The purpose of this function is to collect public symbols names that are unique across all
2191 /// crates in the build. Later, when printing about types we can use those names instead of the
2192 /// full exported path to them.
2194 /// So essentially, if a symbol name can only be imported from one place for a type, and as
2195 /// long as it was not glob-imported anywhere in the current crate, we can trim its printed
2196 /// path and print only the name.
2198 /// This has wide implications on error messages with types, for example, shortening
2199 /// `std::vec::Vec` to just `Vec`, as long as there is no other `Vec` importable anywhere.
2201 /// The implementation uses similar import discovery logic to that of 'use' suggestions.
2202 fn trimmed_def_paths(tcx: TyCtxt<'_>, crate_num: CrateNum) -> FxHashMap<DefId, Symbol> {
2203 assert_eq!(crate_num, LOCAL_CRATE);
2205 let mut map = FxHashMap::default();
2207 if let TrimmedDefPaths::GoodPath = tcx.sess.opts.trimmed_def_paths {
2208 // For good paths causing this bug, the `rustc_middle::ty::print::with_no_trimmed_paths`
2209 // wrapper can be used to suppress this query, in exchange for full paths being formatted.
2210 tcx.sess.delay_good_path_bug("trimmed_def_paths constructed");
2213 let unique_symbols_rev: &mut FxHashMap<(Namespace, Symbol), Option<DefId>> =
2214 &mut FxHashMap::default();
2216 for symbol_set in tcx.glob_map.values() {
2217 for symbol in symbol_set {
2218 unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
2219 unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
2220 unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
2224 for_each_def(tcx, |ident, ns, def_id| {
2225 use std::collections::hash_map::Entry::{Occupied, Vacant};
2227 match unique_symbols_rev.entry((ns, ident.name)) {
2228 Occupied(mut v) => match v.get() {
2231 if *existing != def_id {
2237 v.insert(Some(def_id));
2242 for ((_, symbol), opt_def_id) in unique_symbols_rev.drain() {
2243 if let Some(def_id) = opt_def_id {
2244 map.insert(def_id, symbol);
2251 pub fn provide(providers: &mut ty::query::Providers) {
2252 *providers = ty::query::Providers { trimmed_def_paths, ..*providers };