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<'gcx: 'tcx, 'tcx>:
175 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)
191 value: &ty::Binder<T>,
192 ) -> Result<Self, Self::Error>
193 where T: Print<'gcx, 'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>
195 value.skip_binder().print(self)
198 /// Print comma-separated elements.
201 mut elems: impl Iterator<Item = T>,
202 ) -> Result<Self, Self::Error>
203 where T: Print<'gcx, 'tcx, Self, Output = Self, Error = Self::Error>
205 if let Some(first) = elems.next() {
206 self = first.print(self)?;
208 self.write_str(", ")?;
209 self = elem.print(self)?;
215 /// Print `<...>` around what `f` prints.
216 fn generic_delimiters(
218 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
219 ) -> Result<Self, Self::Error>;
221 /// Return `true` if the region should be printed in
222 /// optional positions, e.g. `&'a T` or `dyn Tr + 'b`.
223 /// This is typically the case for all non-`'_` regions.
224 fn region_should_not_be_omitted(
226 region: ty::Region<'_>,
229 // Defaults (should not be overriden):
231 /// If possible, this returns a global path resolving to `def_id` that is visible
232 /// from at least one local module and returns true. If the crate defining `def_id` is
233 /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
234 fn try_print_visible_def_path(
237 ) -> Result<(Self, bool), Self::Error> {
238 define_scoped_cx!(self);
240 debug!("try_print_visible_def_path: def_id={:?}", def_id);
242 // If `def_id` is a direct or injected extern crate, return the
243 // path to the crate followed by the path to the item within the crate.
244 if def_id.index == CRATE_DEF_INDEX {
245 let cnum = def_id.krate;
247 if cnum == LOCAL_CRATE {
248 return Ok((self.path_crate(cnum)?, true));
251 // In local mode, when we encounter a crate other than
252 // LOCAL_CRATE, execution proceeds in one of two ways:
254 // 1. for a direct dependency, where user added an
255 // `extern crate` manually, we put the `extern
256 // crate` as the parent. So you wind up with
257 // something relative to the current crate.
258 // 2. for an extern inferred from a path or an indirect crate,
259 // where there is no explicit `extern crate`, we just prepend
261 match self.tcx().extern_crate(def_id) {
263 src: ExternCrateSource::Extern(def_id),
268 debug!("try_print_visible_def_path: def_id={:?}", def_id);
269 return Ok((if !span.is_dummy() {
270 self.print_def_path(def_id, &[])?
272 self.path_crate(cnum)?
276 return Ok((self.path_crate(cnum)?, true));
282 if def_id.is_local() {
283 return Ok((self, false));
286 let visible_parent_map = self.tcx().visible_parent_map(LOCAL_CRATE);
288 let mut cur_def_key = self.tcx().def_key(def_id);
289 debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
291 // For a constructor we want the name of its parent rather than <unnamed>.
292 match cur_def_key.disambiguated_data.data {
293 DefPathData::Ctor => {
296 index: cur_def_key.parent
297 .expect("DefPathData::Ctor/VariantData missing a parent"),
300 cur_def_key = self.tcx().def_key(parent);
305 let visible_parent = match visible_parent_map.get(&def_id).cloned() {
306 Some(parent) => parent,
307 None => return Ok((self, false)),
309 // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
310 // knowing ahead of time whether the entire path will succeed or not.
311 // To support printers that do not implement `PrettyPrinter`, a `Vec` or
312 // linked list on the stack would need to be built, before any printing.
313 match self.try_print_visible_def_path(visible_parent)? {
314 (cx, false) => return Ok((cx, false)),
315 (cx, true) => self = cx,
317 let actual_parent = self.tcx().parent(def_id);
319 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
320 visible_parent, actual_parent,
323 let mut data = cur_def_key.disambiguated_data.data;
325 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
326 data, visible_parent, actual_parent,
330 // In order to output a path that could actually be imported (valid and visible),
331 // we need to handle re-exports correctly.
333 // For example, take `std::os::unix::process::CommandExt`, this trait is actually
334 // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
336 // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is
337 // private so the "true" path to `CommandExt` isn't accessible.
339 // In this case, the `visible_parent_map` will look something like this:
341 // (child) -> (parent)
342 // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
343 // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
344 // `std::sys::unix::ext` -> `std::os`
346 // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
349 // When printing the path to `CommandExt` and looking at the `cur_def_key` that
350 // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
351 // to the parent - resulting in a mangled path like
352 // `std::os::ext::process::CommandExt`.
354 // Instead, we must detect that there was a re-export and instead print `unix`
355 // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
356 // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
357 // the visible parent (`std::os`). If these do not match, then we iterate over
358 // the children of the visible parent (as was done when computing
359 // `visible_parent_map`), looking for the specific child we currently have and then
360 // have access to the re-exported name.
361 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
362 let reexport = self.tcx().item_children(visible_parent)
364 .find(|child| child.res.def_id() == def_id)
365 .map(|child| child.ident.as_interned_str());
366 if let Some(reexport) = reexport {
370 // Re-exported `extern crate` (#43189).
371 DefPathData::CrateRoot => {
372 data = DefPathData::TypeNs(
373 self.tcx().original_crate_name(def_id.krate).as_interned_str(),
378 debug!("try_print_visible_def_path: data={:?}", data);
380 Ok((self.path_append(Ok, &DisambiguatedDefPathData {
386 fn pretty_path_qualified(
389 trait_ref: Option<ty::TraitRef<'tcx>>,
390 ) -> Result<Self::Path, Self::Error> {
391 if trait_ref.is_none() {
392 // Inherent impls. Try to print `Foo::bar` for an inherent
393 // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
394 // anything other than a simple path.
396 ty::Adt(..) | ty::Foreign(_) |
397 ty::Bool | ty::Char | ty::Str |
398 ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
399 return self_ty.print(self);
406 self.generic_delimiters(|mut cx| {
407 define_scoped_cx!(cx);
410 if let Some(trait_ref) = trait_ref {
411 p!(write(" as "), print(trait_ref));
417 fn pretty_path_append_impl(
419 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
421 trait_ref: Option<ty::TraitRef<'tcx>>,
422 ) -> Result<Self::Path, Self::Error> {
423 self = print_prefix(self)?;
425 self.generic_delimiters(|mut cx| {
426 define_scoped_cx!(cx);
429 if let Some(trait_ref) = trait_ref {
430 p!(print(trait_ref), write(" for "));
438 fn pretty_print_type(
441 ) -> Result<Self::Type, Self::Error> {
442 define_scoped_cx!(self);
445 ty::Bool => p!(write("bool")),
446 ty::Char => p!(write("char")),
447 ty::Int(t) => p!(write("{}", t.ty_to_string())),
448 ty::Uint(t) => p!(write("{}", t.ty_to_string())),
449 ty::Float(t) => p!(write("{}", t.ty_to_string())),
450 ty::RawPtr(ref tm) => {
451 p!(write("*{} ", match tm.mutbl {
452 hir::MutMutable => "mut",
453 hir::MutImmutable => "const",
457 ty::Ref(r, ty, mutbl) => {
459 if self.region_should_not_be_omitted(r) {
460 p!(print(r), write(" "));
462 p!(print(ty::TypeAndMut { ty, mutbl }))
464 ty::Never => p!(write("!")),
465 ty::Tuple(ref tys) => {
467 let mut tys = tys.iter();
468 if let Some(&ty) = tys.next() {
469 p!(print(ty), write(","));
470 if let Some(&ty) = tys.next() {
471 p!(write(" "), print(ty));
473 p!(write(", "), print(ty));
479 ty::FnDef(def_id, substs) => {
480 let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs);
481 p!(print(sig), write(" {{"), print_value_path(def_id, substs), write("}}"));
483 ty::FnPtr(ref bare_fn) => {
486 ty::Infer(infer_ty) => {
487 if let ty::TyVar(ty_vid) = infer_ty {
488 if let Some(name) = self.infer_ty_name(ty_vid) {
489 p!(write("{}", name))
491 p!(write("{}", infer_ty))
494 p!(write("{}", infer_ty))
497 ty::Error => p!(write("[type error]")),
498 ty::Param(ref param_ty) => p!(write("{}", param_ty)),
499 ty::Bound(debruijn, bound_ty) => {
500 match bound_ty.kind {
501 ty::BoundTyKind::Anon => {
502 if debruijn == ty::INNERMOST {
503 p!(write("^{}", bound_ty.var.index()))
505 p!(write("^{}_{}", debruijn.index(), bound_ty.var.index()))
509 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
512 ty::Adt(def, substs) => {
513 p!(print_def_path(def.did, substs));
515 ty::Dynamic(data, r) => {
516 let print_r = self.region_should_not_be_omitted(r);
520 p!(write("dyn "), print(data));
522 p!(write(" + "), print(r), write(")"));
525 ty::Foreign(def_id) => {
526 p!(print_def_path(def_id, &[]));
528 ty::Projection(ref data) => p!(print(data)),
529 ty::UnnormalizedProjection(ref data) => {
530 p!(write("Unnormalized("), print(data), write(")"))
532 ty::Placeholder(placeholder) => {
533 p!(write("Placeholder({:?})", placeholder))
535 ty::Opaque(def_id, substs) => {
536 // FIXME(eddyb) print this with `print_def_path`.
537 if self.tcx().sess.verbose() {
538 p!(write("Opaque({:?}, {:?})", def_id, substs));
542 let def_key = self.tcx().def_key(def_id);
543 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
544 p!(write("{}", name));
545 let mut substs = substs.iter();
546 // FIXME(eddyb) print this with `print_def_path`.
547 if let Some(first) = substs.next() {
550 for subst in substs {
551 p!(write(", "), print(subst));
557 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
558 // by looking up the projections associated with the def_id.
559 let bounds = self.tcx().predicates_of(def_id).instantiate(self.tcx(), substs);
561 let mut first = true;
562 let mut is_sized = false;
564 for predicate in bounds.predicates {
565 if let Some(trait_ref) = predicate.to_opt_poly_trait_ref() {
566 // Don't print +Sized, but rather +?Sized if absent.
567 if Some(trait_ref.def_id()) == self.tcx().lang_items().sized_trait() {
573 write("{}", if first { " " } else { "+" }),
579 p!(write("{}?Sized", if first { " " } else { "+" }));
584 ty::Str => p!(write("str")),
585 ty::Generator(did, substs, movability) => {
586 let upvar_tys = substs.upvar_tys(did, self.tcx());
587 let witness = substs.witness(did, self.tcx());
588 if movability == hir::GeneratorMovability::Movable {
589 p!(write("[generator"));
591 p!(write("[static generator"));
594 // FIXME(eddyb) should use `def_span`.
595 if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
596 p!(write("@{:?}", self.tcx().hir().span_by_hir_id(hir_id)));
598 for (&var_id, upvar_ty) in self.tcx().upvars(did)
601 .flat_map(|v| v.keys())
607 self.tcx().hir().name_by_hir_id(var_id)),
612 // cross-crate closure types should only be
613 // visible in codegen bug reports, I imagine.
614 p!(write("@{:?}", did));
616 for (index, upvar_ty) in upvar_tys.enumerate() {
618 write("{}{}:", sep, index),
624 p!(write(" "), print(witness), write("]"))
626 ty::GeneratorWitness(types) => {
627 p!(in_binder(&types));
629 ty::Closure(did, substs) => {
630 let upvar_tys = substs.upvar_tys(did, self.tcx());
631 p!(write("[closure"));
633 // FIXME(eddyb) should use `def_span`.
634 if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
635 if self.tcx().sess.opts.debugging_opts.span_free_formats {
636 p!(write("@{:?}", hir_id));
638 p!(write("@{:?}", self.tcx().hir().span_by_hir_id(hir_id)));
641 for (&var_id, upvar_ty) in self.tcx().upvars(did)
644 .flat_map(|v| v.keys())
650 self.tcx().hir().name_by_hir_id(var_id)),
655 // cross-crate closure types should only be
656 // visible in codegen bug reports, I imagine.
657 p!(write("@{:?}", did));
659 for (index, upvar_ty) in upvar_tys.enumerate() {
661 write("{}{}:", sep, index),
667 if self.tcx().sess.verbose() {
669 " closure_kind_ty={:?} closure_sig_ty={:?}",
670 substs.closure_kind_ty(did, self.tcx()),
671 substs.closure_sig_ty(did, self.tcx())
677 ty::Array(ty, sz) => {
678 p!(write("["), print(ty), write("; "));
679 if let Some(n) = sz.assert_usize(self.tcx()) {
687 p!(write("["), print(ty), write("]"))
694 fn infer_ty_name(&self, _: ty::TyVid) -> Option<String> {
698 fn pretty_print_dyn_existential(
700 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
701 ) -> Result<Self::DynExistential, Self::Error> {
702 define_scoped_cx!(self);
704 // Generate the main trait ref, including associated types.
705 let mut first = true;
707 if let Some(principal) = predicates.principal() {
708 p!(print_def_path(principal.def_id, &[]));
710 let mut resugared = false;
712 // Special-case `Fn(...) -> ...` and resugar it.
713 let fn_trait_kind = self.tcx().lang_items().fn_trait_kind(principal.def_id);
714 if !self.tcx().sess.verbose() && fn_trait_kind.is_some() {
715 if let ty::Tuple(ref args) = principal.substs.type_at(0).sty {
716 let mut projections = predicates.projection_bounds();
717 if let (Some(proj), None) = (projections.next(), projections.next()) {
718 let tys: Vec<_> = args.iter().map(|k| k.expect_ty()).collect();
719 p!(pretty_fn_sig(&tys, false, proj.ty));
725 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
726 // in order to place the projections inside the `<...>`.
728 // Use a type that can't appear in defaults of type parameters.
729 let dummy_self = self.tcx().mk_ty_infer(ty::FreshTy(0));
730 let principal = principal.with_self_ty(self.tcx(), dummy_self);
732 let args = self.generic_args_to_print(
733 self.tcx().generics_of(principal.def_id),
737 // Don't print `'_` if there's no unerased regions.
738 let print_regions = args.iter().any(|arg| {
740 UnpackedKind::Lifetime(r) => *r != ty::ReErased,
744 let mut args = args.iter().cloned().filter(|arg| {
746 UnpackedKind::Lifetime(_) => print_regions,
750 let mut projections = predicates.projection_bounds();
752 let arg0 = args.next();
753 let projection0 = projections.next();
754 if arg0.is_some() || projection0.is_some() {
755 let args = arg0.into_iter().chain(args);
756 let projections = projection0.into_iter().chain(projections);
758 p!(generic_delimiters(|mut cx| {
759 cx = cx.comma_sep(args)?;
760 if arg0.is_some() && projection0.is_some() {
763 cx.comma_sep(projections)
771 // FIXME(eddyb) avoid printing twice (needed to ensure
772 // that the auto traits are sorted *and* printed via cx).
773 let mut auto_traits: Vec<_> = predicates.auto_traits().map(|did| {
774 (self.tcx().def_path_str(did), did)
777 // The auto traits come ordered by `DefPathHash`. While
778 // `DefPathHash` is *stable* in the sense that it depends on
779 // neither the host nor the phase of the moon, it depends
780 // "pseudorandomly" on the compiler version and the target.
782 // To avoid that causing instabilities in compiletest
783 // output, sort the auto-traits alphabetically.
786 for (_, def_id) in auto_traits {
792 p!(print_def_path(def_id, &[]));
803 ) -> Result<Self, Self::Error> {
804 define_scoped_cx!(self);
807 let mut inputs = inputs.iter();
808 if let Some(&ty) = inputs.next() {
811 p!(write(", "), print(ty));
818 if !output.is_unit() {
819 p!(write(" -> "), print(output));
825 fn pretty_print_const(
827 ct: &'tcx ty::Const<'tcx>,
828 ) -> Result<Self::Const, Self::Error> {
829 define_scoped_cx!(self);
831 let u8 = self.tcx().types.u8;
832 if let ty::FnDef(did, substs) = ct.ty.sty {
833 p!(print_value_path(did, substs));
836 if let ConstValue::Unevaluated(did, substs) = ct.val {
837 match self.tcx().def_kind(did) {
838 | Some(DefKind::Static)
839 | Some(DefKind::Const)
840 | Some(DefKind::AssocConst) => p!(print_value_path(did, substs)),
841 _ => if did.is_local() {
842 let span = self.tcx().def_span(did);
843 if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span) {
844 p!(write("{}", snip))
846 p!(write("_: "), print(ct.ty))
849 p!(write("_: "), print(ct.ty))
854 if let ConstValue::Infer(..) = ct.val {
855 p!(write("_: "), print(ct.ty));
858 if let ConstValue::Param(ParamConst { name, .. }) = ct.val {
859 p!(write("{}", name));
862 if let ConstValue::Scalar(Scalar::Raw { data, .. }) = ct.val {
865 p!(write("{}", if data == 0 { "false" } else { "true" }));
868 ty::Float(ast::FloatTy::F32) => {
869 p!(write("{}f32", Single::from_bits(data)));
872 ty::Float(ast::FloatTy::F64) => {
873 p!(write("{}f64", Double::from_bits(data)));
877 p!(write("{}{}", data, ui));
881 let ty = self.tcx().lift_to_global(&ct.ty).unwrap();
882 let size = self.tcx().layout_of(ty::ParamEnv::empty().and(ty))
885 p!(write("{}{}", sign_extend(data, size) as i128, i));
889 p!(write("{:?}", ::std::char::from_u32(data as u32).unwrap()));
895 if let ty::Ref(_, ref_ty, _) = ct.ty.sty {
896 let byte_str = match (ct.val, &ref_ty.sty) {
897 (ConstValue::Scalar(Scalar::Ptr(ptr)), ty::Array(t, n)) if *t == u8 => {
898 let n = n.unwrap_usize(self.tcx());
901 .unwrap_memory(ptr.alloc_id)
902 .get_bytes(&self.tcx(), ptr, Size::from_bytes(n)).unwrap())
904 (ConstValue::Slice { data, start, end }, ty::Slice(t)) if *t == u8 => {
905 Some(&data.bytes[start..end])
907 (ConstValue::Slice { data, start, end }, ty::Str) => {
908 let slice = &data.bytes[start..end];
909 let s = ::std::str::from_utf8(slice)
910 .expect("non utf8 str from miri");
911 p!(write("{:?}", s));
916 if let Some(byte_str) = byte_str {
919 for e in std::ascii::escape_default(c) {
920 self.write_char(e as char)?;
927 p!(write("{:?} : ", ct.val), print(ct.ty));
933 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
934 pub struct FmtPrinter<'a, 'gcx, 'tcx, F>(Box<FmtPrinterData<'a, 'gcx, 'tcx, F>>);
936 pub struct FmtPrinterData<'a, 'gcx, 'tcx, F> {
937 tcx: TyCtxt<'a, 'gcx, 'tcx>,
943 used_region_names: FxHashSet<InternedString>,
947 pub region_highlight_mode: RegionHighlightMode,
949 pub name_resolver: Option<Box<&'a dyn Fn(ty::sty::TyVid) -> Option<String>>>,
952 impl<F> Deref for FmtPrinter<'a, 'gcx, 'tcx, F> {
953 type Target = FmtPrinterData<'a, 'gcx, 'tcx, F>;
954 fn deref(&self) -> &Self::Target {
959 impl<F> DerefMut for FmtPrinter<'_, '_, '_, F> {
960 fn deref_mut(&mut self) -> &mut Self::Target {
965 impl<F> FmtPrinter<'a, 'gcx, 'tcx, F> {
966 pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>, fmt: F, ns: Namespace) -> Self {
967 FmtPrinter(Box::new(FmtPrinterData {
971 in_value: ns == Namespace::ValueNS,
972 used_region_names: Default::default(),
975 region_highlight_mode: RegionHighlightMode::default(),
981 impl TyCtxt<'_, '_, '_> {
982 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
983 // (but also some things just print a `DefId` generally so maybe we need this?)
984 fn guess_def_namespace(self, def_id: DefId) -> Namespace {
985 match self.def_key(def_id).disambiguated_data.data {
986 DefPathData::TypeNs(..)
987 | DefPathData::CrateRoot
988 | DefPathData::ImplTrait => Namespace::TypeNS,
990 DefPathData::ValueNs(..)
991 | DefPathData::AnonConst
992 | DefPathData::ClosureExpr
993 | DefPathData::Ctor => Namespace::ValueNS,
995 DefPathData::MacroNs(..) => Namespace::MacroNS,
997 _ => Namespace::TypeNS,
1001 /// Returns a string identifying this `DefId`. This string is
1002 /// suitable for user output.
1003 pub fn def_path_str(self, def_id: DefId) -> String {
1004 let ns = self.guess_def_namespace(def_id);
1005 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1006 let mut s = String::new();
1007 let _ = FmtPrinter::new(self, &mut s, ns)
1008 .print_def_path(def_id, &[]);
1013 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, '_, F> {
1014 fn write_str(&mut self, s: &str) -> fmt::Result {
1015 self.fmt.write_str(s)
1019 impl<F: fmt::Write> Printer<'gcx, 'tcx> for FmtPrinter<'_, 'gcx, 'tcx, F> {
1020 type Error = fmt::Error;
1025 type DynExistential = Self;
1028 fn tcx(&'a self) -> TyCtxt<'a, 'gcx, 'tcx> {
1035 substs: &'tcx [Kind<'tcx>],
1036 ) -> Result<Self::Path, Self::Error> {
1037 define_scoped_cx!(self);
1039 if substs.is_empty() {
1040 match self.try_print_visible_def_path(def_id)? {
1041 (cx, true) => return Ok(cx),
1042 (cx, false) => self = cx,
1046 let key = self.tcx.def_key(def_id);
1047 if let DefPathData::Impl = key.disambiguated_data.data {
1048 // Always use types for non-local impls, where types are always
1049 // available, and filename/line-number is mostly uninteresting.
1051 !def_id.is_local() || {
1052 // Otherwise, use filename/line-number if forced.
1053 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1058 // If no type info is available, fall back to
1059 // pretty printing some span information. This should
1060 // only occur very early in the compiler pipeline.
1061 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1062 let span = self.tcx.def_span(def_id);
1064 self = self.print_def_path(parent_def_id, &[])?;
1066 // HACK(eddyb) copy of `path_append` to avoid
1067 // constructing a `DisambiguatedDefPathData`.
1068 if !self.empty_path {
1069 write!(self, "::")?;
1071 write!(self, "<impl at {:?}>", span)?;
1072 self.empty_path = false;
1078 self.default_print_def_path(def_id, substs)
1083 region: ty::Region<'_>,
1084 ) -> Result<Self::Region, Self::Error> {
1085 self.pretty_print_region(region)
1091 ) -> Result<Self::Type, Self::Error> {
1092 self.pretty_print_type(ty)
1095 fn print_dyn_existential(
1097 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1098 ) -> Result<Self::DynExistential, Self::Error> {
1099 self.pretty_print_dyn_existential(predicates)
1104 ct: &'tcx ty::Const<'tcx>,
1105 ) -> Result<Self::Const, Self::Error> {
1106 self.pretty_print_const(ct)
1112 ) -> Result<Self::Path, Self::Error> {
1113 self.empty_path = true;
1114 if cnum == LOCAL_CRATE {
1115 if self.tcx.sess.rust_2018() {
1116 // We add the `crate::` keyword on Rust 2018, only when desired.
1117 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1118 write!(self, "{}", kw::Crate)?;
1119 self.empty_path = false;
1123 write!(self, "{}", self.tcx.crate_name(cnum))?;
1124 self.empty_path = false;
1131 trait_ref: Option<ty::TraitRef<'tcx>>,
1132 ) -> Result<Self::Path, Self::Error> {
1133 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1134 self.empty_path = false;
1138 fn path_append_impl(
1140 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1141 _disambiguated_data: &DisambiguatedDefPathData,
1143 trait_ref: Option<ty::TraitRef<'tcx>>,
1144 ) -> Result<Self::Path, Self::Error> {
1145 self = self.pretty_path_append_impl(|mut cx| {
1146 cx = print_prefix(cx)?;
1152 }, self_ty, trait_ref)?;
1153 self.empty_path = false;
1158 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1159 disambiguated_data: &DisambiguatedDefPathData,
1160 ) -> Result<Self::Path, Self::Error> {
1161 self = print_prefix(self)?;
1163 // Skip `::{{constructor}}` on tuple/unit structs.
1164 match disambiguated_data.data {
1165 DefPathData::Ctor => return Ok(self),
1169 // FIXME(eddyb) `name` should never be empty, but it
1170 // currently is for `extern { ... }` "foreign modules".
1171 let name = disambiguated_data.data.as_interned_str().as_str();
1172 if !name.is_empty() {
1173 if !self.empty_path {
1174 write!(self, "::")?;
1176 write!(self, "{}", name)?;
1178 // FIXME(eddyb) this will print e.g. `{{closure}}#3`, but it
1179 // might be nicer to use something else, e.g. `{closure#3}`.
1180 let dis = disambiguated_data.disambiguator;
1182 disambiguated_data.data.get_opt_name().is_none() ||
1183 dis != 0 && self.tcx.sess.verbose();
1185 write!(self, "#{}", dis)?;
1188 self.empty_path = false;
1193 fn path_generic_args(
1195 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1196 args: &[Kind<'tcx>],
1197 ) -> Result<Self::Path, Self::Error> {
1198 self = print_prefix(self)?;
1200 // Don't print `'_` if there's no unerased regions.
1201 let print_regions = args.iter().any(|arg| {
1202 match arg.unpack() {
1203 UnpackedKind::Lifetime(r) => *r != ty::ReErased,
1207 let args = args.iter().cloned().filter(|arg| {
1208 match arg.unpack() {
1209 UnpackedKind::Lifetime(_) => print_regions,
1214 if args.clone().next().is_some() {
1216 write!(self, "::")?;
1218 self.generic_delimiters(|cx| cx.comma_sep(args))
1225 impl<F: fmt::Write> PrettyPrinter<'gcx, 'tcx> for FmtPrinter<'_, 'gcx, 'tcx, F> {
1226 fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> {
1227 self.0.name_resolver.as_ref().and_then(|func| func(id))
1230 fn print_value_path(
1233 substs: &'tcx [Kind<'tcx>],
1234 ) -> Result<Self::Path, Self::Error> {
1235 let was_in_value = std::mem::replace(&mut self.in_value, true);
1236 self = self.print_def_path(def_id, substs)?;
1237 self.in_value = was_in_value;
1244 value: &ty::Binder<T>,
1245 ) -> Result<Self, Self::Error>
1246 where T: Print<'gcx, 'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>
1248 self.pretty_in_binder(value)
1251 fn generic_delimiters(
1253 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1254 ) -> Result<Self, Self::Error> {
1257 let was_in_value = std::mem::replace(&mut self.in_value, false);
1258 let mut inner = f(self)?;
1259 inner.in_value = was_in_value;
1261 write!(inner, ">")?;
1265 fn region_should_not_be_omitted(
1267 region: ty::Region<'_>,
1269 let highlight = self.region_highlight_mode;
1270 if highlight.region_highlighted(region).is_some() {
1274 if self.tcx.sess.verbose() {
1278 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1281 ty::ReEarlyBound(ref data) => {
1282 data.name.as_symbol() != kw::Invalid &&
1283 data.name.as_symbol() != kw::UnderscoreLifetime
1286 ty::ReLateBound(_, br) |
1287 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1288 ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1289 if let ty::BrNamed(_, name) = br {
1290 if name.as_symbol() != kw::Invalid &&
1291 name.as_symbol() != kw::UnderscoreLifetime {
1296 if let Some((region, _)) = highlight.highlight_bound_region {
1306 ty::ReVar(_) if identify_regions => true,
1310 ty::ReErased => false,
1314 ty::ReClosureBound(_) => true,
1319 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1320 impl<F: fmt::Write> FmtPrinter<'_, '_, '_, F> {
1321 pub fn pretty_print_region(
1323 region: ty::Region<'_>,
1324 ) -> Result<Self, fmt::Error> {
1325 define_scoped_cx!(self);
1327 // Watch out for region highlights.
1328 let highlight = self.region_highlight_mode;
1329 if let Some(n) = highlight.region_highlighted(region) {
1330 p!(write("'{}", n));
1334 if self.tcx.sess.verbose() {
1335 p!(write("{:?}", region));
1339 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1341 // These printouts are concise. They do not contain all the information
1342 // the user might want to diagnose an error, but there is basically no way
1343 // to fit that into a short string. Hence the recommendation to use
1344 // `explain_region()` or `note_and_explain_region()`.
1346 ty::ReEarlyBound(ref data) => {
1347 if data.name.as_symbol() != kw::Invalid {
1348 p!(write("{}", data.name));
1352 ty::ReLateBound(_, br) |
1353 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1354 ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1355 if let ty::BrNamed(_, name) = br {
1356 if name.as_symbol() != kw::Invalid &&
1357 name.as_symbol() != kw::UnderscoreLifetime {
1358 p!(write("{}", name));
1363 if let Some((region, counter)) = highlight.highlight_bound_region {
1365 p!(write("'{}", counter));
1370 ty::ReScope(scope) if identify_regions => {
1372 region::ScopeData::Node =>
1373 p!(write("'{}s", scope.item_local_id().as_usize())),
1374 region::ScopeData::CallSite =>
1375 p!(write("'{}cs", scope.item_local_id().as_usize())),
1376 region::ScopeData::Arguments =>
1377 p!(write("'{}as", scope.item_local_id().as_usize())),
1378 region::ScopeData::Destruction =>
1379 p!(write("'{}ds", scope.item_local_id().as_usize())),
1380 region::ScopeData::Remainder(first_statement_index) => p!(write(
1382 scope.item_local_id().as_usize(),
1383 first_statement_index.index()
1388 ty::ReVar(region_vid) if identify_regions => {
1389 p!(write("{:?}", region_vid));
1396 p!(write("'static"));
1400 p!(write("'<empty>"));
1404 // The user should never encounter these in unsubstituted form.
1405 ty::ReClosureBound(vid) => {
1406 p!(write("{:?}", vid));
1417 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1418 // `region_index` and `used_region_names`.
1419 impl<F: fmt::Write> FmtPrinter<'_, 'gcx, 'tcx, F> {
1420 pub fn pretty_in_binder<T>(
1422 value: &ty::Binder<T>,
1423 ) -> Result<Self, fmt::Error>
1424 where T: Print<'gcx, 'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>
1426 fn name_by_region_index(index: usize) -> InternedString {
1428 0 => InternedString::intern("'r"),
1429 1 => InternedString::intern("'s"),
1430 i => InternedString::intern(&format!("'t{}", i-2)),
1434 // Replace any anonymous late-bound regions with named
1435 // variants, using gensym'd identifiers, so that we can
1436 // clearly differentiate between named and unnamed regions in
1437 // the output. We'll probably want to tweak this over time to
1438 // decide just how much information to give.
1439 if self.binder_depth == 0 {
1440 self.prepare_late_bound_region_info(value);
1443 let mut empty = true;
1444 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1445 write!(cx, "{}", if empty {
1453 define_scoped_cx!(self);
1455 let old_region_index = self.region_index;
1456 let mut region_index = old_region_index;
1457 let new_value = self.tcx.replace_late_bound_regions(value, |br| {
1458 let _ = start_or_continue(&mut self, "for<", ", ");
1460 ty::BrNamed(_, name) => {
1461 let _ = write!(self, "{}", name);
1467 let name = name_by_region_index(region_index);
1469 if !self.used_region_names.contains(&name) {
1473 let _ = write!(self, "{}", name);
1474 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1477 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
1479 start_or_continue(&mut self, "", "> ")?;
1481 self.binder_depth += 1;
1482 self.region_index = region_index;
1483 let mut inner = new_value.print(self)?;
1484 inner.region_index = old_region_index;
1485 inner.binder_depth -= 1;
1489 fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
1490 where T: TypeFoldable<'tcx>
1493 struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet<InternedString>);
1494 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> {
1495 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
1497 ty::ReLateBound(_, ty::BrNamed(_, name)) => {
1498 self.0.insert(name);
1502 r.super_visit_with(self)
1506 self.used_region_names.clear();
1507 let mut collector = LateBoundRegionNameCollector(&mut self.used_region_names);
1508 value.visit_with(&mut collector);
1509 self.region_index = 0;
1513 impl<'gcx: 'tcx, 'tcx, T, P: PrettyPrinter<'gcx, 'tcx>> Print<'gcx, 'tcx, P>
1515 where T: Print<'gcx, 'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>
1518 type Error = P::Error;
1519 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
1524 impl<'gcx: 'tcx, 'tcx, T, U, P: PrettyPrinter<'gcx, 'tcx>> Print<'gcx, 'tcx, P>
1525 for ty::OutlivesPredicate<T, U>
1526 where T: Print<'gcx, 'tcx, P, Output = P, Error = P::Error>,
1527 U: Print<'gcx, 'tcx, P, Output = P, Error = P::Error>,
1530 type Error = P::Error;
1531 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
1532 define_scoped_cx!(cx);
1533 p!(print(self.0), write(" : "), print(self.1));
1538 macro_rules! forward_display_to_print {
1540 $(impl fmt::Display for $ty {
1541 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1542 ty::tls::with(|tcx| {
1544 .expect("could not lift for printing")
1545 .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1553 macro_rules! define_print_and_forward_display {
1554 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
1555 $(impl<'gcx: 'tcx, 'tcx, P: PrettyPrinter<'gcx, 'tcx>> Print<'gcx, 'tcx, P> for $ty {
1557 type Error = fmt::Error;
1558 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
1559 #[allow(unused_mut)]
1561 define_scoped_cx!($cx);
1563 #[allow(unreachable_code)]
1568 forward_display_to_print!($($ty),+);
1572 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
1573 impl fmt::Display for ty::RegionKind {
1574 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1575 ty::tls::with(|tcx| {
1576 self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1582 forward_display_to_print! {
1584 &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1585 &'tcx ty::Const<'tcx>,
1587 // HACK(eddyb) these are exhaustive instead of generic,
1588 // because `for<'gcx: 'tcx, 'tcx>` isn't possible yet.
1589 ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
1590 ty::Binder<ty::TraitRef<'tcx>>,
1591 ty::Binder<ty::FnSig<'tcx>>,
1592 ty::Binder<ty::TraitPredicate<'tcx>>,
1593 ty::Binder<ty::SubtypePredicate<'tcx>>,
1594 ty::Binder<ty::ProjectionPredicate<'tcx>>,
1595 ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1596 ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
1598 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1599 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1602 define_print_and_forward_display! {
1605 &'tcx ty::List<Ty<'tcx>> {
1607 let mut tys = self.iter();
1608 if let Some(&ty) = tys.next() {
1611 p!(write(", "), print(ty));
1617 ty::TypeAndMut<'tcx> {
1618 p!(write("{}", if self.mutbl == hir::MutMutable { "mut " } else { "" }),
1622 ty::ExistentialTraitRef<'tcx> {
1623 // Use a type that can't appear in defaults of type parameters.
1624 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1625 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
1626 p!(print(trait_ref))
1629 ty::ExistentialProjection<'tcx> {
1630 let name = cx.tcx().associated_item(self.item_def_id).ident;
1631 p!(write("{} = ", name), print(self.ty))
1634 ty::ExistentialPredicate<'tcx> {
1636 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
1637 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
1638 ty::ExistentialPredicate::AutoTrait(def_id) => {
1639 p!(print_def_path(def_id, &[]));
1645 if self.unsafety == hir::Unsafety::Unsafe {
1646 p!(write("unsafe "));
1649 if self.abi != Abi::Rust {
1650 p!(write("extern {} ", self.abi));
1653 p!(write("fn"), pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
1657 if cx.tcx().sess.verbose() {
1658 p!(write("{:?}", self));
1662 ty::TyVar(_) => p!(write("_")),
1663 ty::IntVar(_) => p!(write("{}", "{integer}")),
1664 ty::FloatVar(_) => p!(write("{}", "{float}")),
1665 ty::FreshTy(v) => p!(write("FreshTy({})", v)),
1666 ty::FreshIntTy(v) => p!(write("FreshIntTy({})", v)),
1667 ty::FreshFloatTy(v) => p!(write("FreshFloatTy({})", v))
1671 ty::TraitRef<'tcx> {
1672 p!(print_def_path(self.def_id, self.substs));
1676 p!(write("{}", self.name))
1680 p!(write("{}", self.name))
1683 ty::SubtypePredicate<'tcx> {
1684 p!(print(self.a), write(" <: "), print(self.b))
1687 ty::TraitPredicate<'tcx> {
1688 p!(print(self.trait_ref.self_ty()), write(": "), print(self.trait_ref))
1691 ty::ProjectionPredicate<'tcx> {
1692 p!(print(self.projection_ty), write(" == "), print(self.ty))
1695 ty::ProjectionTy<'tcx> {
1696 p!(print_def_path(self.item_def_id, self.substs));
1701 ty::ClosureKind::Fn => p!(write("Fn")),
1702 ty::ClosureKind::FnMut => p!(write("FnMut")),
1703 ty::ClosureKind::FnOnce => p!(write("FnOnce")),
1707 ty::Predicate<'tcx> {
1709 ty::Predicate::Trait(ref data) => p!(print(data)),
1710 ty::Predicate::Subtype(ref predicate) => p!(print(predicate)),
1711 ty::Predicate::RegionOutlives(ref predicate) => p!(print(predicate)),
1712 ty::Predicate::TypeOutlives(ref predicate) => p!(print(predicate)),
1713 ty::Predicate::Projection(ref predicate) => p!(print(predicate)),
1714 ty::Predicate::WellFormed(ty) => p!(print(ty), write(" well-formed")),
1715 ty::Predicate::ObjectSafe(trait_def_id) => {
1716 p!(write("the trait `"),
1717 print_def_path(trait_def_id, &[]),
1718 write("` is object-safe"))
1720 ty::Predicate::ClosureKind(closure_def_id, _closure_substs, kind) => {
1721 p!(write("the closure `"),
1722 print_value_path(closure_def_id, &[]),
1723 write("` implements the trait `{}`", kind))
1725 ty::Predicate::ConstEvaluatable(def_id, substs) => {
1726 p!(write("the constant `"),
1727 print_value_path(def_id, substs),
1728 write("` can be evaluated"))
1734 match self.unpack() {
1735 UnpackedKind::Lifetime(lt) => p!(print(lt)),
1736 UnpackedKind::Type(ty) => p!(print(ty)),
1737 UnpackedKind::Const(ct) => p!(print(ct)),