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::{Kind, Subst, UnpackedKind};
9 use crate::ty::layout::Size;
10 use crate::mir::interpret::{ConstValue, sign_extend, Scalar};
12 use rustc_apfloat::ieee::{Double, Single};
13 use rustc_apfloat::Float;
14 use rustc_target::spec::abi::Abi;
15 use syntax::symbol::{kw, InternedString};
18 use std::fmt::{self, Write as _};
19 use std::ops::{Deref, DerefMut};
21 // `pretty` is a separate module only for organization.
25 (@write($($data:expr),+)) => {
26 write!(scoped_cx!(), $($data),+)?
28 (@print($x:expr)) => {
29 scoped_cx!() = $x.print(scoped_cx!())?
31 (@$method:ident($($arg:expr),*)) => {
32 scoped_cx!() = scoped_cx!().$method($($arg),*)?
34 ($($kind:ident $data:tt),+) => {{
38 macro_rules! define_scoped_cx {
40 #[allow(unused_macros)]
41 macro_rules! scoped_cx {
48 static FORCE_IMPL_FILENAME_LINE: Cell<bool> = Cell::new(false);
49 static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = Cell::new(false);
52 /// Force us to name impls with just the filename/line number. We
53 /// normally try to use types. But at some points, notably while printing
54 /// cycle errors, this can result in extra or suboptimal error output,
55 /// so this variable disables that check.
56 pub fn with_forced_impl_filename_line<F: FnOnce() -> R, R>(f: F) -> R {
57 FORCE_IMPL_FILENAME_LINE.with(|force| {
58 let old = force.get();
66 /// Adds the `crate::` prefix to paths where appropriate.
67 pub fn with_crate_prefix<F: FnOnce() -> R, R>(f: F) -> R {
68 SHOULD_PREFIX_WITH_CRATE.with(|flag| {
77 /// The "region highlights" are used to control region printing during
78 /// specific error messages. When a "region highlight" is enabled, it
79 /// gives an alternate way to print specific regions. For now, we
80 /// always print those regions using a number, so something like "`'0`".
82 /// Regions not selected by the region highlight mode are presently
84 #[derive(Copy, Clone, Default)]
85 pub struct RegionHighlightMode {
86 /// If enabled, when we see the selected region, use "`'N`"
87 /// instead of the ordinary behavior.
88 highlight_regions: [Option<(ty::RegionKind, usize)>; 3],
90 /// If enabled, when printing a "free region" that originated from
91 /// the given `ty::BoundRegion`, print it as "`'1`". Free regions that would ordinarily
92 /// have names print as normal.
94 /// This is used when you have a signature like `fn foo(x: &u32,
95 /// y: &'a u32)` and we want to give a name to the region of the
97 highlight_bound_region: Option<(ty::BoundRegion, usize)>,
100 impl RegionHighlightMode {
101 /// If `region` and `number` are both `Some`, invokes
102 /// `highlighting_region`.
103 pub fn maybe_highlighting_region(
105 region: Option<ty::Region<'_>>,
106 number: Option<usize>,
108 if let Some(k) = region {
109 if let Some(n) = number {
110 self.highlighting_region(k, n);
115 /// Highlights the region inference variable `vid` as `'N`.
116 pub fn highlighting_region(
118 region: ty::Region<'_>,
121 let num_slots = self.highlight_regions.len();
122 let first_avail_slot = self.highlight_regions.iter_mut()
123 .filter(|s| s.is_none())
127 "can only highlight {} placeholders at a time",
131 *first_avail_slot = Some((*region, number));
134 /// Convenience wrapper for `highlighting_region`.
135 pub fn highlighting_region_vid(
140 self.highlighting_region(&ty::ReVar(vid), number)
143 /// Returns `Some(n)` with the number to use for the given region, if any.
144 fn region_highlighted(&self, region: ty::Region<'_>) -> Option<usize> {
148 .filter_map(|h| match h {
149 Some((r, n)) if r == region => Some(*n),
155 /// Highlight the given bound region.
156 /// We can only highlight one bound region at a time. See
157 /// the field `highlight_bound_region` for more detailed notes.
158 pub fn highlighting_bound_region(
163 assert!(self.highlight_bound_region.is_none());
164 self.highlight_bound_region = Some((br, number));
168 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
169 pub trait PrettyPrinter<'tcx>:
176 DynExistential = Self,
180 /// Like `print_def_path` but for value paths.
184 substs: &'tcx [Kind<'tcx>],
185 ) -> Result<Self::Path, Self::Error> {
186 self.print_def_path(def_id, substs)
189 fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
191 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
193 value.skip_binder().print(self)
196 /// Print comma-separated elements.
197 fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
199 T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
201 if let Some(first) = elems.next() {
202 self = first.print(self)?;
204 self.write_str(", ")?;
205 self = elem.print(self)?;
211 /// Print `<...>` around what `f` prints.
212 fn generic_delimiters(
214 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
215 ) -> Result<Self, Self::Error>;
217 /// Return `true` if the region should be printed in
218 /// optional positions, e.g. `&'a T` or `dyn Tr + 'b`.
219 /// This is typically the case for all non-`'_` regions.
220 fn region_should_not_be_omitted(
222 region: ty::Region<'_>,
225 // Defaults (should not be overriden):
227 /// If possible, this returns a global path resolving to `def_id` that is visible
228 /// from at least one local module and returns true. If the crate defining `def_id` is
229 /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
230 fn try_print_visible_def_path(
233 ) -> Result<(Self, bool), Self::Error> {
234 let mut callers = Vec::new();
235 self.try_print_visible_def_path_recur(def_id, &mut callers)
238 /// Does the work of `try_print_visible_def_path`, building the
239 /// full definition path recursively before attempting to
240 /// post-process it into the valid and visible version that
241 /// accounts for re-exports.
243 /// This method should only be callled by itself or
244 /// `try_print_visible_def_path`.
246 /// `callers` is a chain of visible_parent's leading to `def_id`,
247 /// to support cycle detection during recursion.
248 fn try_print_visible_def_path_recur(
251 callers: &mut Vec<DefId>,
252 ) -> Result<(Self, bool), Self::Error> {
253 define_scoped_cx!(self);
255 debug!("try_print_visible_def_path: def_id={:?}", def_id);
257 // If `def_id` is a direct or injected extern crate, return the
258 // path to the crate followed by the path to the item within the crate.
259 if def_id.index == CRATE_DEF_INDEX {
260 let cnum = def_id.krate;
262 if cnum == LOCAL_CRATE {
263 return Ok((self.path_crate(cnum)?, true));
266 // In local mode, when we encounter a crate other than
267 // LOCAL_CRATE, execution proceeds in one of two ways:
269 // 1. for a direct dependency, where user added an
270 // `extern crate` manually, we put the `extern
271 // crate` as the parent. So you wind up with
272 // something relative to the current crate.
273 // 2. for an extern inferred from a path or an indirect crate,
274 // where there is no explicit `extern crate`, we just prepend
276 match self.tcx().extern_crate(def_id) {
278 src: ExternCrateSource::Extern(def_id),
283 debug!("try_print_visible_def_path: def_id={:?}", def_id);
284 return Ok((if !span.is_dummy() {
285 self.print_def_path(def_id, &[])?
287 self.path_crate(cnum)?
291 return Ok((self.path_crate(cnum)?, true));
297 if def_id.is_local() {
298 return Ok((self, false));
301 let visible_parent_map = self.tcx().visible_parent_map(LOCAL_CRATE);
303 let mut cur_def_key = self.tcx().def_key(def_id);
304 debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
306 // For a constructor we want the name of its parent rather than <unnamed>.
307 match cur_def_key.disambiguated_data.data {
308 DefPathData::Ctor => {
311 index: cur_def_key.parent
312 .expect("DefPathData::Ctor/VariantData missing a parent"),
315 cur_def_key = self.tcx().def_key(parent);
320 let visible_parent = match visible_parent_map.get(&def_id).cloned() {
321 Some(parent) => parent,
322 None => return Ok((self, false)),
324 if callers.contains(&visible_parent) {
325 return Ok((self, false));
327 callers.push(visible_parent);
328 // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
329 // knowing ahead of time whether the entire path will succeed or not.
330 // To support printers that do not implement `PrettyPrinter`, a `Vec` or
331 // linked list on the stack would need to be built, before any printing.
332 match self.try_print_visible_def_path_recur(visible_parent, callers)? {
333 (cx, false) => return Ok((cx, false)),
334 (cx, true) => self = cx,
337 let actual_parent = self.tcx().parent(def_id);
339 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
340 visible_parent, actual_parent,
343 let mut data = cur_def_key.disambiguated_data.data;
345 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
346 data, visible_parent, actual_parent,
350 // In order to output a path that could actually be imported (valid and visible),
351 // we need to handle re-exports correctly.
353 // For example, take `std::os::unix::process::CommandExt`, this trait is actually
354 // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
356 // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is
357 // private so the "true" path to `CommandExt` isn't accessible.
359 // In this case, the `visible_parent_map` will look something like this:
361 // (child) -> (parent)
362 // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
363 // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
364 // `std::sys::unix::ext` -> `std::os`
366 // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
369 // When printing the path to `CommandExt` and looking at the `cur_def_key` that
370 // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
371 // to the parent - resulting in a mangled path like
372 // `std::os::ext::process::CommandExt`.
374 // Instead, we must detect that there was a re-export and instead print `unix`
375 // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
376 // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
377 // the visible parent (`std::os`). If these do not match, then we iterate over
378 // the children of the visible parent (as was done when computing
379 // `visible_parent_map`), looking for the specific child we currently have and then
380 // have access to the re-exported name.
381 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
382 let reexport = self.tcx().item_children(visible_parent)
384 .find(|child| child.res.def_id() == def_id)
385 .map(|child| child.ident.as_interned_str());
386 if let Some(reexport) = reexport {
390 // Re-exported `extern crate` (#43189).
391 DefPathData::CrateRoot => {
392 data = DefPathData::TypeNs(
393 self.tcx().original_crate_name(def_id.krate).as_interned_str(),
398 debug!("try_print_visible_def_path: data={:?}", data);
400 Ok((self.path_append(Ok, &DisambiguatedDefPathData {
406 fn pretty_path_qualified(
409 trait_ref: Option<ty::TraitRef<'tcx>>,
410 ) -> Result<Self::Path, Self::Error> {
411 if trait_ref.is_none() {
412 // Inherent impls. Try to print `Foo::bar` for an inherent
413 // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
414 // anything other than a simple path.
416 ty::Adt(..) | ty::Foreign(_) |
417 ty::Bool | ty::Char | ty::Str |
418 ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
419 return self_ty.print(self);
426 self.generic_delimiters(|mut cx| {
427 define_scoped_cx!(cx);
430 if let Some(trait_ref) = trait_ref {
431 p!(write(" as "), print(trait_ref));
437 fn pretty_path_append_impl(
439 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
441 trait_ref: Option<ty::TraitRef<'tcx>>,
442 ) -> Result<Self::Path, Self::Error> {
443 self = print_prefix(self)?;
445 self.generic_delimiters(|mut cx| {
446 define_scoped_cx!(cx);
449 if let Some(trait_ref) = trait_ref {
450 p!(print(trait_ref), write(" for "));
458 fn pretty_print_type(
461 ) -> Result<Self::Type, Self::Error> {
462 define_scoped_cx!(self);
465 ty::Bool => p!(write("bool")),
466 ty::Char => p!(write("char")),
467 ty::Int(t) => p!(write("{}", t.ty_to_string())),
468 ty::Uint(t) => p!(write("{}", t.ty_to_string())),
469 ty::Float(t) => p!(write("{}", t.ty_to_string())),
470 ty::RawPtr(ref tm) => {
471 p!(write("*{} ", match tm.mutbl {
472 hir::MutMutable => "mut",
473 hir::MutImmutable => "const",
477 ty::Ref(r, ty, mutbl) => {
479 if self.region_should_not_be_omitted(r) {
480 p!(print(r), write(" "));
482 p!(print(ty::TypeAndMut { ty, mutbl }))
484 ty::Never => p!(write("!")),
485 ty::Tuple(ref tys) => {
487 let mut tys = tys.iter();
488 if let Some(&ty) = tys.next() {
489 p!(print(ty), write(","));
490 if let Some(&ty) = tys.next() {
491 p!(write(" "), print(ty));
493 p!(write(", "), print(ty));
499 ty::FnDef(def_id, substs) => {
500 let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs);
501 p!(print(sig), write(" {{"), print_value_path(def_id, substs), write("}}"));
503 ty::FnPtr(ref bare_fn) => {
506 ty::Infer(infer_ty) => {
507 if let ty::TyVar(ty_vid) = infer_ty {
508 if let Some(name) = self.infer_ty_name(ty_vid) {
509 p!(write("{}", name))
511 p!(write("{}", infer_ty))
514 p!(write("{}", infer_ty))
517 ty::Error => p!(write("[type error]")),
518 ty::Param(ref param_ty) => p!(write("{}", param_ty)),
519 ty::Bound(debruijn, bound_ty) => {
520 match bound_ty.kind {
521 ty::BoundTyKind::Anon => {
522 if debruijn == ty::INNERMOST {
523 p!(write("^{}", bound_ty.var.index()))
525 p!(write("^{}_{}", debruijn.index(), bound_ty.var.index()))
529 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
532 ty::Adt(def, substs) => {
533 p!(print_def_path(def.did, substs));
535 ty::Dynamic(data, r) => {
536 let print_r = self.region_should_not_be_omitted(r);
540 p!(write("dyn "), print(data));
542 p!(write(" + "), print(r), write(")"));
545 ty::Foreign(def_id) => {
546 p!(print_def_path(def_id, &[]));
548 ty::Projection(ref data) => p!(print(data)),
549 ty::UnnormalizedProjection(ref data) => {
550 p!(write("Unnormalized("), print(data), write(")"))
552 ty::Placeholder(placeholder) => {
553 p!(write("Placeholder({:?})", placeholder))
555 ty::Opaque(def_id, substs) => {
556 // FIXME(eddyb) print this with `print_def_path`.
557 if self.tcx().sess.verbose() {
558 p!(write("Opaque({:?}, {:?})", def_id, substs));
562 let def_key = self.tcx().def_key(def_id);
563 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
564 p!(write("{}", name));
565 let mut substs = substs.iter();
566 // FIXME(eddyb) print this with `print_def_path`.
567 if let Some(first) = substs.next() {
570 for subst in substs {
571 p!(write(", "), print(subst));
577 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
578 // by looking up the projections associated with the def_id.
579 let bounds = self.tcx().predicates_of(def_id).instantiate(self.tcx(), substs);
581 let mut first = true;
582 let mut is_sized = false;
584 for predicate in bounds.predicates {
585 if let Some(trait_ref) = predicate.to_opt_poly_trait_ref() {
586 // Don't print +Sized, but rather +?Sized if absent.
587 if Some(trait_ref.def_id()) == self.tcx().lang_items().sized_trait() {
593 write("{}", if first { " " } else { "+" }),
599 p!(write("{}?Sized", if first { " " } else { "+" }));
604 ty::Str => p!(write("str")),
605 ty::Generator(did, substs, movability) => {
606 let upvar_tys = substs.upvar_tys(did, self.tcx());
607 let witness = substs.witness(did, self.tcx());
608 if movability == hir::GeneratorMovability::Movable {
609 p!(write("[generator"));
611 p!(write("[static generator"));
614 // FIXME(eddyb) should use `def_span`.
615 if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
616 p!(write("@{:?}", self.tcx().hir().span(hir_id)));
618 for (&var_id, upvar_ty) in self.tcx().upvars(did)
621 .flat_map(|v| v.keys())
627 self.tcx().hir().name(var_id)),
632 // cross-crate closure types should only be
633 // visible in codegen bug reports, I imagine.
634 p!(write("@{:?}", did));
636 for (index, upvar_ty) in upvar_tys.enumerate() {
638 write("{}{}:", sep, index),
644 p!(write(" "), print(witness), write("]"))
646 ty::GeneratorWitness(types) => {
647 p!(in_binder(&types));
649 ty::Closure(did, substs) => {
650 let upvar_tys = substs.upvar_tys(did, self.tcx());
651 p!(write("[closure"));
653 // FIXME(eddyb) should use `def_span`.
654 if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
655 if self.tcx().sess.opts.debugging_opts.span_free_formats {
656 p!(write("@{:?}", hir_id));
658 p!(write("@{:?}", self.tcx().hir().span(hir_id)));
661 for (&var_id, upvar_ty) in self.tcx().upvars(did)
664 .flat_map(|v| v.keys())
670 self.tcx().hir().name(var_id)),
675 // cross-crate closure types should only be
676 // visible in codegen bug reports, I imagine.
677 p!(write("@{:?}", did));
679 for (index, upvar_ty) in upvar_tys.enumerate() {
681 write("{}{}:", sep, index),
687 if self.tcx().sess.verbose() {
689 " closure_kind_ty={:?} closure_sig_ty={:?}",
690 substs.closure_kind_ty(did, self.tcx()),
691 substs.closure_sig_ty(did, self.tcx())
697 ty::Array(ty, sz) => {
698 p!(write("["), print(ty), write("; "));
699 if let ConstValue::Unevaluated(..) = sz.val {
700 // do not try to evalute unevaluated constants. If we are const evaluating an
701 // array length anon const, rustc will (with debug assertions) print the
702 // constant's path. Which will end up here again.
704 } else if let Some(n) = sz.try_eval_usize(self.tcx(), ty::ParamEnv::empty()) {
712 p!(write("["), print(ty), write("]"))
719 fn infer_ty_name(&self, _: ty::TyVid) -> Option<String> {
723 fn pretty_print_dyn_existential(
725 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
726 ) -> Result<Self::DynExistential, Self::Error> {
727 define_scoped_cx!(self);
729 // Generate the main trait ref, including associated types.
730 let mut first = true;
732 if let Some(principal) = predicates.principal() {
733 p!(print_def_path(principal.def_id, &[]));
735 let mut resugared = false;
737 // Special-case `Fn(...) -> ...` and resugar it.
738 let fn_trait_kind = self.tcx().lang_items().fn_trait_kind(principal.def_id);
739 if !self.tcx().sess.verbose() && fn_trait_kind.is_some() {
740 if let ty::Tuple(ref args) = principal.substs.type_at(0).sty {
741 let mut projections = predicates.projection_bounds();
742 if let (Some(proj), None) = (projections.next(), projections.next()) {
743 let tys: Vec<_> = args.iter().map(|k| k.expect_ty()).collect();
744 p!(pretty_fn_sig(&tys, false, proj.ty));
750 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
751 // in order to place the projections inside the `<...>`.
753 // Use a type that can't appear in defaults of type parameters.
754 let dummy_self = self.tcx().mk_ty_infer(ty::FreshTy(0));
755 let principal = principal.with_self_ty(self.tcx(), dummy_self);
757 let args = self.generic_args_to_print(
758 self.tcx().generics_of(principal.def_id),
762 // Don't print `'_` if there's no unerased regions.
763 let print_regions = args.iter().any(|arg| {
765 UnpackedKind::Lifetime(r) => *r != ty::ReErased,
769 let mut args = args.iter().cloned().filter(|arg| {
771 UnpackedKind::Lifetime(_) => print_regions,
775 let mut projections = predicates.projection_bounds();
777 let arg0 = args.next();
778 let projection0 = projections.next();
779 if arg0.is_some() || projection0.is_some() {
780 let args = arg0.into_iter().chain(args);
781 let projections = projection0.into_iter().chain(projections);
783 p!(generic_delimiters(|mut cx| {
784 cx = cx.comma_sep(args)?;
785 if arg0.is_some() && projection0.is_some() {
788 cx.comma_sep(projections)
796 // FIXME(eddyb) avoid printing twice (needed to ensure
797 // that the auto traits are sorted *and* printed via cx).
798 let mut auto_traits: Vec<_> = predicates.auto_traits().map(|did| {
799 (self.tcx().def_path_str(did), did)
802 // The auto traits come ordered by `DefPathHash`. While
803 // `DefPathHash` is *stable* in the sense that it depends on
804 // neither the host nor the phase of the moon, it depends
805 // "pseudorandomly" on the compiler version and the target.
807 // To avoid that causing instabilities in compiletest
808 // output, sort the auto-traits alphabetically.
811 for (_, def_id) in auto_traits {
817 p!(print_def_path(def_id, &[]));
828 ) -> Result<Self, Self::Error> {
829 define_scoped_cx!(self);
832 let mut inputs = inputs.iter();
833 if let Some(&ty) = inputs.next() {
836 p!(write(", "), print(ty));
843 if !output.is_unit() {
844 p!(write(" -> "), print(output));
850 fn pretty_print_const(
852 ct: &'tcx ty::Const<'tcx>,
853 ) -> Result<Self::Const, Self::Error> {
854 define_scoped_cx!(self);
856 let u8 = self.tcx().types.u8;
857 if let ty::FnDef(did, substs) = ct.ty.sty {
858 p!(print_value_path(did, substs));
861 if let ConstValue::Unevaluated(did, substs) = ct.val {
862 match self.tcx().def_kind(did) {
863 | Some(DefKind::Static)
864 | Some(DefKind::Const)
865 | Some(DefKind::AssocConst) => p!(print_value_path(did, substs)),
866 _ => if did.is_local() {
867 let span = self.tcx().def_span(did);
868 if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span) {
869 p!(write("{}", snip))
871 p!(write("_: "), print(ct.ty))
874 p!(write("_: "), print(ct.ty))
879 if let ConstValue::Infer(..) = ct.val {
880 p!(write("_: "), print(ct.ty));
883 if let ConstValue::Param(ParamConst { name, .. }) = ct.val {
884 p!(write("{}", name));
887 if let ConstValue::Scalar(Scalar::Raw { data, .. }) = ct.val {
890 p!(write("{}", if data == 0 { "false" } else { "true" }));
893 ty::Float(ast::FloatTy::F32) => {
894 p!(write("{}f32", Single::from_bits(data)));
897 ty::Float(ast::FloatTy::F64) => {
898 p!(write("{}f64", Double::from_bits(data)));
902 p!(write("{}{}", data, ui));
906 let ty = self.tcx().lift_to_global(&ct.ty).unwrap();
907 let size = self.tcx().layout_of(ty::ParamEnv::empty().and(ty))
910 p!(write("{}{}", sign_extend(data, size) as i128, i));
914 p!(write("{:?}", ::std::char::from_u32(data as u32).unwrap()));
920 if let ty::Ref(_, ref_ty, _) = ct.ty.sty {
921 let byte_str = match (ct.val, &ref_ty.sty) {
922 (ConstValue::Scalar(Scalar::Ptr(ptr)), ty::Array(t, n)) if *t == u8 => {
923 let n = n.eval_usize(self.tcx(), ty::ParamEnv::empty());
926 .unwrap_memory(ptr.alloc_id)
927 .get_bytes(&self.tcx(), ptr, Size::from_bytes(n)).unwrap())
929 (ConstValue::Slice { data, start, end }, ty::Slice(t)) if *t == u8 => {
930 Some(&data.bytes[start..end])
932 (ConstValue::Slice { data, start, end }, ty::Str) => {
933 let slice = &data.bytes[start..end];
934 let s = ::std::str::from_utf8(slice)
935 .expect("non utf8 str from miri");
936 p!(write("{:?}", s));
941 if let Some(byte_str) = byte_str {
944 for e in std::ascii::escape_default(c) {
945 self.write_char(e as char)?;
952 p!(write("{:?} : ", ct.val), print(ct.ty));
958 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
959 pub struct FmtPrinter<'a, 'tcx, F>(Box<FmtPrinterData<'a, 'tcx, F>>);
961 pub struct FmtPrinterData<'a, 'tcx, F> {
968 used_region_names: FxHashSet<InternedString>,
972 pub region_highlight_mode: RegionHighlightMode,
974 pub name_resolver: Option<Box<&'a dyn Fn(ty::sty::TyVid) -> Option<String>>>,
977 impl<F> Deref for FmtPrinter<'a, 'tcx, F> {
978 type Target = FmtPrinterData<'a, 'tcx, F>;
979 fn deref(&self) -> &Self::Target {
984 impl<F> DerefMut for FmtPrinter<'_, '_, F> {
985 fn deref_mut(&mut self) -> &mut Self::Target {
990 impl<F> FmtPrinter<'a, 'tcx, F> {
991 pub fn new(tcx: TyCtxt<'tcx>, fmt: F, ns: Namespace) -> Self {
992 FmtPrinter(Box::new(FmtPrinterData {
996 in_value: ns == Namespace::ValueNS,
997 used_region_names: Default::default(),
1000 region_highlight_mode: RegionHighlightMode::default(),
1001 name_resolver: None,
1007 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1008 // (but also some things just print a `DefId` generally so maybe we need this?)
1009 fn guess_def_namespace(self, def_id: DefId) -> Namespace {
1010 match self.def_key(def_id).disambiguated_data.data {
1011 DefPathData::TypeNs(..)
1012 | DefPathData::CrateRoot
1013 | DefPathData::ImplTrait => Namespace::TypeNS,
1015 DefPathData::ValueNs(..)
1016 | DefPathData::AnonConst
1017 | DefPathData::ClosureExpr
1018 | DefPathData::Ctor => Namespace::ValueNS,
1020 DefPathData::MacroNs(..) => Namespace::MacroNS,
1022 _ => Namespace::TypeNS,
1026 /// Returns a string identifying this `DefId`. This string is
1027 /// suitable for user output.
1028 pub fn def_path_str(self, def_id: DefId) -> String {
1029 let ns = self.guess_def_namespace(def_id);
1030 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1031 let mut s = String::new();
1032 let _ = FmtPrinter::new(self, &mut s, ns)
1033 .print_def_path(def_id, &[]);
1038 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, F> {
1039 fn write_str(&mut self, s: &str) -> fmt::Result {
1040 self.fmt.write_str(s)
1044 impl<F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
1045 type Error = fmt::Error;
1050 type DynExistential = Self;
1053 fn tcx(&'a self) -> TyCtxt<'tcx> {
1060 substs: &'tcx [Kind<'tcx>],
1061 ) -> Result<Self::Path, Self::Error> {
1062 define_scoped_cx!(self);
1064 if substs.is_empty() {
1065 match self.try_print_visible_def_path(def_id)? {
1066 (cx, true) => return Ok(cx),
1067 (cx, false) => self = cx,
1071 let key = self.tcx.def_key(def_id);
1072 if let DefPathData::Impl = key.disambiguated_data.data {
1073 // Always use types for non-local impls, where types are always
1074 // available, and filename/line-number is mostly uninteresting.
1076 !def_id.is_local() || {
1077 // Otherwise, use filename/line-number if forced.
1078 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1083 // If no type info is available, fall back to
1084 // pretty printing some span information. This should
1085 // only occur very early in the compiler pipeline.
1086 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1087 let span = self.tcx.def_span(def_id);
1089 self = self.print_def_path(parent_def_id, &[])?;
1091 // HACK(eddyb) copy of `path_append` to avoid
1092 // constructing a `DisambiguatedDefPathData`.
1093 if !self.empty_path {
1094 write!(self, "::")?;
1096 write!(self, "<impl at {:?}>", span)?;
1097 self.empty_path = false;
1103 self.default_print_def_path(def_id, substs)
1108 region: ty::Region<'_>,
1109 ) -> Result<Self::Region, Self::Error> {
1110 self.pretty_print_region(region)
1116 ) -> Result<Self::Type, Self::Error> {
1117 self.pretty_print_type(ty)
1120 fn print_dyn_existential(
1122 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1123 ) -> Result<Self::DynExistential, Self::Error> {
1124 self.pretty_print_dyn_existential(predicates)
1129 ct: &'tcx ty::Const<'tcx>,
1130 ) -> Result<Self::Const, Self::Error> {
1131 self.pretty_print_const(ct)
1137 ) -> Result<Self::Path, Self::Error> {
1138 self.empty_path = true;
1139 if cnum == LOCAL_CRATE {
1140 if self.tcx.sess.rust_2018() {
1141 // We add the `crate::` keyword on Rust 2018, only when desired.
1142 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1143 write!(self, "{}", kw::Crate)?;
1144 self.empty_path = false;
1148 write!(self, "{}", self.tcx.crate_name(cnum))?;
1149 self.empty_path = false;
1156 trait_ref: Option<ty::TraitRef<'tcx>>,
1157 ) -> Result<Self::Path, Self::Error> {
1158 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1159 self.empty_path = false;
1163 fn path_append_impl(
1165 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1166 _disambiguated_data: &DisambiguatedDefPathData,
1168 trait_ref: Option<ty::TraitRef<'tcx>>,
1169 ) -> Result<Self::Path, Self::Error> {
1170 self = self.pretty_path_append_impl(|mut cx| {
1171 cx = print_prefix(cx)?;
1177 }, self_ty, trait_ref)?;
1178 self.empty_path = false;
1183 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1184 disambiguated_data: &DisambiguatedDefPathData,
1185 ) -> Result<Self::Path, Self::Error> {
1186 self = print_prefix(self)?;
1188 // Skip `::{{constructor}}` on tuple/unit structs.
1189 match disambiguated_data.data {
1190 DefPathData::Ctor => return Ok(self),
1194 // FIXME(eddyb) `name` should never be empty, but it
1195 // currently is for `extern { ... }` "foreign modules".
1196 let name = disambiguated_data.data.as_interned_str().as_str();
1197 if !name.is_empty() {
1198 if !self.empty_path {
1199 write!(self, "::")?;
1201 write!(self, "{}", name)?;
1203 // FIXME(eddyb) this will print e.g. `{{closure}}#3`, but it
1204 // might be nicer to use something else, e.g. `{closure#3}`.
1205 let dis = disambiguated_data.disambiguator;
1207 disambiguated_data.data.get_opt_name().is_none() ||
1208 dis != 0 && self.tcx.sess.verbose();
1210 write!(self, "#{}", dis)?;
1213 self.empty_path = false;
1218 fn path_generic_args(
1220 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1221 args: &[Kind<'tcx>],
1222 ) -> Result<Self::Path, Self::Error> {
1223 self = print_prefix(self)?;
1225 // Don't print `'_` if there's no unerased regions.
1226 let print_regions = args.iter().any(|arg| {
1227 match arg.unpack() {
1228 UnpackedKind::Lifetime(r) => *r != ty::ReErased,
1232 let args = args.iter().cloned().filter(|arg| {
1233 match arg.unpack() {
1234 UnpackedKind::Lifetime(_) => print_regions,
1239 if args.clone().next().is_some() {
1241 write!(self, "::")?;
1243 self.generic_delimiters(|cx| cx.comma_sep(args))
1250 impl<F: fmt::Write> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx, F> {
1251 fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> {
1252 self.0.name_resolver.as_ref().and_then(|func| func(id))
1255 fn print_value_path(
1258 substs: &'tcx [Kind<'tcx>],
1259 ) -> Result<Self::Path, Self::Error> {
1260 let was_in_value = std::mem::replace(&mut self.in_value, true);
1261 self = self.print_def_path(def_id, substs)?;
1262 self.in_value = was_in_value;
1267 fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
1269 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1271 self.pretty_in_binder(value)
1274 fn generic_delimiters(
1276 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1277 ) -> Result<Self, Self::Error> {
1280 let was_in_value = std::mem::replace(&mut self.in_value, false);
1281 let mut inner = f(self)?;
1282 inner.in_value = was_in_value;
1284 write!(inner, ">")?;
1288 fn region_should_not_be_omitted(
1290 region: ty::Region<'_>,
1292 let highlight = self.region_highlight_mode;
1293 if highlight.region_highlighted(region).is_some() {
1297 if self.tcx.sess.verbose() {
1301 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1304 ty::ReEarlyBound(ref data) => {
1305 data.name.as_symbol() != kw::Invalid &&
1306 data.name.as_symbol() != kw::UnderscoreLifetime
1309 ty::ReLateBound(_, br) |
1310 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1311 ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1312 if let ty::BrNamed(_, name) = br {
1313 if name.as_symbol() != kw::Invalid &&
1314 name.as_symbol() != kw::UnderscoreLifetime {
1319 if let Some((region, _)) = highlight.highlight_bound_region {
1329 ty::ReVar(_) if identify_regions => true,
1333 ty::ReErased => false,
1337 ty::ReClosureBound(_) => true,
1342 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1343 impl<F: fmt::Write> FmtPrinter<'_, '_, F> {
1344 pub fn pretty_print_region(
1346 region: ty::Region<'_>,
1347 ) -> Result<Self, fmt::Error> {
1348 define_scoped_cx!(self);
1350 // Watch out for region highlights.
1351 let highlight = self.region_highlight_mode;
1352 if let Some(n) = highlight.region_highlighted(region) {
1353 p!(write("'{}", n));
1357 if self.tcx.sess.verbose() {
1358 p!(write("{:?}", region));
1362 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1364 // These printouts are concise. They do not contain all the information
1365 // the user might want to diagnose an error, but there is basically no way
1366 // to fit that into a short string. Hence the recommendation to use
1367 // `explain_region()` or `note_and_explain_region()`.
1369 ty::ReEarlyBound(ref data) => {
1370 if data.name.as_symbol() != kw::Invalid {
1371 p!(write("{}", data.name));
1375 ty::ReLateBound(_, br) |
1376 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1377 ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1378 if let ty::BrNamed(_, name) = br {
1379 if name.as_symbol() != kw::Invalid &&
1380 name.as_symbol() != kw::UnderscoreLifetime {
1381 p!(write("{}", name));
1386 if let Some((region, counter)) = highlight.highlight_bound_region {
1388 p!(write("'{}", counter));
1393 ty::ReScope(scope) if identify_regions => {
1395 region::ScopeData::Node =>
1396 p!(write("'{}s", scope.item_local_id().as_usize())),
1397 region::ScopeData::CallSite =>
1398 p!(write("'{}cs", scope.item_local_id().as_usize())),
1399 region::ScopeData::Arguments =>
1400 p!(write("'{}as", scope.item_local_id().as_usize())),
1401 region::ScopeData::Destruction =>
1402 p!(write("'{}ds", scope.item_local_id().as_usize())),
1403 region::ScopeData::Remainder(first_statement_index) => p!(write(
1405 scope.item_local_id().as_usize(),
1406 first_statement_index.index()
1411 ty::ReVar(region_vid) if identify_regions => {
1412 p!(write("{:?}", region_vid));
1419 p!(write("'static"));
1423 p!(write("'<empty>"));
1427 // The user should never encounter these in unsubstituted form.
1428 ty::ReClosureBound(vid) => {
1429 p!(write("{:?}", vid));
1440 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1441 // `region_index` and `used_region_names`.
1442 impl<F: fmt::Write> FmtPrinter<'_, 'tcx, F> {
1443 pub fn pretty_in_binder<T>(mut self, value: &ty::Binder<T>) -> Result<Self, fmt::Error>
1445 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1447 fn name_by_region_index(index: usize) -> InternedString {
1449 0 => InternedString::intern("'r"),
1450 1 => InternedString::intern("'s"),
1451 i => InternedString::intern(&format!("'t{}", i-2)),
1455 // Replace any anonymous late-bound regions with named
1456 // variants, using gensym'd identifiers, so that we can
1457 // clearly differentiate between named and unnamed regions in
1458 // the output. We'll probably want to tweak this over time to
1459 // decide just how much information to give.
1460 if self.binder_depth == 0 {
1461 self.prepare_late_bound_region_info(value);
1464 let mut empty = true;
1465 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1466 write!(cx, "{}", if empty {
1474 define_scoped_cx!(self);
1476 let old_region_index = self.region_index;
1477 let mut region_index = old_region_index;
1478 let new_value = self.tcx.replace_late_bound_regions(value, |br| {
1479 let _ = start_or_continue(&mut self, "for<", ", ");
1481 ty::BrNamed(_, name) => {
1482 let _ = write!(self, "{}", name);
1488 let name = name_by_region_index(region_index);
1490 if !self.used_region_names.contains(&name) {
1494 let _ = write!(self, "{}", name);
1495 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1498 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
1500 start_or_continue(&mut self, "", "> ")?;
1502 self.binder_depth += 1;
1503 self.region_index = region_index;
1504 let mut inner = new_value.print(self)?;
1505 inner.region_index = old_region_index;
1506 inner.binder_depth -= 1;
1510 fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
1511 where T: TypeFoldable<'tcx>
1514 struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet<InternedString>);
1515 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> {
1516 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
1518 ty::ReLateBound(_, ty::BrNamed(_, name)) => {
1519 self.0.insert(name);
1523 r.super_visit_with(self)
1527 self.used_region_names.clear();
1528 let mut collector = LateBoundRegionNameCollector(&mut self.used_region_names);
1529 value.visit_with(&mut collector);
1530 self.region_index = 0;
1534 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<T>
1536 T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
1539 type Error = P::Error;
1540 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
1545 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
1547 T: Print<'tcx, P, Output = P, Error = P::Error>,
1548 U: Print<'tcx, P, Output = P, Error = P::Error>,
1551 type Error = P::Error;
1552 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
1553 define_scoped_cx!(cx);
1554 p!(print(self.0), write(" : "), print(self.1));
1559 macro_rules! forward_display_to_print {
1561 $(impl fmt::Display for $ty {
1562 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1563 ty::tls::with(|tcx| {
1565 .expect("could not lift for printing")
1566 .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1574 macro_rules! define_print_and_forward_display {
1575 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
1576 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
1578 type Error = fmt::Error;
1579 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
1580 #[allow(unused_mut)]
1582 define_scoped_cx!($cx);
1584 #[allow(unreachable_code)]
1589 forward_display_to_print!($($ty),+);
1593 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
1594 impl fmt::Display for ty::RegionKind {
1595 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1596 ty::tls::with(|tcx| {
1597 self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1603 forward_display_to_print! {
1605 &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1606 &'tcx ty::Const<'tcx>,
1608 // HACK(eddyb) these are exhaustive instead of generic,
1609 // because `for<'tcx>` isn't possible yet.
1610 ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
1611 ty::Binder<ty::TraitRef<'tcx>>,
1612 ty::Binder<ty::FnSig<'tcx>>,
1613 ty::Binder<ty::TraitPredicate<'tcx>>,
1614 ty::Binder<ty::SubtypePredicate<'tcx>>,
1615 ty::Binder<ty::ProjectionPredicate<'tcx>>,
1616 ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1617 ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
1619 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1620 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1623 define_print_and_forward_display! {
1626 &'tcx ty::List<Ty<'tcx>> {
1628 let mut tys = self.iter();
1629 if let Some(&ty) = tys.next() {
1632 p!(write(", "), print(ty));
1638 ty::TypeAndMut<'tcx> {
1639 p!(write("{}", if self.mutbl == hir::MutMutable { "mut " } else { "" }),
1643 ty::ExistentialTraitRef<'tcx> {
1644 // Use a type that can't appear in defaults of type parameters.
1645 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1646 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
1647 p!(print(trait_ref))
1650 ty::ExistentialProjection<'tcx> {
1651 let name = cx.tcx().associated_item(self.item_def_id).ident;
1652 p!(write("{} = ", name), print(self.ty))
1655 ty::ExistentialPredicate<'tcx> {
1657 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
1658 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
1659 ty::ExistentialPredicate::AutoTrait(def_id) => {
1660 p!(print_def_path(def_id, &[]));
1666 if self.unsafety == hir::Unsafety::Unsafe {
1667 p!(write("unsafe "));
1670 if self.abi != Abi::Rust {
1671 p!(write("extern {} ", self.abi));
1674 p!(write("fn"), pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
1678 if cx.tcx().sess.verbose() {
1679 p!(write("{:?}", self));
1683 ty::TyVar(_) => p!(write("_")),
1684 ty::IntVar(_) => p!(write("{}", "{integer}")),
1685 ty::FloatVar(_) => p!(write("{}", "{float}")),
1686 ty::FreshTy(v) => p!(write("FreshTy({})", v)),
1687 ty::FreshIntTy(v) => p!(write("FreshIntTy({})", v)),
1688 ty::FreshFloatTy(v) => p!(write("FreshFloatTy({})", v))
1692 ty::TraitRef<'tcx> {
1693 p!(print_def_path(self.def_id, self.substs));
1697 p!(write("{}", self.name))
1701 p!(write("{}", self.name))
1704 ty::SubtypePredicate<'tcx> {
1705 p!(print(self.a), write(" <: "), print(self.b))
1708 ty::TraitPredicate<'tcx> {
1709 p!(print(self.trait_ref.self_ty()), write(": "), print(self.trait_ref))
1712 ty::ProjectionPredicate<'tcx> {
1713 p!(print(self.projection_ty), write(" == "), print(self.ty))
1716 ty::ProjectionTy<'tcx> {
1717 p!(print_def_path(self.item_def_id, self.substs));
1722 ty::ClosureKind::Fn => p!(write("Fn")),
1723 ty::ClosureKind::FnMut => p!(write("FnMut")),
1724 ty::ClosureKind::FnOnce => p!(write("FnOnce")),
1728 ty::Predicate<'tcx> {
1730 ty::Predicate::Trait(ref data) => p!(print(data)),
1731 ty::Predicate::Subtype(ref predicate) => p!(print(predicate)),
1732 ty::Predicate::RegionOutlives(ref predicate) => p!(print(predicate)),
1733 ty::Predicate::TypeOutlives(ref predicate) => p!(print(predicate)),
1734 ty::Predicate::Projection(ref predicate) => p!(print(predicate)),
1735 ty::Predicate::WellFormed(ty) => p!(print(ty), write(" well-formed")),
1736 ty::Predicate::ObjectSafe(trait_def_id) => {
1737 p!(write("the trait `"),
1738 print_def_path(trait_def_id, &[]),
1739 write("` is object-safe"))
1741 ty::Predicate::ClosureKind(closure_def_id, _closure_substs, kind) => {
1742 p!(write("the closure `"),
1743 print_value_path(closure_def_id, &[]),
1744 write("` implements the trait `{}`", kind))
1746 ty::Predicate::ConstEvaluatable(def_id, substs) => {
1747 p!(write("the constant `"),
1748 print_value_path(def_id, substs),
1749 write("` can be evaluated"))
1755 match self.unpack() {
1756 UnpackedKind::Lifetime(lt) => p!(print(lt)),
1757 UnpackedKind::Type(ty) => p!(print(ty)),
1758 UnpackedKind::Const(ct) => p!(print(ct)),