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};
11 use rustc_hir::def::{CtorKind, DefKind, Namespace};
12 use rustc_hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
13 use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
14 use rustc_span::symbol::{kw, Ident, Symbol};
15 use rustc_target::abi::{Integer, Size};
16 use rustc_target::spec::abi::Abi;
20 use std::collections::BTreeMap;
21 use std::fmt::{self, Write as _};
22 use std::ops::{Deref, DerefMut};
24 // `pretty` is a separate module only for organization.
28 (@write($($data:expr),+)) => {
29 write!(scoped_cx!(), $($data),+)?
31 (@print($x:expr)) => {
32 scoped_cx!() = $x.print(scoped_cx!())?
34 (@$method:ident($($arg:expr),*)) => {
35 scoped_cx!() = scoped_cx!().$method($($arg),*)?
37 ($($kind:ident $data:tt),+) => {{
41 macro_rules! define_scoped_cx {
43 #[allow(unused_macros)]
44 macro_rules! scoped_cx {
53 static FORCE_IMPL_FILENAME_LINE: Cell<bool> = Cell::new(false);
54 static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = Cell::new(false);
55 static NO_QUERIES: Cell<bool> = Cell::new(false);
58 /// Avoids running any queries during any prints that occur
59 /// during the closure. This may alter the appearance of some
60 /// types (e.g. forcing verbose printing for opaque types).
61 /// This method is used during some queries (e.g. `predicates_of`
62 /// for opaque types), to ensure that any debug printing that
63 /// occurs during the query computation does not end up recursively
64 /// calling the same query.
65 pub fn with_no_queries<F: FnOnce() -> R, R>(f: F) -> R {
66 NO_QUERIES.with(|no_queries| {
67 let old = no_queries.replace(true);
74 /// Force us to name impls with just the filename/line number. We
75 /// normally try to use types. But at some points, notably while printing
76 /// cycle errors, this can result in extra or suboptimal error output,
77 /// so this variable disables that check.
78 pub fn with_forced_impl_filename_line<F: FnOnce() -> R, R>(f: F) -> R {
79 FORCE_IMPL_FILENAME_LINE.with(|force| {
80 let old = force.replace(true);
87 /// Adds the `crate::` prefix to paths where appropriate.
88 pub fn with_crate_prefix<F: FnOnce() -> R, R>(f: F) -> R {
89 SHOULD_PREFIX_WITH_CRATE.with(|flag| {
90 let old = flag.replace(true);
97 /// The "region highlights" are used to control region printing during
98 /// specific error messages. When a "region highlight" is enabled, it
99 /// gives an alternate way to print specific regions. For now, we
100 /// always print those regions using a number, so something like "`'0`".
102 /// Regions not selected by the region highlight mode are presently
104 #[derive(Copy, Clone, Default)]
105 pub struct RegionHighlightMode {
106 /// If enabled, when we see the selected region, use "`'N`"
107 /// instead of the ordinary behavior.
108 highlight_regions: [Option<(ty::RegionKind, usize)>; 3],
110 /// If enabled, when printing a "free region" that originated from
111 /// the given `ty::BoundRegion`, print it as "`'1`". Free regions that would ordinarily
112 /// have names print as normal.
114 /// This is used when you have a signature like `fn foo(x: &u32,
115 /// y: &'a u32)` and we want to give a name to the region of the
117 highlight_bound_region: Option<(ty::BoundRegion, usize)>,
120 impl RegionHighlightMode {
121 /// If `region` and `number` are both `Some`, invokes
122 /// `highlighting_region`.
123 pub fn maybe_highlighting_region(
125 region: Option<ty::Region<'_>>,
126 number: Option<usize>,
128 if let Some(k) = region {
129 if let Some(n) = number {
130 self.highlighting_region(k, n);
135 /// Highlights the region inference variable `vid` as `'N`.
136 pub fn highlighting_region(&mut self, region: ty::Region<'_>, number: usize) {
137 let num_slots = self.highlight_regions.len();
138 let first_avail_slot =
139 self.highlight_regions.iter_mut().find(|s| s.is_none()).unwrap_or_else(|| {
140 bug!("can only highlight {} placeholders at a time", num_slots,)
142 *first_avail_slot = Some((*region, number));
145 /// Convenience wrapper for `highlighting_region`.
146 pub fn highlighting_region_vid(&mut self, vid: ty::RegionVid, number: usize) {
147 self.highlighting_region(&ty::ReVar(vid), number)
150 /// Returns `Some(n)` with the number to use for the given region, if any.
151 fn region_highlighted(&self, region: ty::Region<'_>) -> Option<usize> {
152 self.highlight_regions.iter().find_map(|h| match h {
153 Some((r, n)) if r == region => Some(*n),
158 /// Highlight the given bound region.
159 /// We can only highlight one bound region at a time. See
160 /// the field `highlight_bound_region` for more detailed notes.
161 pub fn highlighting_bound_region(&mut self, br: ty::BoundRegion, number: usize) {
162 assert!(self.highlight_bound_region.is_none());
163 self.highlight_bound_region = Some((br, number));
167 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
168 pub trait PrettyPrinter<'tcx>:
175 DynExistential = Self,
179 /// Like `print_def_path` but for value paths.
183 substs: &'tcx [GenericArg<'tcx>],
184 ) -> Result<Self::Path, Self::Error> {
185 self.print_def_path(def_id, substs)
188 fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
190 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
192 value.as_ref().skip_binder().print(self)
195 /// Prints comma-separated elements.
196 fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
198 T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
200 if let Some(first) = elems.next() {
201 self = first.print(self)?;
203 self.write_str(", ")?;
204 self = elem.print(self)?;
210 /// Prints `{f: t}` or `{f as t}` depending on the `cast` argument
213 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
214 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
216 ) -> Result<Self::Const, Self::Error> {
217 self.write_str("{")?;
219 self.write_str(conversion)?;
221 self.write_str("}")?;
225 /// Prints `<...>` around what `f` prints.
226 fn generic_delimiters(
228 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
229 ) -> Result<Self, Self::Error>;
231 /// Returns `true` if the region should be printed in
232 /// optional positions, e.g., `&'a T` or `dyn Tr + 'b`.
233 /// This is typically the case for all non-`'_` regions.
234 fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool;
236 // Defaults (should not be overridden):
238 /// If possible, this returns a global path resolving to `def_id` that is visible
239 /// from at least one local module, and returns `true`. If the crate defining `def_id` is
240 /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
241 fn try_print_visible_def_path(self, def_id: DefId) -> Result<(Self, bool), Self::Error> {
242 let mut callers = Vec::new();
243 self.try_print_visible_def_path_recur(def_id, &mut callers)
246 /// Does the work of `try_print_visible_def_path`, building the
247 /// full definition path recursively before attempting to
248 /// post-process it into the valid and visible version that
249 /// accounts for re-exports.
251 /// This method should only be called by itself or
252 /// `try_print_visible_def_path`.
254 /// `callers` is a chain of visible_parent's leading to `def_id`,
255 /// to support cycle detection during recursion.
256 fn try_print_visible_def_path_recur(
259 callers: &mut Vec<DefId>,
260 ) -> Result<(Self, bool), Self::Error> {
261 define_scoped_cx!(self);
263 debug!("try_print_visible_def_path: def_id={:?}", def_id);
265 // If `def_id` is a direct or injected extern crate, return the
266 // path to the crate followed by the path to the item within the crate.
267 if def_id.index == CRATE_DEF_INDEX {
268 let cnum = def_id.krate;
270 if cnum == LOCAL_CRATE {
271 return Ok((self.path_crate(cnum)?, true));
274 // In local mode, when we encounter a crate other than
275 // LOCAL_CRATE, execution proceeds in one of two ways:
277 // 1. For a direct dependency, where user added an
278 // `extern crate` manually, we put the `extern
279 // crate` as the parent. So you wind up with
280 // something relative to the current crate.
281 // 2. For an extern inferred from a path or an indirect crate,
282 // where there is no explicit `extern crate`, we just prepend
284 match self.tcx().extern_crate(def_id) {
285 Some(&ExternCrate { src, dependency_of, span, .. }) => match (src, dependency_of) {
286 (ExternCrateSource::Extern(def_id), LOCAL_CRATE) => {
287 debug!("try_print_visible_def_path: def_id={:?}", def_id);
289 if !span.is_dummy() {
290 self.print_def_path(def_id, &[])?
292 self.path_crate(cnum)?
297 (ExternCrateSource::Path, LOCAL_CRATE) => {
298 debug!("try_print_visible_def_path: def_id={:?}", def_id);
299 return Ok((self.path_crate(cnum)?, true));
304 return Ok((self.path_crate(cnum)?, true));
309 if def_id.is_local() {
310 return Ok((self, false));
313 let visible_parent_map = self.tcx().visible_parent_map(LOCAL_CRATE);
315 let mut cur_def_key = self.tcx().def_key(def_id);
316 debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
318 // For a constructor, we want the name of its parent rather than <unnamed>.
319 if let DefPathData::Ctor = cur_def_key.disambiguated_data.data {
324 .expect("`DefPathData::Ctor` / `VariantData` missing a parent"),
327 cur_def_key = self.tcx().def_key(parent);
330 let visible_parent = match visible_parent_map.get(&def_id).cloned() {
331 Some(parent) => parent,
332 None => return Ok((self, false)),
334 if callers.contains(&visible_parent) {
335 return Ok((self, false));
337 callers.push(visible_parent);
338 // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
339 // knowing ahead of time whether the entire path will succeed or not.
340 // To support printers that do not implement `PrettyPrinter`, a `Vec` or
341 // linked list on the stack would need to be built, before any printing.
342 match self.try_print_visible_def_path_recur(visible_parent, callers)? {
343 (cx, false) => return Ok((cx, false)),
344 (cx, true) => self = cx,
347 let actual_parent = self.tcx().parent(def_id);
349 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
350 visible_parent, actual_parent,
353 let mut data = cur_def_key.disambiguated_data.data;
355 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
356 data, visible_parent, actual_parent,
360 // In order to output a path that could actually be imported (valid and visible),
361 // we need to handle re-exports correctly.
363 // For example, take `std::os::unix::process::CommandExt`, this trait is actually
364 // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
366 // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is
367 // private so the "true" path to `CommandExt` isn't accessible.
369 // In this case, the `visible_parent_map` will look something like this:
371 // (child) -> (parent)
372 // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
373 // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
374 // `std::sys::unix::ext` -> `std::os`
376 // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
379 // When printing the path to `CommandExt` and looking at the `cur_def_key` that
380 // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
381 // to the parent - resulting in a mangled path like
382 // `std::os::ext::process::CommandExt`.
384 // Instead, we must detect that there was a re-export and instead print `unix`
385 // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
386 // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
387 // the visible parent (`std::os`). If these do not match, then we iterate over
388 // the children of the visible parent (as was done when computing
389 // `visible_parent_map`), looking for the specific child we currently have and then
390 // have access to the re-exported name.
391 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
394 .item_children(visible_parent)
396 .find(|child| child.res.opt_def_id() == Some(def_id))
397 .map(|child| child.ident.name);
398 if let Some(reexport) = reexport {
402 // Re-exported `extern crate` (#43189).
403 DefPathData::CrateRoot => {
404 data = DefPathData::TypeNs(self.tcx().original_crate_name(def_id.krate));
408 debug!("try_print_visible_def_path: data={:?}", data);
410 Ok((self.path_append(Ok, &DisambiguatedDefPathData { data, disambiguator: 0 })?, true))
413 fn pretty_path_qualified(
416 trait_ref: Option<ty::TraitRef<'tcx>>,
417 ) -> Result<Self::Path, Self::Error> {
418 if trait_ref.is_none() {
419 // Inherent impls. Try to print `Foo::bar` for an inherent
420 // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
421 // anything other than a simple path.
431 return self_ty.print(self);
438 self.generic_delimiters(|mut cx| {
439 define_scoped_cx!(cx);
442 if let Some(trait_ref) = trait_ref {
443 p!(write(" as "), print(trait_ref.print_only_trait_path()));
449 fn pretty_path_append_impl(
451 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
453 trait_ref: Option<ty::TraitRef<'tcx>>,
454 ) -> Result<Self::Path, Self::Error> {
455 self = print_prefix(self)?;
457 self.generic_delimiters(|mut cx| {
458 define_scoped_cx!(cx);
461 if let Some(trait_ref) = trait_ref {
462 p!(print(trait_ref.print_only_trait_path()), write(" for "));
470 fn pretty_print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
471 define_scoped_cx!(self);
474 ty::Bool => p!(write("bool")),
475 ty::Char => p!(write("char")),
476 ty::Int(t) => p!(write("{}", t.name_str())),
477 ty::Uint(t) => p!(write("{}", t.name_str())),
478 ty::Float(t) => p!(write("{}", t.name_str())),
479 ty::RawPtr(ref tm) => {
483 hir::Mutability::Mut => "mut",
484 hir::Mutability::Not => "const",
489 ty::Ref(r, ty, mutbl) => {
491 if self.region_should_not_be_omitted(r) {
492 p!(print(r), write(" "));
494 p!(print(ty::TypeAndMut { ty, mutbl }))
496 ty::Never => p!(write("!")),
497 ty::Tuple(ref tys) => {
498 p!(write("("), comma_sep(tys.iter()));
504 ty::FnDef(def_id, substs) => {
505 let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs);
506 p!(print(sig), write(" {{"), print_value_path(def_id, substs), write("}}"));
508 ty::FnPtr(ref bare_fn) => p!(print(bare_fn)),
509 ty::Infer(infer_ty) => {
510 if let ty::TyVar(ty_vid) = infer_ty {
511 if let Some(name) = self.infer_ty_name(ty_vid) {
512 p!(write("{}", name))
514 p!(write("{}", infer_ty))
517 p!(write("{}", infer_ty))
520 ty::Error(_) => p!(write("[type error]")),
521 ty::Param(ref param_ty) => p!(write("{}", param_ty)),
522 ty::Bound(debruijn, bound_ty) => match bound_ty.kind {
523 ty::BoundTyKind::Anon => self.pretty_print_bound_var(debruijn, bound_ty.var)?,
524 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
526 ty::Adt(def, substs) => {
527 p!(print_def_path(def.did, substs));
529 ty::Dynamic(data, r) => {
530 let print_r = self.region_should_not_be_omitted(r);
534 p!(write("dyn "), print(data));
536 p!(write(" + "), print(r), write(")"));
539 ty::Foreign(def_id) => {
540 p!(print_def_path(def_id, &[]));
542 ty::Projection(ref data) => p!(print(data)),
543 ty::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
544 ty::Opaque(def_id, substs) => {
545 // FIXME(eddyb) print this with `print_def_path`.
546 // We use verbose printing in 'NO_QUERIES' mode, to
547 // avoid needing to call `predicates_of`. This should
548 // only affect certain debug messages (e.g. messages printed
549 // from `rustc_middle::ty` during the computation of `tcx.predicates_of`),
550 // and should have no effect on any compiler output.
551 if self.tcx().sess.verbose() || NO_QUERIES.with(|q| q.get()) {
552 p!(write("Opaque({:?}, {:?})", def_id, substs));
556 return Ok(with_no_queries(|| {
557 let def_key = self.tcx().def_key(def_id);
558 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
559 p!(write("{}", name));
560 // FIXME(eddyb) print this with `print_def_path`.
561 if !substs.is_empty() {
563 p!(generic_delimiters(|cx| cx.comma_sep(substs.iter())));
567 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
568 // by looking up the projections associated with the def_id.
569 let bounds = self.tcx().predicates_of(def_id).instantiate(self.tcx(), substs);
571 let mut first = true;
572 let mut is_sized = false;
574 for predicate in bounds.predicates {
575 // Note: We can't use `to_opt_poly_trait_ref` here as `predicate`
576 // may contain unbound variables. We therefore do this manually.
578 // FIXME(lcnr): Find out why exactly this is the case :)
579 if let ty::PredicateKind::Trait(pred, _) = predicate
580 .ignore_quantifiers_with_unbound_vars(self.tcx())
584 let trait_ref = ty::Binder::bind(pred.trait_ref);
585 // Don't print +Sized, but rather +?Sized if absent.
586 if Some(trait_ref.def_id()) == self.tcx().lang_items().sized_trait() {
592 write("{}", if first { " " } else { "+" }),
593 print(trait_ref.print_only_trait_path())
599 p!(write("{}?Sized", if first { " " } else { "+" }));
606 ty::Str => p!(write("str")),
607 ty::Generator(did, substs, movability) => {
609 hir::Movability::Movable => p!(write("[generator")),
610 hir::Movability::Static => p!(write("[static generator")),
613 // FIXME(eddyb) should use `def_span`.
614 if let Some(did) = did.as_local() {
615 let hir_id = self.tcx().hir().as_local_hir_id(did);
616 let span = self.tcx().hir().span(hir_id);
617 p!(write("@{}", self.tcx().sess.source_map().span_to_string(span)));
619 if substs.as_generator().is_valid() {
620 let upvar_tys = substs.as_generator().upvar_tys();
622 for (&var_id, upvar_ty) in self
624 .upvars_mentioned(did)
627 .flat_map(|v| v.keys())
630 p!(write("{}{}:", sep, self.tcx().hir().name(var_id)), print(upvar_ty));
635 p!(write("@{}", self.tcx().def_path_str(did)));
637 if substs.as_generator().is_valid() {
638 let upvar_tys = substs.as_generator().upvar_tys();
640 for (index, upvar_ty) in upvar_tys.enumerate() {
641 p!(write("{}{}:", sep, index), print(upvar_ty));
647 if substs.as_generator().is_valid() {
648 p!(write(" "), print(substs.as_generator().witness()));
653 ty::GeneratorWitness(types) => {
654 p!(in_binder(&types));
656 ty::Closure(did, substs) => {
657 p!(write("[closure"));
659 // FIXME(eddyb) should use `def_span`.
660 if let Some(did) = did.as_local() {
661 let hir_id = self.tcx().hir().as_local_hir_id(did);
662 if self.tcx().sess.opts.debugging_opts.span_free_formats {
663 p!(write("@"), print_def_path(did.to_def_id(), substs));
665 let span = self.tcx().hir().span(hir_id);
666 p!(write("@{}", self.tcx().sess.source_map().span_to_string(span)));
669 if substs.as_closure().is_valid() {
670 let upvar_tys = substs.as_closure().upvar_tys();
672 for (&var_id, upvar_ty) in self
674 .upvars_mentioned(did)
677 .flat_map(|v| v.keys())
680 p!(write("{}{}:", sep, self.tcx().hir().name(var_id)), print(upvar_ty));
685 p!(write("@{}", self.tcx().def_path_str(did)));
687 if substs.as_closure().is_valid() {
688 let upvar_tys = substs.as_closure().upvar_tys();
690 for (index, upvar_ty) in upvar_tys.enumerate() {
691 p!(write("{}{}:", sep, index), print(upvar_ty));
697 if self.tcx().sess.verbose() && substs.as_closure().is_valid() {
698 p!(write(" closure_kind_ty="), print(substs.as_closure().kind_ty()));
700 write(" closure_sig_as_fn_ptr_ty="),
701 print(substs.as_closure().sig_as_fn_ptr_ty())
707 ty::Array(ty, sz) => {
708 p!(write("["), print(ty), write("; "));
709 if self.tcx().sess.verbose() {
710 p!(write("{:?}", sz));
711 } else if let ty::ConstKind::Unevaluated(..) = sz.val {
712 // Do not try to evaluate unevaluated constants. If we are const evaluating an
713 // array length anon const, rustc will (with debug assertions) print the
714 // constant's path. Which will end up here again.
716 } else if let Some(n) = sz.val.try_to_bits(self.tcx().data_layout.pointer_size) {
718 } else if let ty::ConstKind::Param(param) = sz.val {
719 p!(write("{}", param));
725 ty::Slice(ty) => p!(write("["), print(ty), write("]")),
731 fn pretty_print_bound_var(
733 debruijn: ty::DebruijnIndex,
735 ) -> Result<(), Self::Error> {
736 if debruijn == ty::INNERMOST {
737 write!(self, "^{}", var.index())
739 write!(self, "^{}_{}", debruijn.index(), var.index())
743 fn infer_ty_name(&self, _: ty::TyVid) -> Option<String> {
747 fn pretty_print_dyn_existential(
749 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
750 ) -> Result<Self::DynExistential, Self::Error> {
751 define_scoped_cx!(self);
753 // Generate the main trait ref, including associated types.
754 let mut first = true;
756 if let Some(principal) = predicates.principal() {
757 p!(print_def_path(principal.def_id, &[]));
759 let mut resugared = false;
761 // Special-case `Fn(...) -> ...` and resugar it.
762 let fn_trait_kind = self.tcx().fn_trait_kind_from_lang_item(principal.def_id);
763 if !self.tcx().sess.verbose() && fn_trait_kind.is_some() {
764 if let ty::Tuple(ref args) = principal.substs.type_at(0).kind {
765 let mut projections = predicates.projection_bounds();
766 if let (Some(proj), None) = (projections.next(), projections.next()) {
767 let tys: Vec<_> = args.iter().map(|k| k.expect_ty()).collect();
768 p!(pretty_fn_sig(&tys, false, proj.ty));
774 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
775 // in order to place the projections inside the `<...>`.
777 // Use a type that can't appear in defaults of type parameters.
778 let dummy_self = self.tcx().mk_ty_infer(ty::FreshTy(0));
779 let principal = principal.with_self_ty(self.tcx(), dummy_self);
781 let args = self.generic_args_to_print(
782 self.tcx().generics_of(principal.def_id),
786 // Don't print `'_` if there's no unerased regions.
787 let print_regions = args.iter().any(|arg| match arg.unpack() {
788 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
791 let mut args = args.iter().cloned().filter(|arg| match arg.unpack() {
792 GenericArgKind::Lifetime(_) => print_regions,
795 let mut projections = predicates.projection_bounds();
797 let arg0 = args.next();
798 let projection0 = projections.next();
799 if arg0.is_some() || projection0.is_some() {
800 let args = arg0.into_iter().chain(args);
801 let projections = projection0.into_iter().chain(projections);
803 p!(generic_delimiters(|mut cx| {
804 cx = cx.comma_sep(args)?;
805 if arg0.is_some() && projection0.is_some() {
808 cx.comma_sep(projections)
816 // FIXME(eddyb) avoid printing twice (needed to ensure
817 // that the auto traits are sorted *and* printed via cx).
818 let mut auto_traits: Vec<_> =
819 predicates.auto_traits().map(|did| (self.tcx().def_path_str(did), did)).collect();
821 // The auto traits come ordered by `DefPathHash`. While
822 // `DefPathHash` is *stable* in the sense that it depends on
823 // neither the host nor the phase of the moon, it depends
824 // "pseudorandomly" on the compiler version and the target.
826 // To avoid that causing instabilities in compiletest
827 // output, sort the auto-traits alphabetically.
830 for (_, def_id) in auto_traits {
836 p!(print_def_path(def_id, &[]));
847 ) -> Result<Self, Self::Error> {
848 define_scoped_cx!(self);
850 p!(write("("), comma_sep(inputs.iter().copied()));
852 if !inputs.is_empty() {
858 if !output.is_unit() {
859 p!(write(" -> "), print(output));
865 fn pretty_print_const(
867 ct: &'tcx ty::Const<'tcx>,
869 ) -> Result<Self::Const, Self::Error> {
870 define_scoped_cx!(self);
872 if self.tcx().sess.verbose() {
873 p!(write("Const({:?}: {:?})", ct.val, ct.ty));
877 macro_rules! print_underscore {
880 self = self.typed_value(
885 |this| this.print_type(ct.ty),
895 ty::ConstKind::Unevaluated(def, substs, promoted) => {
896 if let Some(promoted) = promoted {
897 p!(print_value_path(def.did, substs));
898 p!(write("::{:?}", promoted));
900 match self.tcx().def_kind(def.did) {
901 DefKind::Static | DefKind::Const | DefKind::AssocConst => {
902 p!(print_value_path(def.did, substs))
906 let span = self.tcx().def_span(def.did);
907 if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span)
909 p!(write("{}", snip))
920 ty::ConstKind::Infer(..) => print_underscore!(),
921 ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)),
922 ty::ConstKind::Value(value) => {
923 return self.pretty_print_const_value(value, ct.ty, print_ty);
926 ty::ConstKind::Bound(debruijn, bound_var) => {
927 self.pretty_print_bound_var(debruijn, bound_var)?
929 ty::ConstKind::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
930 ty::ConstKind::Error(_) => p!(write("[const error]")),
935 fn pretty_print_const_scalar(
940 ) -> Result<Self::Const, Self::Error> {
941 define_scoped_cx!(self);
943 match (scalar, &ty.kind) {
944 // Byte strings (&[u8; N])
952 ty::TyS { kind: ty::Uint(ast::UintTy::U8), .. },
955 ty::ConstKind::Value(ConstValue::Scalar(Scalar::Raw {
966 ) => match self.tcx().get_global_alloc(ptr.alloc_id) {
967 Some(GlobalAlloc::Memory(alloc)) => {
968 if let Ok(byte_str) = alloc.get_bytes(&self.tcx(), ptr, Size::from_bytes(*data))
970 p!(pretty_print_byte_str(byte_str))
972 p!(write("<too short allocation>"))
975 // FIXME: for statics and functions, we could in principle print more detail.
976 Some(GlobalAlloc::Static(def_id)) => p!(write("<static({:?})>", def_id)),
977 Some(GlobalAlloc::Function(_)) => p!(write("<function>")),
978 None => p!(write("<dangling pointer>")),
981 (Scalar::Raw { data: 0, .. }, ty::Bool) => p!(write("false")),
982 (Scalar::Raw { data: 1, .. }, ty::Bool) => p!(write("true")),
984 (Scalar::Raw { data, .. }, ty::Float(ast::FloatTy::F32)) => {
985 p!(write("{}f32", Single::from_bits(data)))
987 (Scalar::Raw { data, .. }, ty::Float(ast::FloatTy::F64)) => {
988 p!(write("{}f64", Double::from_bits(data)))
991 (Scalar::Raw { data, .. }, ty::Uint(ui)) => {
992 let size = Integer::from_attr(&self.tcx(), UnsignedInt(*ui)).size();
993 let int = ConstInt::new(data, size, false, ty.is_ptr_sized_integral());
994 if print_ty { p!(write("{:#?}", int)) } else { p!(write("{:?}", int)) }
996 (Scalar::Raw { data, .. }, ty::Int(i)) => {
997 let size = Integer::from_attr(&self.tcx(), SignedInt(*i)).size();
998 let int = ConstInt::new(data, size, true, ty.is_ptr_sized_integral());
999 if print_ty { p!(write("{:#?}", int)) } else { p!(write("{:?}", int)) }
1002 (Scalar::Raw { data, .. }, ty::Char) if char::from_u32(data as u32).is_some() => {
1003 p!(write("{:?}", char::from_u32(data as u32).unwrap()))
1006 (Scalar::Raw { data, .. }, ty::RawPtr(_)) => {
1007 self = self.typed_value(
1009 write!(this, "0x{:x}", data)?;
1012 |this| this.print_type(ty),
1016 (Scalar::Ptr(ptr), ty::FnPtr(_)) => {
1017 // FIXME: this can ICE when the ptr is dangling or points to a non-function.
1018 // We should probably have a helper method to share code with the "Byte strings"
1019 // printing above (which also has to handle pointers to all sorts of things).
1020 let instance = self.tcx().global_alloc(ptr.alloc_id).unwrap_fn();
1021 self = self.typed_value(
1022 |this| this.print_value_path(instance.def_id(), instance.substs),
1023 |this| this.print_type(ty),
1027 // For function type zsts just printing the path is enough
1028 (Scalar::Raw { size: 0, .. }, ty::FnDef(d, s)) => p!(print_value_path(*d, s)),
1029 // Nontrivial types with scalar bit representation
1030 (Scalar::Raw { data, size }, _) => {
1031 let print = |mut this: Self| {
1033 write!(this, "transmute(())")?;
1035 write!(this, "transmute(0x{:01$x})", data, size as usize * 2)?;
1039 self = if print_ty {
1040 self.typed_value(print, |this| this.print_type(ty), ": ")?
1045 // Any pointer values not covered by a branch above
1046 (Scalar::Ptr(p), _) => {
1047 self = self.pretty_print_const_pointer(p, ty, print_ty)?;
1053 /// This is overridden for MIR printing because we only want to hide alloc ids from users, not
1054 /// from MIR where it is actually useful.
1055 fn pretty_print_const_pointer(
1060 ) -> Result<Self::Const, Self::Error> {
1064 this.write_str("&_")?;
1067 |this| this.print_type(ty),
1071 self.write_str("&_")?;
1076 fn pretty_print_byte_str(mut self, byte_str: &'tcx [u8]) -> Result<Self::Const, Self::Error> {
1077 define_scoped_cx!(self);
1079 for &c in byte_str {
1080 for e in std::ascii::escape_default(c) {
1081 self.write_char(e as char)?;
1088 fn pretty_print_const_value(
1090 ct: ConstValue<'tcx>,
1093 ) -> Result<Self::Const, Self::Error> {
1094 define_scoped_cx!(self);
1096 if self.tcx().sess.verbose() {
1097 p!(write("ConstValue({:?}: ", ct), print(ty), write(")"));
1101 let u8_type = self.tcx().types.u8;
1103 match (ct, &ty.kind) {
1104 // Byte/string slices, printed as (byte) string literals.
1106 ConstValue::Slice { data, start, end },
1107 ty::Ref(_, ty::TyS { kind: ty::Slice(t), .. }, _),
1108 ) if *t == u8_type => {
1109 // The `inspect` here is okay since we checked the bounds, and there are
1110 // no relocations (we have an active slice reference here). We don't use
1111 // this result to affect interpreter execution.
1112 let byte_str = data.inspect_with_undef_and_ptr_outside_interpreter(start..end);
1113 self.pretty_print_byte_str(byte_str)
1116 ConstValue::Slice { data, start, end },
1117 ty::Ref(_, ty::TyS { kind: ty::Str, .. }, _),
1119 // The `inspect` here is okay since we checked the bounds, and there are no
1120 // relocations (we have an active `str` reference here). We don't use this
1121 // result to affect interpreter execution.
1122 let slice = data.inspect_with_undef_and_ptr_outside_interpreter(start..end);
1123 let s = ::std::str::from_utf8(slice).expect("non utf8 str from miri");
1124 p!(write("{:?}", s));
1127 (ConstValue::ByRef { alloc, offset }, ty::Array(t, n)) if *t == u8_type => {
1128 let n = n.val.try_to_bits(self.tcx().data_layout.pointer_size).unwrap();
1129 // cast is ok because we already checked for pointer size (32 or 64 bit) above
1130 let n = Size::from_bytes(n);
1131 let ptr = Pointer::new(AllocId(0), offset);
1133 let byte_str = alloc.get_bytes(&self.tcx(), ptr, n).unwrap();
1135 p!(pretty_print_byte_str(byte_str));
1139 // Aggregates, printed as array/tuple/struct/variant construction syntax.
1141 // NB: the `has_param_types_or_consts` check ensures that we can use
1142 // the `destructure_const` query with an empty `ty::ParamEnv` without
1143 // introducing ICEs (e.g. via `layout_of`) from missing bounds.
1144 // E.g. `transmute([0usize; 2]): (u8, *mut T)` needs to know `T: Sized`
1145 // to be able to destructure the tuple into `(0u8, *mut T)
1147 // FIXME(eddyb) for `--emit=mir`/`-Z dump-mir`, we should provide the
1148 // correct `ty::ParamEnv` to allow printing *all* constant values.
1149 (_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) if !ty.has_param_types_or_consts() => {
1150 let contents = self.tcx().destructure_const(
1151 ty::ParamEnv::reveal_all()
1152 .and(self.tcx().mk_const(ty::Const { val: ty::ConstKind::Value(ct), ty })),
1154 let fields = contents.fields.iter().copied();
1158 p!(write("["), comma_sep(fields), write("]"));
1161 p!(write("("), comma_sep(fields));
1162 if contents.fields.len() == 1 {
1167 ty::Adt(def, substs) if def.variants.is_empty() => {
1168 p!(print_value_path(def.did, substs));
1170 ty::Adt(def, substs) => {
1172 contents.variant.expect("destructed const of adt without variant id");
1173 let variant_def = &def.variants[variant_id];
1174 p!(print_value_path(variant_def.def_id, substs));
1176 match variant_def.ctor_kind {
1177 CtorKind::Const => {}
1179 p!(write("("), comma_sep(fields), write(")"));
1181 CtorKind::Fictive => {
1183 let mut first = true;
1184 for (field_def, field) in variant_def.fields.iter().zip(fields) {
1188 p!(write("{}: ", field_def.ident), print(field));
1195 _ => unreachable!(),
1201 (ConstValue::Scalar(scalar), _) => self.pretty_print_const_scalar(scalar, ty, print_ty),
1203 // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
1204 // their fields instead of just dumping the memory.
1207 p!(write("{:?}", ct));
1209 p!(write(": "), print(ty));
1217 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
1218 pub struct FmtPrinter<'a, 'tcx, F>(Box<FmtPrinterData<'a, 'tcx, F>>);
1220 pub struct FmtPrinterData<'a, 'tcx, F> {
1226 pub print_alloc_ids: bool,
1228 used_region_names: FxHashSet<Symbol>,
1229 region_index: usize,
1230 binder_depth: usize,
1232 pub region_highlight_mode: RegionHighlightMode,
1234 pub name_resolver: Option<Box<&'a dyn Fn(ty::sty::TyVid) -> Option<String>>>,
1237 impl<F> Deref for FmtPrinter<'a, 'tcx, F> {
1238 type Target = FmtPrinterData<'a, 'tcx, F>;
1239 fn deref(&self) -> &Self::Target {
1244 impl<F> DerefMut for FmtPrinter<'_, '_, F> {
1245 fn deref_mut(&mut self) -> &mut Self::Target {
1250 impl<F> FmtPrinter<'a, 'tcx, F> {
1251 pub fn new(tcx: TyCtxt<'tcx>, fmt: F, ns: Namespace) -> Self {
1252 FmtPrinter(Box::new(FmtPrinterData {
1256 in_value: ns == Namespace::ValueNS,
1257 print_alloc_ids: false,
1258 used_region_names: Default::default(),
1261 region_highlight_mode: RegionHighlightMode::default(),
1262 name_resolver: None,
1267 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1268 // (but also some things just print a `DefId` generally so maybe we need this?)
1269 fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
1270 match tcx.def_key(def_id).disambiguated_data.data {
1271 DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::ImplTrait => {
1275 DefPathData::ValueNs(..)
1276 | DefPathData::AnonConst
1277 | DefPathData::ClosureExpr
1278 | DefPathData::Ctor => Namespace::ValueNS,
1280 DefPathData::MacroNs(..) => Namespace::MacroNS,
1282 _ => Namespace::TypeNS,
1287 /// Returns a string identifying this `DefId`. This string is
1288 /// suitable for user output.
1289 pub fn def_path_str(self, def_id: DefId) -> String {
1290 self.def_path_str_with_substs(def_id, &[])
1293 pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1294 let ns = guess_def_namespace(self, def_id);
1295 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1296 let mut s = String::new();
1297 let _ = FmtPrinter::new(self, &mut s, ns).print_def_path(def_id, substs);
1302 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, F> {
1303 fn write_str(&mut self, s: &str) -> fmt::Result {
1304 self.fmt.write_str(s)
1308 impl<F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
1309 type Error = fmt::Error;
1314 type DynExistential = Self;
1317 fn tcx(&'a self) -> TyCtxt<'tcx> {
1324 substs: &'tcx [GenericArg<'tcx>],
1325 ) -> Result<Self::Path, Self::Error> {
1326 define_scoped_cx!(self);
1328 if substs.is_empty() {
1329 match self.try_print_visible_def_path(def_id)? {
1330 (cx, true) => return Ok(cx),
1331 (cx, false) => self = cx,
1335 let key = self.tcx.def_key(def_id);
1336 if let DefPathData::Impl = key.disambiguated_data.data {
1337 // Always use types for non-local impls, where types are always
1338 // available, and filename/line-number is mostly uninteresting.
1339 let use_types = !def_id.is_local() || {
1340 // Otherwise, use filename/line-number if forced.
1341 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1346 // If no type info is available, fall back to
1347 // pretty printing some span information. This should
1348 // only occur very early in the compiler pipeline.
1349 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1350 let span = self.tcx.def_span(def_id);
1352 self = self.print_def_path(parent_def_id, &[])?;
1354 // HACK(eddyb) copy of `path_append` to avoid
1355 // constructing a `DisambiguatedDefPathData`.
1356 if !self.empty_path {
1357 write!(self, "::")?;
1359 write!(self, "<impl at {}>", self.tcx.sess.source_map().span_to_string(span))?;
1360 self.empty_path = false;
1366 self.default_print_def_path(def_id, substs)
1369 fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
1370 self.pretty_print_region(region)
1373 fn print_type(self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1374 self.pretty_print_type(ty)
1377 fn print_dyn_existential(
1379 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1380 ) -> Result<Self::DynExistential, Self::Error> {
1381 self.pretty_print_dyn_existential(predicates)
1384 fn print_const(self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1385 self.pretty_print_const(ct, true)
1388 fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1389 self.empty_path = true;
1390 if cnum == LOCAL_CRATE {
1391 if self.tcx.sess.rust_2018() {
1392 // We add the `crate::` keyword on Rust 2018, only when desired.
1393 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1394 write!(self, "{}", kw::Crate)?;
1395 self.empty_path = false;
1399 write!(self, "{}", self.tcx.crate_name(cnum))?;
1400 self.empty_path = false;
1408 trait_ref: Option<ty::TraitRef<'tcx>>,
1409 ) -> Result<Self::Path, Self::Error> {
1410 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1411 self.empty_path = false;
1415 fn path_append_impl(
1417 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1418 _disambiguated_data: &DisambiguatedDefPathData,
1420 trait_ref: Option<ty::TraitRef<'tcx>>,
1421 ) -> Result<Self::Path, Self::Error> {
1422 self = self.pretty_path_append_impl(
1424 cx = print_prefix(cx)?;
1434 self.empty_path = false;
1440 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1441 disambiguated_data: &DisambiguatedDefPathData,
1442 ) -> Result<Self::Path, Self::Error> {
1443 self = print_prefix(self)?;
1445 // Skip `::{{constructor}}` on tuple/unit structs.
1446 if let DefPathData::Ctor = disambiguated_data.data {
1450 // FIXME(eddyb) `name` should never be empty, but it
1451 // currently is for `extern { ... }` "foreign modules".
1452 let name = disambiguated_data.data.as_symbol();
1453 if name != kw::Invalid {
1454 if !self.empty_path {
1455 write!(self, "::")?;
1457 if Ident::with_dummy_span(name).is_raw_guess() {
1458 write!(self, "r#")?;
1460 write!(self, "{}", name)?;
1462 // FIXME(eddyb) this will print e.g. `{{closure}}#3`, but it
1463 // might be nicer to use something else, e.g. `{closure#3}`.
1464 let dis = disambiguated_data.disambiguator;
1465 let print_dis = disambiguated_data.data.get_opt_name().is_none()
1466 || dis != 0 && self.tcx.sess.verbose();
1468 write!(self, "#{}", dis)?;
1471 self.empty_path = false;
1477 fn path_generic_args(
1479 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1480 args: &[GenericArg<'tcx>],
1481 ) -> Result<Self::Path, Self::Error> {
1482 self = print_prefix(self)?;
1484 // Don't print `'_` if there's no unerased regions.
1485 let print_regions = args.iter().any(|arg| match arg.unpack() {
1486 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
1489 let args = args.iter().cloned().filter(|arg| match arg.unpack() {
1490 GenericArgKind::Lifetime(_) => print_regions,
1494 if args.clone().next().is_some() {
1496 write!(self, "::")?;
1498 self.generic_delimiters(|cx| cx.comma_sep(args))
1505 impl<F: fmt::Write> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx, F> {
1506 fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> {
1507 self.0.name_resolver.as_ref().and_then(|func| func(id))
1510 fn print_value_path(
1513 substs: &'tcx [GenericArg<'tcx>],
1514 ) -> Result<Self::Path, Self::Error> {
1515 let was_in_value = std::mem::replace(&mut self.in_value, true);
1516 self = self.print_def_path(def_id, substs)?;
1517 self.in_value = was_in_value;
1522 fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
1524 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1526 self.pretty_in_binder(value)
1531 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1532 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
1534 ) -> Result<Self::Const, Self::Error> {
1535 self.write_str("{")?;
1537 self.write_str(conversion)?;
1538 let was_in_value = std::mem::replace(&mut self.in_value, false);
1540 self.in_value = was_in_value;
1541 self.write_str("}")?;
1545 fn generic_delimiters(
1547 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1548 ) -> Result<Self, Self::Error> {
1551 let was_in_value = std::mem::replace(&mut self.in_value, false);
1552 let mut inner = f(self)?;
1553 inner.in_value = was_in_value;
1555 write!(inner, ">")?;
1559 fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool {
1560 let highlight = self.region_highlight_mode;
1561 if highlight.region_highlighted(region).is_some() {
1565 if self.tcx.sess.verbose() {
1569 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1572 ty::ReEarlyBound(ref data) => {
1573 data.name != kw::Invalid && data.name != kw::UnderscoreLifetime
1576 ty::ReLateBound(_, br)
1577 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1578 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1579 if let ty::BrNamed(_, name) = br {
1580 if name != kw::Invalid && name != kw::UnderscoreLifetime {
1585 if let Some((region, _)) = highlight.highlight_bound_region {
1594 ty::ReVar(_) if identify_regions => true,
1596 ty::ReVar(_) | ty::ReErased => false,
1598 ty::ReStatic | ty::ReEmpty(_) => true,
1602 fn pretty_print_const_pointer(
1607 ) -> Result<Self::Const, Self::Error> {
1608 let print = |mut this: Self| {
1609 define_scoped_cx!(this);
1610 if this.print_alloc_ids {
1611 p!(write("{:?}", p));
1618 self.typed_value(print, |this| this.print_type(ty), ": ")
1625 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1626 impl<F: fmt::Write> FmtPrinter<'_, '_, F> {
1627 pub fn pretty_print_region(mut self, region: ty::Region<'_>) -> Result<Self, fmt::Error> {
1628 define_scoped_cx!(self);
1630 // Watch out for region highlights.
1631 let highlight = self.region_highlight_mode;
1632 if let Some(n) = highlight.region_highlighted(region) {
1633 p!(write("'{}", n));
1637 if self.tcx.sess.verbose() {
1638 p!(write("{:?}", region));
1642 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1644 // These printouts are concise. They do not contain all the information
1645 // the user might want to diagnose an error, but there is basically no way
1646 // to fit that into a short string. Hence the recommendation to use
1647 // `explain_region()` or `note_and_explain_region()`.
1649 ty::ReEarlyBound(ref data) => {
1650 if data.name != kw::Invalid {
1651 p!(write("{}", data.name));
1655 ty::ReLateBound(_, br)
1656 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1657 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1658 if let ty::BrNamed(_, name) = br {
1659 if name != kw::Invalid && name != kw::UnderscoreLifetime {
1660 p!(write("{}", name));
1665 if let Some((region, counter)) = highlight.highlight_bound_region {
1667 p!(write("'{}", counter));
1672 ty::ReVar(region_vid) if identify_regions => {
1673 p!(write("{:?}", region_vid));
1679 p!(write("'static"));
1682 ty::ReEmpty(ty::UniverseIndex::ROOT) => {
1683 p!(write("'<empty>"));
1686 ty::ReEmpty(ui) => {
1687 p!(write("'<empty:{:?}>", ui));
1698 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1699 // `region_index` and `used_region_names`.
1700 impl<F: fmt::Write> FmtPrinter<'_, 'tcx, F> {
1701 pub fn name_all_regions<T>(
1703 value: &ty::Binder<T>,
1704 ) -> Result<(Self, (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)), fmt::Error>
1706 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1708 fn name_by_region_index(index: usize) -> Symbol {
1710 0 => Symbol::intern("'r"),
1711 1 => Symbol::intern("'s"),
1712 i => Symbol::intern(&format!("'t{}", i - 2)),
1716 // Replace any anonymous late-bound regions with named
1717 // variants, using new unique identifiers, so that we can
1718 // clearly differentiate between named and unnamed regions in
1719 // the output. We'll probably want to tweak this over time to
1720 // decide just how much information to give.
1721 if self.binder_depth == 0 {
1722 self.prepare_late_bound_region_info(value);
1725 let mut empty = true;
1726 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1739 define_scoped_cx!(self);
1741 let mut region_index = self.region_index;
1742 let new_value = self.tcx.replace_late_bound_regions(value, |br| {
1743 let _ = start_or_continue(&mut self, "for<", ", ");
1745 ty::BrNamed(_, name) => {
1746 let _ = write!(self, "{}", name);
1749 ty::BrAnon(_) | ty::BrEnv => {
1751 let name = name_by_region_index(region_index);
1753 if !self.used_region_names.contains(&name) {
1757 let _ = write!(self, "{}", name);
1758 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1761 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
1763 start_or_continue(&mut self, "", "> ")?;
1765 self.binder_depth += 1;
1766 self.region_index = region_index;
1767 Ok((self, new_value))
1770 pub fn pretty_in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, fmt::Error>
1772 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1774 let old_region_index = self.region_index;
1775 let (new, new_value) = self.name_all_regions(value)?;
1776 let mut inner = new_value.0.print(new)?;
1777 inner.region_index = old_region_index;
1778 inner.binder_depth -= 1;
1782 fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
1784 T: TypeFoldable<'tcx>,
1786 struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet<Symbol>);
1787 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> {
1788 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
1789 if let ty::ReLateBound(_, ty::BrNamed(_, name)) = *r {
1790 self.0.insert(name);
1792 r.super_visit_with(self)
1796 self.used_region_names.clear();
1797 let mut collector = LateBoundRegionNameCollector(&mut self.used_region_names);
1798 value.visit_with(&mut collector);
1799 self.region_index = 0;
1803 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<T>
1805 T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
1808 type Error = P::Error;
1809 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
1814 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
1816 T: Print<'tcx, P, Output = P, Error = P::Error>,
1817 U: Print<'tcx, P, Output = P, Error = P::Error>,
1820 type Error = P::Error;
1821 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
1822 define_scoped_cx!(cx);
1823 p!(print(self.0), write(": "), print(self.1));
1828 macro_rules! forward_display_to_print {
1830 $(impl fmt::Display for $ty {
1831 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1832 ty::tls::with(|tcx| {
1834 .expect("could not lift for printing")
1835 .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1843 macro_rules! define_print_and_forward_display {
1844 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
1845 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
1847 type Error = fmt::Error;
1848 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
1849 #[allow(unused_mut)]
1851 define_scoped_cx!($cx);
1853 #[allow(unreachable_code)]
1858 forward_display_to_print!($($ty),+);
1862 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
1863 impl fmt::Display for ty::RegionKind {
1864 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1865 ty::tls::with(|tcx| {
1866 self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1872 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
1873 /// the trait path. That is, it will print `Trait<U>` instead of
1874 /// `<T as Trait<U>>`.
1875 #[derive(Copy, Clone, TypeFoldable, Lift)]
1876 pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
1878 impl fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
1879 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1880 fmt::Display::fmt(self, f)
1884 impl ty::TraitRef<'tcx> {
1885 pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
1886 TraitRefPrintOnlyTraitPath(self)
1890 impl ty::Binder<ty::TraitRef<'tcx>> {
1891 pub fn print_only_trait_path(self) -> ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>> {
1892 self.map_bound(|tr| tr.print_only_trait_path())
1896 forward_display_to_print! {
1898 &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1899 &'tcx ty::Const<'tcx>,
1901 // HACK(eddyb) these are exhaustive instead of generic,
1902 // because `for<'tcx>` isn't possible yet.
1903 ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
1904 ty::Binder<ty::TraitRef<'tcx>>,
1905 ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>>,
1906 ty::Binder<ty::FnSig<'tcx>>,
1907 ty::Binder<ty::TraitPredicate<'tcx>>,
1908 ty::Binder<ty::SubtypePredicate<'tcx>>,
1909 ty::Binder<ty::ProjectionPredicate<'tcx>>,
1910 ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1911 ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
1913 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1914 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1917 define_print_and_forward_display! {
1920 &'tcx ty::List<Ty<'tcx>> {
1921 p!(write("{{"), comma_sep(self.iter()), write("}}"))
1924 ty::TypeAndMut<'tcx> {
1925 p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
1928 ty::ExistentialTraitRef<'tcx> {
1929 // Use a type that can't appear in defaults of type parameters.
1930 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1931 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
1932 p!(print(trait_ref.print_only_trait_path()))
1935 ty::ExistentialProjection<'tcx> {
1936 let name = cx.tcx().associated_item(self.item_def_id).ident;
1937 p!(write("{} = ", name), print(self.ty))
1940 ty::ExistentialPredicate<'tcx> {
1942 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
1943 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
1944 ty::ExistentialPredicate::AutoTrait(def_id) => {
1945 p!(print_def_path(def_id, &[]));
1951 p!(write("{}", self.unsafety.prefix_str()));
1953 if self.abi != Abi::Rust {
1954 p!(write("extern {} ", self.abi));
1957 p!(write("fn"), pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
1961 if cx.tcx().sess.verbose() {
1962 p!(write("{:?}", self));
1966 ty::TyVar(_) => p!(write("_")),
1967 ty::IntVar(_) => p!(write("{}", "{integer}")),
1968 ty::FloatVar(_) => p!(write("{}", "{float}")),
1969 ty::FreshTy(v) => p!(write("FreshTy({})", v)),
1970 ty::FreshIntTy(v) => p!(write("FreshIntTy({})", v)),
1971 ty::FreshFloatTy(v) => p!(write("FreshFloatTy({})", v))
1975 ty::TraitRef<'tcx> {
1976 p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
1979 TraitRefPrintOnlyTraitPath<'tcx> {
1980 p!(print_def_path(self.0.def_id, self.0.substs));
1984 p!(write("{}", self.name))
1988 p!(write("{}", self.name))
1991 ty::SubtypePredicate<'tcx> {
1992 p!(print(self.a), write(" <: "), print(self.b))
1995 ty::TraitPredicate<'tcx> {
1996 p!(print(self.trait_ref.self_ty()), write(": "),
1997 print(self.trait_ref.print_only_trait_path()))
2000 ty::ProjectionPredicate<'tcx> {
2001 p!(print(self.projection_ty), write(" == "), print(self.ty))
2004 ty::ProjectionTy<'tcx> {
2005 p!(print_def_path(self.item_def_id, self.substs));
2010 ty::ClosureKind::Fn => p!(write("Fn")),
2011 ty::ClosureKind::FnMut => p!(write("FnMut")),
2012 ty::ClosureKind::FnOnce => p!(write("FnOnce")),
2016 ty::Predicate<'tcx> {
2018 &ty::PredicateKind::Trait(ref data, constness) => {
2019 if let hir::Constness::Const = constness {
2020 p!(write("const "));
2024 ty::PredicateKind::Subtype(predicate) => p!(print(predicate)),
2025 ty::PredicateKind::RegionOutlives(predicate) => p!(print(predicate)),
2026 ty::PredicateKind::TypeOutlives(predicate) => p!(print(predicate)),
2027 ty::PredicateKind::Projection(predicate) => p!(print(predicate)),
2028 ty::PredicateKind::WellFormed(arg) => p!(print(arg), write(" well-formed")),
2029 &ty::PredicateKind::ObjectSafe(trait_def_id) => {
2030 p!(write("the trait `"),
2031 print_def_path(trait_def_id, &[]),
2032 write("` is object-safe"))
2034 &ty::PredicateKind::ClosureKind(closure_def_id, _closure_substs, kind) => {
2035 p!(write("the closure `"),
2036 print_value_path(closure_def_id, &[]),
2037 write("` implements the trait `{}`", kind))
2039 &ty::PredicateKind::ConstEvaluatable(def, substs) => {
2040 p!(write("the constant `"),
2041 print_value_path(def.did, substs),
2042 write("` can be evaluated"))
2044 ty::PredicateKind::ConstEquate(c1, c2) => {
2045 p!(write("the constant `"),
2047 write("` equals `"),
2051 ty::PredicateKind::ForAll(binder) => {
2058 match self.unpack() {
2059 GenericArgKind::Lifetime(lt) => p!(print(lt)),
2060 GenericArgKind::Type(ty) => p!(print(ty)),
2061 GenericArgKind::Const(ct) => p!(print(ct)),