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) => p!(write("{}", infer_ty)),
487 ty::Error => p!(write("[type error]")),
488 ty::Param(ref param_ty) => p!(write("{}", param_ty)),
489 ty::Bound(debruijn, bound_ty) => {
490 match bound_ty.kind {
491 ty::BoundTyKind::Anon => {
492 if debruijn == ty::INNERMOST {
493 p!(write("^{}", bound_ty.var.index()))
495 p!(write("^{}_{}", debruijn.index(), bound_ty.var.index()))
499 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
502 ty::Adt(def, substs) => {
503 p!(print_def_path(def.did, substs));
505 ty::Dynamic(data, r) => {
506 let print_r = self.region_should_not_be_omitted(r);
510 p!(write("dyn "), print(data));
512 p!(write(" + "), print(r), write(")"));
515 ty::Foreign(def_id) => {
516 p!(print_def_path(def_id, &[]));
518 ty::Projection(ref data) => p!(print(data)),
519 ty::UnnormalizedProjection(ref data) => {
520 p!(write("Unnormalized("), print(data), write(")"))
522 ty::Placeholder(placeholder) => {
523 p!(write("Placeholder({:?})", placeholder))
525 ty::Opaque(def_id, substs) => {
526 // FIXME(eddyb) print this with `print_def_path`.
527 if self.tcx().sess.verbose() {
528 p!(write("Opaque({:?}, {:?})", def_id, substs));
532 let def_key = self.tcx().def_key(def_id);
533 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
534 p!(write("{}", name));
535 let mut substs = substs.iter();
536 // FIXME(eddyb) print this with `print_def_path`.
537 if let Some(first) = substs.next() {
540 for subst in substs {
541 p!(write(", "), print(subst));
547 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
548 // by looking up the projections associated with the def_id.
549 let bounds = self.tcx().predicates_of(def_id).instantiate(self.tcx(), substs);
551 let mut first = true;
552 let mut is_sized = false;
554 for predicate in bounds.predicates {
555 if let Some(trait_ref) = predicate.to_opt_poly_trait_ref() {
556 // Don't print +Sized, but rather +?Sized if absent.
557 if Some(trait_ref.def_id()) == self.tcx().lang_items().sized_trait() {
563 write("{}", if first { " " } else { "+" }),
569 p!(write("{}?Sized", if first { " " } else { "+" }));
574 ty::Str => p!(write("str")),
575 ty::Generator(did, substs, movability) => {
576 let upvar_tys = substs.upvar_tys(did, self.tcx());
577 let witness = substs.witness(did, self.tcx());
578 if movability == hir::GeneratorMovability::Movable {
579 p!(write("[generator"));
581 p!(write("[static generator"));
584 // FIXME(eddyb) should use `def_span`.
585 if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
586 p!(write("@{:?}", self.tcx().hir().span_by_hir_id(hir_id)));
588 for (upvar, upvar_ty) in self.tcx().upvars(did)
590 .map_or(&[][..], |v| &v[..])
597 self.tcx().hir().name_by_hir_id(upvar.var_id)),
602 // cross-crate closure types should only be
603 // visible in codegen bug reports, I imagine.
604 p!(write("@{:?}", did));
606 for (index, upvar_ty) in upvar_tys.enumerate() {
608 write("{}{}:", sep, index),
614 p!(write(" "), print(witness), write("]"))
616 ty::GeneratorWitness(types) => {
617 p!(in_binder(&types));
619 ty::Closure(did, substs) => {
620 let upvar_tys = substs.upvar_tys(did, self.tcx());
621 p!(write("[closure"));
623 // FIXME(eddyb) should use `def_span`.
624 if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
625 if self.tcx().sess.opts.debugging_opts.span_free_formats {
626 p!(write("@{:?}", hir_id));
628 p!(write("@{:?}", self.tcx().hir().span_by_hir_id(hir_id)));
631 for (upvar, upvar_ty) in self.tcx().upvars(did)
633 .map_or(&[][..], |v| &v[..])
640 self.tcx().hir().name_by_hir_id(upvar.var_id)),
645 // cross-crate closure types should only be
646 // visible in codegen bug reports, I imagine.
647 p!(write("@{:?}", did));
649 for (index, upvar_ty) in upvar_tys.enumerate() {
651 write("{}{}:", sep, index),
657 if self.tcx().sess.verbose() {
659 " closure_kind_ty={:?} closure_sig_ty={:?}",
660 substs.closure_kind_ty(did, self.tcx()),
661 substs.closure_sig_ty(did, self.tcx())
667 ty::Array(ty, sz) => {
668 p!(write("["), print(ty), write("; "));
669 if let Some(n) = sz.assert_usize(self.tcx()) {
677 p!(write("["), print(ty), write("]"))
684 fn pretty_print_dyn_existential(
686 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
687 ) -> Result<Self::DynExistential, Self::Error> {
688 define_scoped_cx!(self);
690 // Generate the main trait ref, including associated types.
691 let mut first = true;
693 if let Some(principal) = predicates.principal() {
694 p!(print_def_path(principal.def_id, &[]));
696 let mut resugared = false;
698 // Special-case `Fn(...) -> ...` and resugar it.
699 let fn_trait_kind = self.tcx().lang_items().fn_trait_kind(principal.def_id);
700 if !self.tcx().sess.verbose() && fn_trait_kind.is_some() {
701 if let ty::Tuple(ref args) = principal.substs.type_at(0).sty {
702 let mut projections = predicates.projection_bounds();
703 if let (Some(proj), None) = (projections.next(), projections.next()) {
704 let tys: Vec<_> = args.iter().map(|k| k.expect_ty()).collect();
705 p!(pretty_fn_sig(&tys, false, proj.ty));
711 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
712 // in order to place the projections inside the `<...>`.
714 // Use a type that can't appear in defaults of type parameters.
715 let dummy_self = self.tcx().mk_ty_infer(ty::FreshTy(0));
716 let principal = principal.with_self_ty(self.tcx(), dummy_self);
718 let args = self.generic_args_to_print(
719 self.tcx().generics_of(principal.def_id),
723 // Don't print `'_` if there's no unerased regions.
724 let print_regions = args.iter().any(|arg| {
726 UnpackedKind::Lifetime(r) => *r != ty::ReErased,
730 let mut args = args.iter().cloned().filter(|arg| {
732 UnpackedKind::Lifetime(_) => print_regions,
736 let mut projections = predicates.projection_bounds();
738 let arg0 = args.next();
739 let projection0 = projections.next();
740 if arg0.is_some() || projection0.is_some() {
741 let args = arg0.into_iter().chain(args);
742 let projections = projection0.into_iter().chain(projections);
744 p!(generic_delimiters(|mut cx| {
745 cx = cx.comma_sep(args)?;
746 if arg0.is_some() && projection0.is_some() {
749 cx.comma_sep(projections)
757 // FIXME(eddyb) avoid printing twice (needed to ensure
758 // that the auto traits are sorted *and* printed via cx).
759 let mut auto_traits: Vec<_> = predicates.auto_traits().map(|did| {
760 (self.tcx().def_path_str(did), did)
763 // The auto traits come ordered by `DefPathHash`. While
764 // `DefPathHash` is *stable* in the sense that it depends on
765 // neither the host nor the phase of the moon, it depends
766 // "pseudorandomly" on the compiler version and the target.
768 // To avoid that causing instabilities in compiletest
769 // output, sort the auto-traits alphabetically.
772 for (_, def_id) in auto_traits {
778 p!(print_def_path(def_id, &[]));
789 ) -> Result<Self, Self::Error> {
790 define_scoped_cx!(self);
793 let mut inputs = inputs.iter();
794 if let Some(&ty) = inputs.next() {
797 p!(write(", "), print(ty));
804 if !output.is_unit() {
805 p!(write(" -> "), print(output));
811 fn pretty_print_const(
813 ct: &'tcx ty::Const<'tcx>,
814 ) -> Result<Self::Const, Self::Error> {
815 define_scoped_cx!(self);
817 let u8 = self.tcx().types.u8;
818 if let ty::FnDef(did, substs) = ct.ty.sty {
819 p!(print_value_path(did, substs));
822 if let ConstValue::Unevaluated(did, substs) = ct.val {
823 match self.tcx().def_kind(did) {
824 | Some(DefKind::Static)
825 | Some(DefKind::Const)
826 | Some(DefKind::AssocConst) => p!(print_value_path(did, substs)),
827 _ => if did.is_local() {
828 let span = self.tcx().def_span(did);
829 if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span) {
830 p!(write("{}", snip))
832 p!(write("_: "), print(ct.ty))
835 p!(write("_: "), print(ct.ty))
840 if let ConstValue::Infer(..) = ct.val {
841 p!(write("_: "), print(ct.ty));
844 if let ConstValue::Param(ParamConst { name, .. }) = ct.val {
845 p!(write("{}", name));
848 if let ConstValue::Scalar(Scalar::Raw { data, .. }) = ct.val {
851 p!(write("{}", if data == 0 { "false" } else { "true" }));
854 ty::Float(ast::FloatTy::F32) => {
855 p!(write("{}f32", Single::from_bits(data)));
858 ty::Float(ast::FloatTy::F64) => {
859 p!(write("{}f64", Double::from_bits(data)));
863 p!(write("{}{}", data, ui));
867 let ty = self.tcx().lift_to_global(&ct.ty).unwrap();
868 let size = self.tcx().layout_of(ty::ParamEnv::empty().and(ty))
871 p!(write("{}{}", sign_extend(data, size) as i128, i));
875 p!(write("{:?}", ::std::char::from_u32(data as u32).unwrap()));
881 if let ty::Ref(_, ref_ty, _) = ct.ty.sty {
882 let byte_str = match (ct.val, &ref_ty.sty) {
883 (ConstValue::Scalar(Scalar::Ptr(ptr)), ty::Array(t, n)) if *t == u8 => {
884 let n = n.unwrap_usize(self.tcx());
887 .unwrap_memory(ptr.alloc_id)
888 .get_bytes(&self.tcx(), ptr, Size::from_bytes(n)).unwrap())
890 (ConstValue::Slice { data, start, end }, ty::Slice(t)) if *t == u8 => {
891 Some(&data.bytes[start..end])
893 (ConstValue::Slice { data, start, end }, ty::Str) => {
894 let slice = &data.bytes[start..end];
895 let s = ::std::str::from_utf8(slice)
896 .expect("non utf8 str from miri");
897 p!(write("{:?}", s));
902 if let Some(byte_str) = byte_str {
905 for e in std::ascii::escape_default(c) {
906 self.write_char(e as char)?;
913 p!(write("{:?} : ", ct.val), print(ct.ty));
919 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
920 pub struct FmtPrinter<'a, 'gcx, 'tcx, F>(Box<FmtPrinterData<'a, 'gcx, 'tcx, F>>);
922 pub struct FmtPrinterData<'a, 'gcx, 'tcx, F> {
923 tcx: TyCtxt<'a, 'gcx, 'tcx>,
929 used_region_names: FxHashSet<InternedString>,
933 pub region_highlight_mode: RegionHighlightMode,
936 impl<F> Deref for FmtPrinter<'a, 'gcx, 'tcx, F> {
937 type Target = FmtPrinterData<'a, 'gcx, 'tcx, F>;
938 fn deref(&self) -> &Self::Target {
943 impl<F> DerefMut for FmtPrinter<'_, '_, '_, F> {
944 fn deref_mut(&mut self) -> &mut Self::Target {
949 impl<F> FmtPrinter<'a, 'gcx, 'tcx, F> {
950 pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>, fmt: F, ns: Namespace) -> Self {
951 FmtPrinter(Box::new(FmtPrinterData {
955 in_value: ns == Namespace::ValueNS,
956 used_region_names: Default::default(),
959 region_highlight_mode: RegionHighlightMode::default(),
964 impl TyCtxt<'_, '_, '_> {
965 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
966 // (but also some things just print a `DefId` generally so maybe we need this?)
967 fn guess_def_namespace(self, def_id: DefId) -> Namespace {
968 match self.def_key(def_id).disambiguated_data.data {
969 DefPathData::TypeNs(..)
970 | DefPathData::CrateRoot
971 | DefPathData::ImplTrait => Namespace::TypeNS,
973 DefPathData::ValueNs(..)
974 | DefPathData::AnonConst
975 | DefPathData::ClosureExpr
976 | DefPathData::Ctor => Namespace::ValueNS,
978 DefPathData::MacroNs(..) => Namespace::MacroNS,
980 _ => Namespace::TypeNS,
984 /// Returns a string identifying this `DefId`. This string is
985 /// suitable for user output.
986 pub fn def_path_str(self, def_id: DefId) -> String {
987 let ns = self.guess_def_namespace(def_id);
988 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
989 let mut s = String::new();
990 let _ = FmtPrinter::new(self, &mut s, ns)
991 .print_def_path(def_id, &[]);
996 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, '_, F> {
997 fn write_str(&mut self, s: &str) -> fmt::Result {
998 self.fmt.write_str(s)
1002 impl<F: fmt::Write> Printer<'gcx, 'tcx> for FmtPrinter<'_, 'gcx, 'tcx, F> {
1003 type Error = fmt::Error;
1008 type DynExistential = Self;
1011 fn tcx(&'a self) -> TyCtxt<'a, 'gcx, 'tcx> {
1018 substs: &'tcx [Kind<'tcx>],
1019 ) -> Result<Self::Path, Self::Error> {
1020 define_scoped_cx!(self);
1022 if substs.is_empty() {
1023 match self.try_print_visible_def_path(def_id)? {
1024 (cx, true) => return Ok(cx),
1025 (cx, false) => self = cx,
1029 let key = self.tcx.def_key(def_id);
1030 if let DefPathData::Impl = key.disambiguated_data.data {
1031 // Always use types for non-local impls, where types are always
1032 // available, and filename/line-number is mostly uninteresting.
1034 !def_id.is_local() || {
1035 // Otherwise, use filename/line-number if forced.
1036 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1041 // If no type info is available, fall back to
1042 // pretty printing some span information. This should
1043 // only occur very early in the compiler pipeline.
1044 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1045 let span = self.tcx.def_span(def_id);
1047 self = self.print_def_path(parent_def_id, &[])?;
1049 // HACK(eddyb) copy of `path_append` to avoid
1050 // constructing a `DisambiguatedDefPathData`.
1051 if !self.empty_path {
1052 write!(self, "::")?;
1054 write!(self, "<impl at {:?}>", span)?;
1055 self.empty_path = false;
1061 self.default_print_def_path(def_id, substs)
1066 region: ty::Region<'_>,
1067 ) -> Result<Self::Region, Self::Error> {
1068 self.pretty_print_region(region)
1074 ) -> Result<Self::Type, Self::Error> {
1075 self.pretty_print_type(ty)
1078 fn print_dyn_existential(
1080 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1081 ) -> Result<Self::DynExistential, Self::Error> {
1082 self.pretty_print_dyn_existential(predicates)
1087 ct: &'tcx ty::Const<'tcx>,
1088 ) -> Result<Self::Const, Self::Error> {
1089 self.pretty_print_const(ct)
1095 ) -> Result<Self::Path, Self::Error> {
1096 self.empty_path = true;
1097 if cnum == LOCAL_CRATE {
1098 if self.tcx.sess.rust_2018() {
1099 // We add the `crate::` keyword on Rust 2018, only when desired.
1100 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1101 write!(self, "{}", kw::Crate)?;
1102 self.empty_path = false;
1106 write!(self, "{}", self.tcx.crate_name(cnum))?;
1107 self.empty_path = false;
1114 trait_ref: Option<ty::TraitRef<'tcx>>,
1115 ) -> Result<Self::Path, Self::Error> {
1116 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1117 self.empty_path = false;
1121 fn path_append_impl(
1123 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1124 _disambiguated_data: &DisambiguatedDefPathData,
1126 trait_ref: Option<ty::TraitRef<'tcx>>,
1127 ) -> Result<Self::Path, Self::Error> {
1128 self = self.pretty_path_append_impl(|mut cx| {
1129 cx = print_prefix(cx)?;
1135 }, self_ty, trait_ref)?;
1136 self.empty_path = false;
1141 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1142 disambiguated_data: &DisambiguatedDefPathData,
1143 ) -> Result<Self::Path, Self::Error> {
1144 self = print_prefix(self)?;
1146 // Skip `::{{constructor}}` on tuple/unit structs.
1147 match disambiguated_data.data {
1148 DefPathData::Ctor => return Ok(self),
1152 // FIXME(eddyb) `name` should never be empty, but it
1153 // currently is for `extern { ... }` "foreign modules".
1154 let name = disambiguated_data.data.as_interned_str().as_str();
1155 if !name.is_empty() {
1156 if !self.empty_path {
1157 write!(self, "::")?;
1159 write!(self, "{}", name)?;
1161 // FIXME(eddyb) this will print e.g. `{{closure}}#3`, but it
1162 // might be nicer to use something else, e.g. `{closure#3}`.
1163 let dis = disambiguated_data.disambiguator;
1165 disambiguated_data.data.get_opt_name().is_none() ||
1166 dis != 0 && self.tcx.sess.verbose();
1168 write!(self, "#{}", dis)?;
1171 self.empty_path = false;
1176 fn path_generic_args(
1178 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1179 args: &[Kind<'tcx>],
1180 ) -> Result<Self::Path, Self::Error> {
1181 self = print_prefix(self)?;
1183 // Don't print `'_` if there's no unerased regions.
1184 let print_regions = args.iter().any(|arg| {
1185 match arg.unpack() {
1186 UnpackedKind::Lifetime(r) => *r != ty::ReErased,
1190 let args = args.iter().cloned().filter(|arg| {
1191 match arg.unpack() {
1192 UnpackedKind::Lifetime(_) => print_regions,
1197 if args.clone().next().is_some() {
1199 write!(self, "::")?;
1201 self.generic_delimiters(|cx| cx.comma_sep(args))
1208 impl<F: fmt::Write> PrettyPrinter<'gcx, 'tcx> for FmtPrinter<'_, 'gcx, 'tcx, F> {
1209 fn print_value_path(
1212 substs: &'tcx [Kind<'tcx>],
1213 ) -> Result<Self::Path, Self::Error> {
1214 let was_in_value = std::mem::replace(&mut self.in_value, true);
1215 self = self.print_def_path(def_id, substs)?;
1216 self.in_value = was_in_value;
1223 value: &ty::Binder<T>,
1224 ) -> Result<Self, Self::Error>
1225 where T: Print<'gcx, 'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>
1227 self.pretty_in_binder(value)
1230 fn generic_delimiters(
1232 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1233 ) -> Result<Self, Self::Error> {
1236 let was_in_value = std::mem::replace(&mut self.in_value, false);
1237 let mut inner = f(self)?;
1238 inner.in_value = was_in_value;
1240 write!(inner, ">")?;
1244 fn region_should_not_be_omitted(
1246 region: ty::Region<'_>,
1248 let highlight = self.region_highlight_mode;
1249 if highlight.region_highlighted(region).is_some() {
1253 if self.tcx.sess.verbose() {
1257 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1260 ty::ReEarlyBound(ref data) => {
1261 data.name.as_symbol() != kw::Invalid &&
1262 data.name.as_symbol() != kw::UnderscoreLifetime
1265 ty::ReLateBound(_, br) |
1266 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1267 ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1268 if let ty::BrNamed(_, name) = br {
1269 if name.as_symbol() != kw::Invalid &&
1270 name.as_symbol() != kw::UnderscoreLifetime {
1275 if let Some((region, _)) = highlight.highlight_bound_region {
1285 ty::ReVar(_) if identify_regions => true,
1289 ty::ReErased => false,
1293 ty::ReClosureBound(_) => true,
1298 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1299 impl<F: fmt::Write> FmtPrinter<'_, '_, '_, F> {
1300 pub fn pretty_print_region(
1302 region: ty::Region<'_>,
1303 ) -> Result<Self, fmt::Error> {
1304 define_scoped_cx!(self);
1306 // Watch out for region highlights.
1307 let highlight = self.region_highlight_mode;
1308 if let Some(n) = highlight.region_highlighted(region) {
1309 p!(write("'{}", n));
1313 if self.tcx.sess.verbose() {
1314 p!(write("{:?}", region));
1318 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1320 // These printouts are concise. They do not contain all the information
1321 // the user might want to diagnose an error, but there is basically no way
1322 // to fit that into a short string. Hence the recommendation to use
1323 // `explain_region()` or `note_and_explain_region()`.
1325 ty::ReEarlyBound(ref data) => {
1326 if data.name.as_symbol() != kw::Invalid {
1327 p!(write("{}", data.name));
1331 ty::ReLateBound(_, br) |
1332 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1333 ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1334 if let ty::BrNamed(_, name) = br {
1335 if name.as_symbol() != kw::Invalid &&
1336 name.as_symbol() != kw::UnderscoreLifetime {
1337 p!(write("{}", name));
1342 if let Some((region, counter)) = highlight.highlight_bound_region {
1344 p!(write("'{}", counter));
1349 ty::ReScope(scope) if identify_regions => {
1351 region::ScopeData::Node =>
1352 p!(write("'{}s", scope.item_local_id().as_usize())),
1353 region::ScopeData::CallSite =>
1354 p!(write("'{}cs", scope.item_local_id().as_usize())),
1355 region::ScopeData::Arguments =>
1356 p!(write("'{}as", scope.item_local_id().as_usize())),
1357 region::ScopeData::Destruction =>
1358 p!(write("'{}ds", scope.item_local_id().as_usize())),
1359 region::ScopeData::Remainder(first_statement_index) => p!(write(
1361 scope.item_local_id().as_usize(),
1362 first_statement_index.index()
1367 ty::ReVar(region_vid) if identify_regions => {
1368 p!(write("{:?}", region_vid));
1375 p!(write("'static"));
1379 p!(write("'<empty>"));
1383 // The user should never encounter these in unsubstituted form.
1384 ty::ReClosureBound(vid) => {
1385 p!(write("{:?}", vid));
1396 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1397 // `region_index` and `used_region_names`.
1398 impl<F: fmt::Write> FmtPrinter<'_, 'gcx, 'tcx, F> {
1399 pub fn pretty_in_binder<T>(
1401 value: &ty::Binder<T>,
1402 ) -> Result<Self, fmt::Error>
1403 where T: Print<'gcx, 'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>
1405 fn name_by_region_index(index: usize) -> InternedString {
1407 0 => InternedString::intern("'r"),
1408 1 => InternedString::intern("'s"),
1409 i => InternedString::intern(&format!("'t{}", i-2)),
1413 // Replace any anonymous late-bound regions with named
1414 // variants, using gensym'd identifiers, so that we can
1415 // clearly differentiate between named and unnamed regions in
1416 // the output. We'll probably want to tweak this over time to
1417 // decide just how much information to give.
1418 if self.binder_depth == 0 {
1419 self.prepare_late_bound_region_info(value);
1422 let mut empty = true;
1423 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1424 write!(cx, "{}", if empty {
1432 define_scoped_cx!(self);
1434 let old_region_index = self.region_index;
1435 let mut region_index = old_region_index;
1436 let new_value = self.tcx.replace_late_bound_regions(value, |br| {
1437 let _ = start_or_continue(&mut self, "for<", ", ");
1439 ty::BrNamed(_, name) => {
1440 let _ = write!(self, "{}", name);
1446 let name = name_by_region_index(region_index);
1448 if !self.used_region_names.contains(&name) {
1452 let _ = write!(self, "{}", name);
1453 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1456 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
1458 start_or_continue(&mut self, "", "> ")?;
1460 self.binder_depth += 1;
1461 self.region_index = region_index;
1462 let mut inner = new_value.print(self)?;
1463 inner.region_index = old_region_index;
1464 inner.binder_depth -= 1;
1468 fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
1469 where T: TypeFoldable<'tcx>
1472 struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet<InternedString>);
1473 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> {
1474 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
1476 ty::ReLateBound(_, ty::BrNamed(_, name)) => {
1477 self.0.insert(name);
1481 r.super_visit_with(self)
1485 self.used_region_names.clear();
1486 let mut collector = LateBoundRegionNameCollector(&mut self.used_region_names);
1487 value.visit_with(&mut collector);
1488 self.region_index = 0;
1492 impl<'gcx: 'tcx, 'tcx, T, P: PrettyPrinter<'gcx, 'tcx>> Print<'gcx, 'tcx, P>
1494 where T: Print<'gcx, 'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>
1497 type Error = P::Error;
1498 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
1503 impl<'gcx: 'tcx, 'tcx, T, U, P: PrettyPrinter<'gcx, 'tcx>> Print<'gcx, 'tcx, P>
1504 for ty::OutlivesPredicate<T, U>
1505 where T: Print<'gcx, 'tcx, P, Output = P, Error = P::Error>,
1506 U: Print<'gcx, 'tcx, P, Output = P, Error = P::Error>,
1509 type Error = P::Error;
1510 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
1511 define_scoped_cx!(cx);
1512 p!(print(self.0), write(" : "), print(self.1));
1517 macro_rules! forward_display_to_print {
1519 $(impl fmt::Display for $ty {
1520 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1521 ty::tls::with(|tcx| {
1523 .expect("could not lift for printing")
1524 .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1532 macro_rules! define_print_and_forward_display {
1533 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
1534 $(impl<'gcx: 'tcx, 'tcx, P: PrettyPrinter<'gcx, 'tcx>> Print<'gcx, 'tcx, P> for $ty {
1536 type Error = fmt::Error;
1537 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
1538 #[allow(unused_mut)]
1540 define_scoped_cx!($cx);
1542 #[allow(unreachable_code)]
1547 forward_display_to_print!($($ty),+);
1551 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
1552 impl fmt::Display for ty::RegionKind {
1553 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1554 ty::tls::with(|tcx| {
1555 self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1561 forward_display_to_print! {
1563 &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1564 &'tcx ty::Const<'tcx>,
1566 // HACK(eddyb) these are exhaustive instead of generic,
1567 // because `for<'gcx: 'tcx, 'tcx>` isn't possible yet.
1568 ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
1569 ty::Binder<ty::TraitRef<'tcx>>,
1570 ty::Binder<ty::FnSig<'tcx>>,
1571 ty::Binder<ty::TraitPredicate<'tcx>>,
1572 ty::Binder<ty::SubtypePredicate<'tcx>>,
1573 ty::Binder<ty::ProjectionPredicate<'tcx>>,
1574 ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1575 ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
1577 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1578 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1581 define_print_and_forward_display! {
1584 &'tcx ty::List<Ty<'tcx>> {
1586 let mut tys = self.iter();
1587 if let Some(&ty) = tys.next() {
1590 p!(write(", "), print(ty));
1596 ty::TypeAndMut<'tcx> {
1597 p!(write("{}", if self.mutbl == hir::MutMutable { "mut " } else { "" }),
1601 ty::ExistentialTraitRef<'tcx> {
1602 // Use a type that can't appear in defaults of type parameters.
1603 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1604 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
1605 p!(print(trait_ref))
1608 ty::ExistentialProjection<'tcx> {
1609 let name = cx.tcx().associated_item(self.item_def_id).ident;
1610 p!(write("{} = ", name), print(self.ty))
1613 ty::ExistentialPredicate<'tcx> {
1615 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
1616 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
1617 ty::ExistentialPredicate::AutoTrait(def_id) => {
1618 p!(print_def_path(def_id, &[]));
1624 if self.unsafety == hir::Unsafety::Unsafe {
1625 p!(write("unsafe "));
1628 if self.abi != Abi::Rust {
1629 p!(write("extern {} ", self.abi));
1632 p!(write("fn"), pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
1636 if cx.tcx().sess.verbose() {
1637 p!(write("{:?}", self));
1641 ty::TyVar(_) => p!(write("_")),
1642 ty::IntVar(_) => p!(write("{}", "{integer}")),
1643 ty::FloatVar(_) => p!(write("{}", "{float}")),
1644 ty::FreshTy(v) => p!(write("FreshTy({})", v)),
1645 ty::FreshIntTy(v) => p!(write("FreshIntTy({})", v)),
1646 ty::FreshFloatTy(v) => p!(write("FreshFloatTy({})", v))
1650 ty::TraitRef<'tcx> {
1651 p!(print_def_path(self.def_id, self.substs));
1655 p!(write("{}", self.name))
1659 p!(write("{}", self.name))
1662 ty::SubtypePredicate<'tcx> {
1663 p!(print(self.a), write(" <: "), print(self.b))
1666 ty::TraitPredicate<'tcx> {
1667 p!(print(self.trait_ref.self_ty()), write(": "), print(self.trait_ref))
1670 ty::ProjectionPredicate<'tcx> {
1671 p!(print(self.projection_ty), write(" == "), print(self.ty))
1674 ty::ProjectionTy<'tcx> {
1675 p!(print_def_path(self.item_def_id, self.substs));
1680 ty::ClosureKind::Fn => p!(write("Fn")),
1681 ty::ClosureKind::FnMut => p!(write("FnMut")),
1682 ty::ClosureKind::FnOnce => p!(write("FnOnce")),
1686 ty::Predicate<'tcx> {
1688 ty::Predicate::Trait(ref data) => p!(print(data)),
1689 ty::Predicate::Subtype(ref predicate) => p!(print(predicate)),
1690 ty::Predicate::RegionOutlives(ref predicate) => p!(print(predicate)),
1691 ty::Predicate::TypeOutlives(ref predicate) => p!(print(predicate)),
1692 ty::Predicate::Projection(ref predicate) => p!(print(predicate)),
1693 ty::Predicate::WellFormed(ty) => p!(print(ty), write(" well-formed")),
1694 ty::Predicate::ObjectSafe(trait_def_id) => {
1695 p!(write("the trait `"),
1696 print_def_path(trait_def_id, &[]),
1697 write("` is object-safe"))
1699 ty::Predicate::ClosureKind(closure_def_id, _closure_substs, kind) => {
1700 p!(write("the closure `"),
1701 print_value_path(closure_def_id, &[]),
1702 write("` implements the trait `{}`", kind))
1704 ty::Predicate::ConstEvaluatable(def_id, substs) => {
1705 p!(write("the constant `"),
1706 print_value_path(def_id, substs),
1707 write("` can be evaluated"))
1713 match self.unpack() {
1714 UnpackedKind::Lifetime(lt) => p!(print(lt)),
1715 UnpackedKind::Type(ty) => p!(print(ty)),
1716 UnpackedKind::Const(ct) => p!(print(ct)),