2 use crate::hir::def::{Namespace, DefKind};
3 use crate::hir::map::{DefPathData, DisambiguatedDefPathData};
4 use crate::hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
5 use crate::middle::cstore::{ExternCrate, ExternCrateSource};
6 use crate::middle::region;
7 use crate::ty::{self, DefIdTree, ParamConst, Ty, TyCtxt, TypeFoldable};
8 use crate::ty::subst::{GenericArg, Subst, GenericArgKind};
9 use crate::ty::layout::{Integer, IntegerExt, Size};
10 use crate::mir::interpret::{ConstValue, sign_extend, Scalar, truncate};
12 use rustc_apfloat::ieee::{Double, Single};
13 use rustc_apfloat::Float;
14 use rustc_target::spec::abi::Abi;
16 use syntax::attr::{SignedInt, UnsignedInt};
17 use syntax::symbol::{kw, InternedString};
20 use std::fmt::{self, Write as _};
21 use std::ops::{Deref, DerefMut};
23 // `pretty` is a separate module only for organization.
27 (@write($($data:expr),+)) => {
28 write!(scoped_cx!(), $($data),+)?
30 (@print($x:expr)) => {
31 scoped_cx!() = $x.print(scoped_cx!())?
33 (@$method:ident($($arg:expr),*)) => {
34 scoped_cx!() = scoped_cx!().$method($($arg),*)?
36 ($($kind:ident $data:tt),+) => {{
40 macro_rules! define_scoped_cx {
42 #[allow(unused_macros)]
43 macro_rules! scoped_cx {
50 static FORCE_IMPL_FILENAME_LINE: Cell<bool> = Cell::new(false);
51 static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = Cell::new(false);
54 /// Force us to name impls with just the filename/line number. We
55 /// normally try to use types. But at some points, notably while printing
56 /// cycle errors, this can result in extra or suboptimal error output,
57 /// so this variable disables that check.
58 pub fn with_forced_impl_filename_line<F: FnOnce() -> R, R>(f: F) -> R {
59 FORCE_IMPL_FILENAME_LINE.with(|force| {
60 let old = force.get();
68 /// Adds the `crate::` prefix to paths where appropriate.
69 pub fn with_crate_prefix<F: FnOnce() -> R, R>(f: F) -> R {
70 SHOULD_PREFIX_WITH_CRATE.with(|flag| {
79 /// The "region highlights" are used to control region printing during
80 /// specific error messages. When a "region highlight" is enabled, it
81 /// gives an alternate way to print specific regions. For now, we
82 /// always print those regions using a number, so something like "`'0`".
84 /// Regions not selected by the region highlight mode are presently
86 #[derive(Copy, Clone, Default)]
87 pub struct RegionHighlightMode {
88 /// If enabled, when we see the selected region, use "`'N`"
89 /// instead of the ordinary behavior.
90 highlight_regions: [Option<(ty::RegionKind, usize)>; 3],
92 /// If enabled, when printing a "free region" that originated from
93 /// the given `ty::BoundRegion`, print it as "`'1`". Free regions that would ordinarily
94 /// have names print as normal.
96 /// This is used when you have a signature like `fn foo(x: &u32,
97 /// y: &'a u32)` and we want to give a name to the region of the
99 highlight_bound_region: Option<(ty::BoundRegion, usize)>,
102 impl RegionHighlightMode {
103 /// If `region` and `number` are both `Some`, invokes
104 /// `highlighting_region`.
105 pub fn maybe_highlighting_region(
107 region: Option<ty::Region<'_>>,
108 number: Option<usize>,
110 if let Some(k) = region {
111 if let Some(n) = number {
112 self.highlighting_region(k, n);
117 /// Highlights the region inference variable `vid` as `'N`.
118 pub fn highlighting_region(
120 region: ty::Region<'_>,
123 let num_slots = self.highlight_regions.len();
124 let first_avail_slot = self.highlight_regions.iter_mut()
125 .filter(|s| s.is_none())
129 "can only highlight {} placeholders at a time",
133 *first_avail_slot = Some((*region, number));
136 /// Convenience wrapper for `highlighting_region`.
137 pub fn highlighting_region_vid(
142 self.highlighting_region(&ty::ReVar(vid), number)
145 /// Returns `Some(n)` with the number to use for the given region, if any.
146 fn region_highlighted(&self, region: ty::Region<'_>) -> Option<usize> {
150 .filter_map(|h| match h {
151 Some((r, n)) if r == region => Some(*n),
157 /// Highlight the given bound region.
158 /// We can only highlight one bound region at a time. See
159 /// the field `highlight_bound_region` for more detailed notes.
160 pub fn highlighting_bound_region(
165 assert!(self.highlight_bound_region.is_none());
166 self.highlight_bound_region = Some((br, number));
170 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
171 pub trait PrettyPrinter<'tcx>:
178 DynExistential = Self,
182 /// Like `print_def_path` but for value paths.
186 substs: &'tcx [GenericArg<'tcx>],
187 ) -> Result<Self::Path, Self::Error> {
188 self.print_def_path(def_id, substs)
191 fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
193 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
195 value.skip_binder().print(self)
198 /// Prints comma-separated elements.
199 fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
201 T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
203 if let Some(first) = elems.next() {
204 self = first.print(self)?;
206 self.write_str(", ")?;
207 self = elem.print(self)?;
213 /// Prints `<...>` around what `f` prints.
214 fn generic_delimiters(
216 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
217 ) -> Result<Self, Self::Error>;
219 /// Returns `true` if the region should be printed in
220 /// optional positions, e.g., `&'a T` or `dyn Tr + 'b`.
221 /// This is typically the case for all non-`'_` regions.
222 fn region_should_not_be_omitted(
224 region: ty::Region<'_>,
227 // Defaults (should not be overriden):
229 /// If possible, this returns a global path resolving to `def_id` that is visible
230 /// from at least one local module, and returns `true`. If the crate defining `def_id` is
231 /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
232 fn try_print_visible_def_path(
235 ) -> Result<(Self, bool), Self::Error> {
236 let mut callers = Vec::new();
237 self.try_print_visible_def_path_recur(def_id, &mut callers)
240 /// Does the work of `try_print_visible_def_path`, building the
241 /// full definition path recursively before attempting to
242 /// post-process it into the valid and visible version that
243 /// accounts for re-exports.
245 /// This method should only be callled by itself or
246 /// `try_print_visible_def_path`.
248 /// `callers` is a chain of visible_parent's leading to `def_id`,
249 /// to support cycle detection during recursion.
250 fn try_print_visible_def_path_recur(
253 callers: &mut Vec<DefId>,
254 ) -> Result<(Self, bool), Self::Error> {
255 define_scoped_cx!(self);
257 debug!("try_print_visible_def_path: def_id={:?}", def_id);
259 // If `def_id` is a direct or injected extern crate, return the
260 // path to the crate followed by the path to the item within the crate.
261 if def_id.index == CRATE_DEF_INDEX {
262 let cnum = def_id.krate;
264 if cnum == LOCAL_CRATE {
265 return Ok((self.path_crate(cnum)?, true));
268 // In local mode, when we encounter a crate other than
269 // LOCAL_CRATE, execution proceeds in one of two ways:
271 // 1. For a direct dependency, where user added an
272 // `extern crate` manually, we put the `extern
273 // crate` as the parent. So you wind up with
274 // something relative to the current crate.
275 // 2. For an extern inferred from a path or an indirect crate,
276 // where there is no explicit `extern crate`, we just prepend
278 match self.tcx().extern_crate(def_id) {
280 src: ExternCrateSource::Extern(def_id),
281 dependency_of: LOCAL_CRATE,
285 debug!("try_print_visible_def_path: def_id={:?}", def_id);
286 return Ok((if !span.is_dummy() {
287 self.print_def_path(def_id, &[])?
289 self.path_crate(cnum)?
293 return Ok((self.path_crate(cnum)?, true));
299 if def_id.is_local() {
300 return Ok((self, false));
303 let visible_parent_map = self.tcx().visible_parent_map(LOCAL_CRATE);
305 let mut cur_def_key = self.tcx().def_key(def_id);
306 debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
308 // For a constructor, we want the name of its parent rather than <unnamed>.
309 match cur_def_key.disambiguated_data.data {
310 DefPathData::Ctor => {
313 index: cur_def_key.parent
314 .expect("`DefPathData::Ctor` / `VariantData` missing a parent"),
317 cur_def_key = self.tcx().def_key(parent);
322 let visible_parent = match visible_parent_map.get(&def_id).cloned() {
323 Some(parent) => parent,
324 None => return Ok((self, false)),
326 if callers.contains(&visible_parent) {
327 return Ok((self, false));
329 callers.push(visible_parent);
330 // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
331 // knowing ahead of time whether the entire path will succeed or not.
332 // To support printers that do not implement `PrettyPrinter`, a `Vec` or
333 // linked list on the stack would need to be built, before any printing.
334 match self.try_print_visible_def_path_recur(visible_parent, callers)? {
335 (cx, false) => return Ok((cx, false)),
336 (cx, true) => self = cx,
339 let actual_parent = self.tcx().parent(def_id);
341 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
342 visible_parent, actual_parent,
345 let mut data = cur_def_key.disambiguated_data.data;
347 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
348 data, visible_parent, actual_parent,
352 // In order to output a path that could actually be imported (valid and visible),
353 // we need to handle re-exports correctly.
355 // For example, take `std::os::unix::process::CommandExt`, this trait is actually
356 // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
358 // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is
359 // private so the "true" path to `CommandExt` isn't accessible.
361 // In this case, the `visible_parent_map` will look something like this:
363 // (child) -> (parent)
364 // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
365 // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
366 // `std::sys::unix::ext` -> `std::os`
368 // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
371 // When printing the path to `CommandExt` and looking at the `cur_def_key` that
372 // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
373 // to the parent - resulting in a mangled path like
374 // `std::os::ext::process::CommandExt`.
376 // Instead, we must detect that there was a re-export and instead print `unix`
377 // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
378 // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
379 // the visible parent (`std::os`). If these do not match, then we iterate over
380 // the children of the visible parent (as was done when computing
381 // `visible_parent_map`), looking for the specific child we currently have and then
382 // have access to the re-exported name.
383 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
384 let reexport = self.tcx().item_children(visible_parent)
386 .find(|child| child.res.def_id() == def_id)
387 .map(|child| child.ident.as_interned_str());
388 if let Some(reexport) = reexport {
392 // Re-exported `extern crate` (#43189).
393 DefPathData::CrateRoot => {
394 data = DefPathData::TypeNs(
395 self.tcx().original_crate_name(def_id.krate).as_interned_str(),
400 debug!("try_print_visible_def_path: data={:?}", data);
402 Ok((self.path_append(Ok, &DisambiguatedDefPathData {
408 fn pretty_path_qualified(
411 trait_ref: Option<ty::TraitRef<'tcx>>,
412 ) -> Result<Self::Path, Self::Error> {
413 if trait_ref.is_none() {
414 // Inherent impls. Try to print `Foo::bar` for an inherent
415 // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
416 // anything other than a simple path.
418 ty::Adt(..) | ty::Foreign(_) |
419 ty::Bool | ty::Char | ty::Str |
420 ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
421 return self_ty.print(self);
428 self.generic_delimiters(|mut cx| {
429 define_scoped_cx!(cx);
432 if let Some(trait_ref) = trait_ref {
433 p!(write(" as "), print(trait_ref));
439 fn pretty_path_append_impl(
441 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
443 trait_ref: Option<ty::TraitRef<'tcx>>,
444 ) -> Result<Self::Path, Self::Error> {
445 self = print_prefix(self)?;
447 self.generic_delimiters(|mut cx| {
448 define_scoped_cx!(cx);
451 if let Some(trait_ref) = trait_ref {
452 p!(print(trait_ref), write(" for "));
460 fn pretty_print_type(
463 ) -> Result<Self::Type, Self::Error> {
464 define_scoped_cx!(self);
467 ty::Bool => p!(write("bool")),
468 ty::Char => p!(write("char")),
469 ty::Int(t) => p!(write("{}", t.ty_to_string())),
470 ty::Uint(t) => p!(write("{}", t.ty_to_string())),
471 ty::Float(t) => p!(write("{}", t.ty_to_string())),
472 ty::RawPtr(ref tm) => {
473 p!(write("*{} ", match tm.mutbl {
474 hir::MutMutable => "mut",
475 hir::MutImmutable => "const",
479 ty::Ref(r, ty, mutbl) => {
481 if self.region_should_not_be_omitted(r) {
482 p!(print(r), write(" "));
484 p!(print(ty::TypeAndMut { ty, mutbl }))
486 ty::Never => p!(write("!")),
487 ty::Tuple(ref tys) => {
489 let mut tys = tys.iter();
490 if let Some(&ty) = tys.next() {
491 p!(print(ty), write(","));
492 if let Some(&ty) = tys.next() {
493 p!(write(" "), print(ty));
495 p!(write(", "), print(ty));
501 ty::FnDef(def_id, substs) => {
502 let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs);
503 p!(print(sig), write(" {{"), print_value_path(def_id, substs), write("}}"));
505 ty::FnPtr(ref bare_fn) => {
508 ty::Infer(infer_ty) => {
509 if let ty::TyVar(ty_vid) = infer_ty {
510 if let Some(name) = self.infer_ty_name(ty_vid) {
511 p!(write("{}", name))
513 p!(write("{}", infer_ty))
516 p!(write("{}", infer_ty))
519 ty::Error => p!(write("[type error]")),
520 ty::Param(ref param_ty) => p!(write("{}", param_ty)),
521 ty::Bound(debruijn, bound_ty) => {
522 match bound_ty.kind {
523 ty::BoundTyKind::Anon => {
524 if debruijn == ty::INNERMOST {
525 p!(write("^{}", bound_ty.var.index()))
527 p!(write("^{}_{}", debruijn.index(), bound_ty.var.index()))
531 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
534 ty::Adt(def, substs) => {
535 p!(print_def_path(def.did, substs));
537 ty::Dynamic(data, r) => {
538 let print_r = self.region_should_not_be_omitted(r);
542 p!(write("dyn "), print(data));
544 p!(write(" + "), print(r), write(")"));
547 ty::Foreign(def_id) => {
548 p!(print_def_path(def_id, &[]));
550 ty::Projection(ref data) => p!(print(data)),
551 ty::UnnormalizedProjection(ref data) => {
552 p!(write("Unnormalized("), print(data), write(")"))
554 ty::Placeholder(placeholder) => {
555 p!(write("Placeholder({:?})", placeholder))
557 ty::Opaque(def_id, substs) => {
558 // FIXME(eddyb) print this with `print_def_path`.
559 if self.tcx().sess.verbose() {
560 p!(write("Opaque({:?}, {:?})", def_id, substs));
564 let def_key = self.tcx().def_key(def_id);
565 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
566 p!(write("{}", name));
567 let mut substs = substs.iter();
568 // FIXME(eddyb) print this with `print_def_path`.
569 if let Some(first) = substs.next() {
572 for subst in substs {
573 p!(write(", "), print(subst));
579 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
580 // by looking up the projections associated with the def_id.
581 let bounds = self.tcx().predicates_of(def_id).instantiate(self.tcx(), substs);
583 let mut first = true;
584 let mut is_sized = false;
586 for predicate in bounds.predicates {
587 if let Some(trait_ref) = predicate.to_opt_poly_trait_ref() {
588 // Don't print +Sized, but rather +?Sized if absent.
589 if Some(trait_ref.def_id()) == self.tcx().lang_items().sized_trait() {
595 write("{}", if first { " " } else { "+" }),
601 p!(write("{}?Sized", if first { " " } else { "+" }));
606 ty::Str => p!(write("str")),
607 ty::Generator(did, substs, movability) => {
608 let upvar_tys = substs.as_generator().upvar_tys(did, self.tcx());
609 let witness = substs.as_generator().witness(did, self.tcx());
610 if movability == hir::GeneratorMovability::Movable {
611 p!(write("[generator"));
613 p!(write("[static generator"));
616 // FIXME(eddyb) should use `def_span`.
617 if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
618 p!(write("@{:?}", self.tcx().hir().span(hir_id)));
620 for (&var_id, upvar_ty) in self.tcx().upvars(did)
623 .flat_map(|v| v.keys())
629 self.tcx().hir().name(var_id)),
634 // Cross-crate closure types should only be
635 // visible in codegen bug reports, I imagine.
636 p!(write("@{:?}", did));
638 for (index, upvar_ty) in upvar_tys.enumerate() {
640 write("{}{}:", sep, index),
646 p!(write(" "), print(witness), write("]"))
648 ty::GeneratorWitness(types) => {
649 p!(in_binder(&types));
651 ty::Closure(did, substs) => {
652 let upvar_tys = substs.as_closure().upvar_tys(did, self.tcx());
653 p!(write("[closure"));
655 // FIXME(eddyb) should use `def_span`.
656 if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
657 if self.tcx().sess.opts.debugging_opts.span_free_formats {
658 p!(write("@{:?}", hir_id));
660 p!(write("@{:?}", self.tcx().hir().span(hir_id)));
663 for (&var_id, upvar_ty) in self.tcx().upvars(did)
666 .flat_map(|v| v.keys())
672 self.tcx().hir().name(var_id)),
677 // Cross-crate closure types should only be
678 // visible in codegen bug reports, I imagine.
679 p!(write("@{:?}", did));
681 for (index, upvar_ty) in upvar_tys.enumerate() {
683 write("{}{}:", sep, index),
689 if self.tcx().sess.verbose() {
691 " closure_kind_ty={:?} closure_sig_ty={:?}",
692 substs.as_closure().kind(did, self.tcx()),
693 substs.as_closure().sig_ty(did, self.tcx())
699 ty::Array(ty, sz) => {
700 p!(write("["), print(ty), write("; "));
701 if let ConstValue::Unevaluated(..) = sz.val {
702 // do not try to evalute unevaluated constants. If we are const evaluating an
703 // array length anon const, rustc will (with debug assertions) print the
704 // constant's path. Which will end up here again.
706 } else if let Some(n) = sz.try_eval_usize(self.tcx(), ty::ParamEnv::empty()) {
714 p!(write("["), print(ty), write("]"))
721 fn infer_ty_name(&self, _: ty::TyVid) -> Option<String> {
725 fn pretty_print_dyn_existential(
727 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
728 ) -> Result<Self::DynExistential, Self::Error> {
729 define_scoped_cx!(self);
731 // Generate the main trait ref, including associated types.
732 let mut first = true;
734 if let Some(principal) = predicates.principal() {
735 p!(print_def_path(principal.def_id, &[]));
737 let mut resugared = false;
739 // Special-case `Fn(...) -> ...` and resugar it.
740 let fn_trait_kind = self.tcx().lang_items().fn_trait_kind(principal.def_id);
741 if !self.tcx().sess.verbose() && fn_trait_kind.is_some() {
742 if let ty::Tuple(ref args) = principal.substs.type_at(0).kind {
743 let mut projections = predicates.projection_bounds();
744 if let (Some(proj), None) = (projections.next(), projections.next()) {
745 let tys: Vec<_> = args.iter().map(|k| k.expect_ty()).collect();
746 p!(pretty_fn_sig(&tys, false, proj.ty));
752 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
753 // in order to place the projections inside the `<...>`.
755 // Use a type that can't appear in defaults of type parameters.
756 let dummy_self = self.tcx().mk_ty_infer(ty::FreshTy(0));
757 let principal = principal.with_self_ty(self.tcx(), dummy_self);
759 let args = self.generic_args_to_print(
760 self.tcx().generics_of(principal.def_id),
764 // Don't print `'_` if there's no unerased regions.
765 let print_regions = args.iter().any(|arg| {
767 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
771 let mut args = args.iter().cloned().filter(|arg| {
773 GenericArgKind::Lifetime(_) => print_regions,
777 let mut projections = predicates.projection_bounds();
779 let arg0 = args.next();
780 let projection0 = projections.next();
781 if arg0.is_some() || projection0.is_some() {
782 let args = arg0.into_iter().chain(args);
783 let projections = projection0.into_iter().chain(projections);
785 p!(generic_delimiters(|mut cx| {
786 cx = cx.comma_sep(args)?;
787 if arg0.is_some() && projection0.is_some() {
790 cx.comma_sep(projections)
798 // FIXME(eddyb) avoid printing twice (needed to ensure
799 // that the auto traits are sorted *and* printed via cx).
800 let mut auto_traits: Vec<_> = predicates.auto_traits().map(|did| {
801 (self.tcx().def_path_str(did), did)
804 // The auto traits come ordered by `DefPathHash`. While
805 // `DefPathHash` is *stable* in the sense that it depends on
806 // neither the host nor the phase of the moon, it depends
807 // "pseudorandomly" on the compiler version and the target.
809 // To avoid that causing instabilities in compiletest
810 // output, sort the auto-traits alphabetically.
813 for (_, def_id) in auto_traits {
819 p!(print_def_path(def_id, &[]));
830 ) -> Result<Self, Self::Error> {
831 define_scoped_cx!(self);
834 let mut inputs = inputs.iter();
835 if let Some(&ty) = inputs.next() {
838 p!(write(", "), print(ty));
845 if !output.is_unit() {
846 p!(write(" -> "), print(output));
852 fn pretty_print_const(
854 ct: &'tcx ty::Const<'tcx>,
855 ) -> Result<Self::Const, Self::Error> {
856 define_scoped_cx!(self);
858 let u8 = self.tcx().types.u8;
859 if let ty::FnDef(did, substs) = ct.ty.kind {
860 p!(print_value_path(did, substs));
863 if let ConstValue::Unevaluated(did, substs) = ct.val {
864 match self.tcx().def_kind(did) {
865 | Some(DefKind::Static)
866 | Some(DefKind::Const)
867 | Some(DefKind::AssocConst) => p!(print_value_path(did, substs)),
868 _ => if did.is_local() {
869 let span = self.tcx().def_span(did);
870 if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span) {
871 p!(write("{}", snip))
873 p!(write("_: "), print(ct.ty))
876 p!(write("_: "), print(ct.ty))
881 if let ConstValue::Infer(..) = ct.val {
882 p!(write("_: "), print(ct.ty));
885 if let ConstValue::Param(ParamConst { name, .. }) = ct.val {
886 p!(write("{}", name));
889 if let ConstValue::Scalar(Scalar::Raw { data, .. }) = ct.val {
892 p!(write("{}", if data == 0 { "false" } else { "true" }));
895 ty::Float(ast::FloatTy::F32) => {
896 p!(write("{}f32", Single::from_bits(data)));
899 ty::Float(ast::FloatTy::F64) => {
900 p!(write("{}f64", Double::from_bits(data)));
904 let bit_size = Integer::from_attr(&self.tcx(), UnsignedInt(ui)).size();
905 let max = truncate(u128::max_value(), bit_size);
908 p!(write("std::{}::MAX", ui))
910 p!(write("{}{}", data, ui))
915 let bit_size = Integer::from_attr(&self.tcx(), SignedInt(i))
916 .size().bits() as u128;
917 let min = 1u128 << (bit_size - 1);
920 let ty = self.tcx().lift(&ct.ty).unwrap();
921 let size = self.tcx().layout_of(ty::ParamEnv::empty().and(ty))
925 d if d == min => p!(write("std::{}::MIN", i)),
926 d if d == max => p!(write("std::{}::MAX", i)),
927 _ => p!(write("{}{}", sign_extend(data, size) as i128, i))
932 p!(write("{:?}", ::std::char::from_u32(data as u32).unwrap()));
938 if let ty::Ref(_, ref_ty, _) = ct.ty.kind {
939 let byte_str = match (ct.val, &ref_ty.kind) {
940 (ConstValue::Scalar(Scalar::Ptr(ptr)), ty::Array(t, n)) if *t == u8 => {
941 let n = n.eval_usize(self.tcx(), ty::ParamEnv::empty());
944 .unwrap_memory(ptr.alloc_id)
945 .get_bytes(&self.tcx(), ptr, Size::from_bytes(n)).unwrap())
947 (ConstValue::Slice { data, start, end }, ty::Slice(t)) if *t == u8 => {
948 // The `inspect` here is okay since we checked the bounds, and there are no
949 // relocations (we have an active slice reference here). We don't use this
950 // result to affect interpreter execution.
951 Some(data.inspect_with_undef_and_ptr_outside_interpreter(start..end))
953 (ConstValue::Slice { data, start, end }, ty::Str) => {
954 // The `inspect` here is okay since we checked the bounds, and there are no
955 // relocations (we have an active `str` reference here). We don't use this
956 // result to affect interpreter execution.
957 let slice = data.inspect_with_undef_and_ptr_outside_interpreter(start..end);
958 let s = ::std::str::from_utf8(slice)
959 .expect("non utf8 str from miri");
960 p!(write("{:?}", s));
965 if let Some(byte_str) = byte_str {
968 for e in std::ascii::escape_default(c) {
969 self.write_char(e as char)?;
976 p!(write("{:?} : ", ct.val), print(ct.ty));
982 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
983 pub struct FmtPrinter<'a, 'tcx, F>(Box<FmtPrinterData<'a, 'tcx, F>>);
985 pub struct FmtPrinterData<'a, 'tcx, F> {
992 used_region_names: FxHashSet<InternedString>,
996 pub region_highlight_mode: RegionHighlightMode,
998 pub name_resolver: Option<Box<&'a dyn Fn(ty::sty::TyVid) -> Option<String>>>,
1001 impl<F> Deref for FmtPrinter<'a, 'tcx, F> {
1002 type Target = FmtPrinterData<'a, 'tcx, F>;
1003 fn deref(&self) -> &Self::Target {
1008 impl<F> DerefMut for FmtPrinter<'_, '_, F> {
1009 fn deref_mut(&mut self) -> &mut Self::Target {
1014 impl<F> FmtPrinter<'a, 'tcx, F> {
1015 pub fn new(tcx: TyCtxt<'tcx>, fmt: F, ns: Namespace) -> Self {
1016 FmtPrinter(Box::new(FmtPrinterData {
1020 in_value: ns == Namespace::ValueNS,
1021 used_region_names: Default::default(),
1024 region_highlight_mode: RegionHighlightMode::default(),
1025 name_resolver: None,
1031 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1032 // (but also some things just print a `DefId` generally so maybe we need this?)
1033 fn guess_def_namespace(self, def_id: DefId) -> Namespace {
1034 match self.def_key(def_id).disambiguated_data.data {
1035 DefPathData::TypeNs(..)
1036 | DefPathData::CrateRoot
1037 | DefPathData::ImplTrait => Namespace::TypeNS,
1039 DefPathData::ValueNs(..)
1040 | DefPathData::AnonConst
1041 | DefPathData::ClosureExpr
1042 | DefPathData::Ctor => Namespace::ValueNS,
1044 DefPathData::MacroNs(..) => Namespace::MacroNS,
1046 _ => Namespace::TypeNS,
1050 /// Returns a string identifying this `DefId`. This string is
1051 /// suitable for user output.
1052 pub fn def_path_str(self, def_id: DefId) -> String {
1053 let ns = self.guess_def_namespace(def_id);
1054 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1055 let mut s = String::new();
1056 let _ = FmtPrinter::new(self, &mut s, ns)
1057 .print_def_path(def_id, &[]);
1062 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, F> {
1063 fn write_str(&mut self, s: &str) -> fmt::Result {
1064 self.fmt.write_str(s)
1068 impl<F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
1069 type Error = fmt::Error;
1074 type DynExistential = Self;
1077 fn tcx(&'a self) -> TyCtxt<'tcx> {
1084 substs: &'tcx [GenericArg<'tcx>],
1085 ) -> Result<Self::Path, Self::Error> {
1086 define_scoped_cx!(self);
1088 if substs.is_empty() {
1089 match self.try_print_visible_def_path(def_id)? {
1090 (cx, true) => return Ok(cx),
1091 (cx, false) => self = cx,
1095 let key = self.tcx.def_key(def_id);
1096 if let DefPathData::Impl = key.disambiguated_data.data {
1097 // Always use types for non-local impls, where types are always
1098 // available, and filename/line-number is mostly uninteresting.
1100 !def_id.is_local() || {
1101 // Otherwise, use filename/line-number if forced.
1102 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1107 // If no type info is available, fall back to
1108 // pretty printing some span information. This should
1109 // only occur very early in the compiler pipeline.
1110 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1111 let span = self.tcx.def_span(def_id);
1113 self = self.print_def_path(parent_def_id, &[])?;
1115 // HACK(eddyb) copy of `path_append` to avoid
1116 // constructing a `DisambiguatedDefPathData`.
1117 if !self.empty_path {
1118 write!(self, "::")?;
1120 write!(self, "<impl at {:?}>", span)?;
1121 self.empty_path = false;
1127 self.default_print_def_path(def_id, substs)
1132 region: ty::Region<'_>,
1133 ) -> Result<Self::Region, Self::Error> {
1134 self.pretty_print_region(region)
1140 ) -> Result<Self::Type, Self::Error> {
1141 self.pretty_print_type(ty)
1144 fn print_dyn_existential(
1146 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1147 ) -> Result<Self::DynExistential, Self::Error> {
1148 self.pretty_print_dyn_existential(predicates)
1153 ct: &'tcx ty::Const<'tcx>,
1154 ) -> Result<Self::Const, Self::Error> {
1155 self.pretty_print_const(ct)
1161 ) -> Result<Self::Path, Self::Error> {
1162 self.empty_path = true;
1163 if cnum == LOCAL_CRATE {
1164 if self.tcx.sess.rust_2018() {
1165 // We add the `crate::` keyword on Rust 2018, only when desired.
1166 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1167 write!(self, "{}", kw::Crate)?;
1168 self.empty_path = false;
1172 write!(self, "{}", self.tcx.crate_name(cnum))?;
1173 self.empty_path = false;
1181 trait_ref: Option<ty::TraitRef<'tcx>>,
1182 ) -> Result<Self::Path, Self::Error> {
1183 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1184 self.empty_path = false;
1188 fn path_append_impl(
1190 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1191 _disambiguated_data: &DisambiguatedDefPathData,
1193 trait_ref: Option<ty::TraitRef<'tcx>>,
1194 ) -> Result<Self::Path, Self::Error> {
1195 self = self.pretty_path_append_impl(|mut cx| {
1196 cx = print_prefix(cx)?;
1202 }, self_ty, trait_ref)?;
1203 self.empty_path = false;
1209 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1210 disambiguated_data: &DisambiguatedDefPathData,
1211 ) -> Result<Self::Path, Self::Error> {
1212 self = print_prefix(self)?;
1214 // Skip `::{{constructor}}` on tuple/unit structs.
1215 match disambiguated_data.data {
1216 DefPathData::Ctor => return Ok(self),
1220 // FIXME(eddyb) `name` should never be empty, but it
1221 // currently is for `extern { ... }` "foreign modules".
1222 let name = disambiguated_data.data.as_interned_str().as_str();
1223 if !name.is_empty() {
1224 if !self.empty_path {
1225 write!(self, "::")?;
1227 write!(self, "{}", name)?;
1229 // FIXME(eddyb) this will print e.g. `{{closure}}#3`, but it
1230 // might be nicer to use something else, e.g. `{closure#3}`.
1231 let dis = disambiguated_data.disambiguator;
1233 disambiguated_data.data.get_opt_name().is_none() ||
1234 dis != 0 && self.tcx.sess.verbose();
1236 write!(self, "#{}", dis)?;
1239 self.empty_path = false;
1245 fn path_generic_args(
1247 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1248 args: &[GenericArg<'tcx>],
1249 ) -> Result<Self::Path, Self::Error> {
1250 self = print_prefix(self)?;
1252 // Don't print `'_` if there's no unerased regions.
1253 let print_regions = args.iter().any(|arg| {
1254 match arg.unpack() {
1255 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
1259 let args = args.iter().cloned().filter(|arg| {
1260 match arg.unpack() {
1261 GenericArgKind::Lifetime(_) => print_regions,
1266 if args.clone().next().is_some() {
1268 write!(self, "::")?;
1270 self.generic_delimiters(|cx| cx.comma_sep(args))
1277 impl<F: fmt::Write> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx, F> {
1278 fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> {
1279 self.0.name_resolver.as_ref().and_then(|func| func(id))
1282 fn print_value_path(
1285 substs: &'tcx [GenericArg<'tcx>],
1286 ) -> Result<Self::Path, Self::Error> {
1287 let was_in_value = std::mem::replace(&mut self.in_value, true);
1288 self = self.print_def_path(def_id, substs)?;
1289 self.in_value = was_in_value;
1294 fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
1296 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1298 self.pretty_in_binder(value)
1301 fn generic_delimiters(
1303 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1304 ) -> Result<Self, Self::Error> {
1307 let was_in_value = std::mem::replace(&mut self.in_value, false);
1308 let mut inner = f(self)?;
1309 inner.in_value = was_in_value;
1311 write!(inner, ">")?;
1315 fn region_should_not_be_omitted(
1317 region: ty::Region<'_>,
1319 let highlight = self.region_highlight_mode;
1320 if highlight.region_highlighted(region).is_some() {
1324 if self.tcx.sess.verbose() {
1328 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1331 ty::ReEarlyBound(ref data) => {
1332 data.name.as_symbol() != kw::Invalid &&
1333 data.name.as_symbol() != kw::UnderscoreLifetime
1336 ty::ReLateBound(_, br) |
1337 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1338 ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1339 if let ty::BrNamed(_, name) = br {
1340 if name.as_symbol() != kw::Invalid &&
1341 name.as_symbol() != kw::UnderscoreLifetime {
1346 if let Some((region, _)) = highlight.highlight_bound_region {
1356 ty::ReVar(_) if identify_regions => true,
1360 ty::ReErased => false,
1364 ty::ReClosureBound(_) => true,
1369 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1370 impl<F: fmt::Write> FmtPrinter<'_, '_, F> {
1371 pub fn pretty_print_region(
1373 region: ty::Region<'_>,
1374 ) -> Result<Self, fmt::Error> {
1375 define_scoped_cx!(self);
1377 // Watch out for region highlights.
1378 let highlight = self.region_highlight_mode;
1379 if let Some(n) = highlight.region_highlighted(region) {
1380 p!(write("'{}", n));
1384 if self.tcx.sess.verbose() {
1385 p!(write("{:?}", region));
1389 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1391 // These printouts are concise. They do not contain all the information
1392 // the user might want to diagnose an error, but there is basically no way
1393 // to fit that into a short string. Hence the recommendation to use
1394 // `explain_region()` or `note_and_explain_region()`.
1396 ty::ReEarlyBound(ref data) => {
1397 if data.name.as_symbol() != kw::Invalid {
1398 p!(write("{}", data.name));
1402 ty::ReLateBound(_, br) |
1403 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1404 ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1405 if let ty::BrNamed(_, name) = br {
1406 if name.as_symbol() != kw::Invalid &&
1407 name.as_symbol() != kw::UnderscoreLifetime {
1408 p!(write("{}", name));
1413 if let Some((region, counter)) = highlight.highlight_bound_region {
1415 p!(write("'{}", counter));
1420 ty::ReScope(scope) if identify_regions => {
1422 region::ScopeData::Node =>
1423 p!(write("'{}s", scope.item_local_id().as_usize())),
1424 region::ScopeData::CallSite =>
1425 p!(write("'{}cs", scope.item_local_id().as_usize())),
1426 region::ScopeData::Arguments =>
1427 p!(write("'{}as", scope.item_local_id().as_usize())),
1428 region::ScopeData::Destruction =>
1429 p!(write("'{}ds", scope.item_local_id().as_usize())),
1430 region::ScopeData::Remainder(first_statement_index) => p!(write(
1432 scope.item_local_id().as_usize(),
1433 first_statement_index.index()
1438 ty::ReVar(region_vid) if identify_regions => {
1439 p!(write("{:?}", region_vid));
1446 p!(write("'static"));
1450 p!(write("'<empty>"));
1454 // The user should never encounter these in unsubstituted form.
1455 ty::ReClosureBound(vid) => {
1456 p!(write("{:?}", vid));
1467 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1468 // `region_index` and `used_region_names`.
1469 impl<F: fmt::Write> FmtPrinter<'_, 'tcx, F> {
1470 pub fn pretty_in_binder<T>(mut self, value: &ty::Binder<T>) -> Result<Self, fmt::Error>
1472 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1474 fn name_by_region_index(index: usize) -> InternedString {
1476 0 => InternedString::intern("'r"),
1477 1 => InternedString::intern("'s"),
1478 i => InternedString::intern(&format!("'t{}", i-2)),
1482 // Replace any anonymous late-bound regions with named
1483 // variants, using gensym'd identifiers, so that we can
1484 // clearly differentiate between named and unnamed regions in
1485 // the output. We'll probably want to tweak this over time to
1486 // decide just how much information to give.
1487 if self.binder_depth == 0 {
1488 self.prepare_late_bound_region_info(value);
1491 let mut empty = true;
1492 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1493 write!(cx, "{}", if empty {
1501 define_scoped_cx!(self);
1503 let old_region_index = self.region_index;
1504 let mut region_index = old_region_index;
1505 let new_value = self.tcx.replace_late_bound_regions(value, |br| {
1506 let _ = start_or_continue(&mut self, "for<", ", ");
1508 ty::BrNamed(_, name) => {
1509 let _ = write!(self, "{}", name);
1515 let name = name_by_region_index(region_index);
1517 if !self.used_region_names.contains(&name) {
1521 let _ = write!(self, "{}", name);
1522 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1525 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
1527 start_or_continue(&mut self, "", "> ")?;
1529 self.binder_depth += 1;
1530 self.region_index = region_index;
1531 let mut inner = new_value.print(self)?;
1532 inner.region_index = old_region_index;
1533 inner.binder_depth -= 1;
1537 fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
1538 where T: TypeFoldable<'tcx>
1541 struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet<InternedString>);
1542 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> {
1543 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
1545 ty::ReLateBound(_, ty::BrNamed(_, name)) => {
1546 self.0.insert(name);
1550 r.super_visit_with(self)
1554 self.used_region_names.clear();
1555 let mut collector = LateBoundRegionNameCollector(&mut self.used_region_names);
1556 value.visit_with(&mut collector);
1557 self.region_index = 0;
1561 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<T>
1563 T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
1566 type Error = P::Error;
1567 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
1572 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
1574 T: Print<'tcx, P, Output = P, Error = P::Error>,
1575 U: Print<'tcx, P, Output = P, Error = P::Error>,
1578 type Error = P::Error;
1579 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
1580 define_scoped_cx!(cx);
1581 p!(print(self.0), write(" : "), print(self.1));
1586 macro_rules! forward_display_to_print {
1588 $(impl fmt::Display for $ty {
1589 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1590 ty::tls::with(|tcx| {
1592 .expect("could not lift for printing")
1593 .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1601 macro_rules! define_print_and_forward_display {
1602 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
1603 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
1605 type Error = fmt::Error;
1606 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
1607 #[allow(unused_mut)]
1609 define_scoped_cx!($cx);
1611 #[allow(unreachable_code)]
1616 forward_display_to_print!($($ty),+);
1620 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
1621 impl fmt::Display for ty::RegionKind {
1622 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1623 ty::tls::with(|tcx| {
1624 self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1630 forward_display_to_print! {
1632 &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1633 &'tcx ty::Const<'tcx>,
1635 // HACK(eddyb) these are exhaustive instead of generic,
1636 // because `for<'tcx>` isn't possible yet.
1637 ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
1638 ty::Binder<ty::TraitRef<'tcx>>,
1639 ty::Binder<ty::FnSig<'tcx>>,
1640 ty::Binder<ty::TraitPredicate<'tcx>>,
1641 ty::Binder<ty::SubtypePredicate<'tcx>>,
1642 ty::Binder<ty::ProjectionPredicate<'tcx>>,
1643 ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1644 ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
1646 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1647 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1650 define_print_and_forward_display! {
1653 &'tcx ty::List<Ty<'tcx>> {
1655 let mut tys = self.iter();
1656 if let Some(&ty) = tys.next() {
1659 p!(write(", "), print(ty));
1665 ty::TypeAndMut<'tcx> {
1666 p!(write("{}", if self.mutbl == hir::MutMutable { "mut " } else { "" }),
1670 ty::ExistentialTraitRef<'tcx> {
1671 // Use a type that can't appear in defaults of type parameters.
1672 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1673 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
1674 p!(print(trait_ref))
1677 ty::ExistentialProjection<'tcx> {
1678 let name = cx.tcx().associated_item(self.item_def_id).ident;
1679 p!(write("{} = ", name), print(self.ty))
1682 ty::ExistentialPredicate<'tcx> {
1684 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
1685 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
1686 ty::ExistentialPredicate::AutoTrait(def_id) => {
1687 p!(print_def_path(def_id, &[]));
1693 if self.unsafety == hir::Unsafety::Unsafe {
1694 p!(write("unsafe "));
1697 if self.abi != Abi::Rust {
1698 p!(write("extern {} ", self.abi));
1701 p!(write("fn"), pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
1705 if cx.tcx().sess.verbose() {
1706 p!(write("{:?}", self));
1710 ty::TyVar(_) => p!(write("_")),
1711 ty::IntVar(_) => p!(write("{}", "{integer}")),
1712 ty::FloatVar(_) => p!(write("{}", "{float}")),
1713 ty::FreshTy(v) => p!(write("FreshTy({})", v)),
1714 ty::FreshIntTy(v) => p!(write("FreshIntTy({})", v)),
1715 ty::FreshFloatTy(v) => p!(write("FreshFloatTy({})", v))
1719 ty::TraitRef<'tcx> {
1720 p!(print_def_path(self.def_id, self.substs));
1724 p!(write("{}", self.name))
1728 p!(write("{}", self.name))
1731 ty::SubtypePredicate<'tcx> {
1732 p!(print(self.a), write(" <: "), print(self.b))
1735 ty::TraitPredicate<'tcx> {
1736 p!(print(self.trait_ref.self_ty()), write(": "), print(self.trait_ref))
1739 ty::ProjectionPredicate<'tcx> {
1740 p!(print(self.projection_ty), write(" == "), print(self.ty))
1743 ty::ProjectionTy<'tcx> {
1744 p!(print_def_path(self.item_def_id, self.substs));
1749 ty::ClosureKind::Fn => p!(write("Fn")),
1750 ty::ClosureKind::FnMut => p!(write("FnMut")),
1751 ty::ClosureKind::FnOnce => p!(write("FnOnce")),
1755 ty::Predicate<'tcx> {
1757 ty::Predicate::Trait(ref data) => p!(print(data)),
1758 ty::Predicate::Subtype(ref predicate) => p!(print(predicate)),
1759 ty::Predicate::RegionOutlives(ref predicate) => p!(print(predicate)),
1760 ty::Predicate::TypeOutlives(ref predicate) => p!(print(predicate)),
1761 ty::Predicate::Projection(ref predicate) => p!(print(predicate)),
1762 ty::Predicate::WellFormed(ty) => p!(print(ty), write(" well-formed")),
1763 ty::Predicate::ObjectSafe(trait_def_id) => {
1764 p!(write("the trait `"),
1765 print_def_path(trait_def_id, &[]),
1766 write("` is object-safe"))
1768 ty::Predicate::ClosureKind(closure_def_id, _closure_substs, kind) => {
1769 p!(write("the closure `"),
1770 print_value_path(closure_def_id, &[]),
1771 write("` implements the trait `{}`", kind))
1773 ty::Predicate::ConstEvaluatable(def_id, substs) => {
1774 p!(write("the constant `"),
1775 print_value_path(def_id, substs),
1776 write("` can be evaluated"))
1782 match self.unpack() {
1783 GenericArgKind::Lifetime(lt) => p!(print(lt)),
1784 GenericArgKind::Type(ty) => p!(print(ty)),
1785 GenericArgKind::Const(ct) => p!(print(ct)),