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 Some(n) = sz.assert_usize(self.tcx()) {
707 p!(write("["), print(ty), write("]"))
714 fn infer_ty_name(&self, _: ty::TyVid) -> Option<String> {
718 fn pretty_print_dyn_existential(
720 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
721 ) -> Result<Self::DynExistential, Self::Error> {
722 define_scoped_cx!(self);
724 // Generate the main trait ref, including associated types.
725 let mut first = true;
727 if let Some(principal) = predicates.principal() {
728 p!(print_def_path(principal.def_id, &[]));
730 let mut resugared = false;
732 // Special-case `Fn(...) -> ...` and resugar it.
733 let fn_trait_kind = self.tcx().lang_items().fn_trait_kind(principal.def_id);
734 if !self.tcx().sess.verbose() && fn_trait_kind.is_some() {
735 if let ty::Tuple(ref args) = principal.substs.type_at(0).sty {
736 let mut projections = predicates.projection_bounds();
737 if let (Some(proj), None) = (projections.next(), projections.next()) {
738 let tys: Vec<_> = args.iter().map(|k| k.expect_ty()).collect();
739 p!(pretty_fn_sig(&tys, false, proj.ty));
745 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
746 // in order to place the projections inside the `<...>`.
748 // Use a type that can't appear in defaults of type parameters.
749 let dummy_self = self.tcx().mk_ty_infer(ty::FreshTy(0));
750 let principal = principal.with_self_ty(self.tcx(), dummy_self);
752 let args = self.generic_args_to_print(
753 self.tcx().generics_of(principal.def_id),
757 // Don't print `'_` if there's no unerased regions.
758 let print_regions = args.iter().any(|arg| {
760 UnpackedKind::Lifetime(r) => *r != ty::ReErased,
764 let mut args = args.iter().cloned().filter(|arg| {
766 UnpackedKind::Lifetime(_) => print_regions,
770 let mut projections = predicates.projection_bounds();
772 let arg0 = args.next();
773 let projection0 = projections.next();
774 if arg0.is_some() || projection0.is_some() {
775 let args = arg0.into_iter().chain(args);
776 let projections = projection0.into_iter().chain(projections);
778 p!(generic_delimiters(|mut cx| {
779 cx = cx.comma_sep(args)?;
780 if arg0.is_some() && projection0.is_some() {
783 cx.comma_sep(projections)
791 // FIXME(eddyb) avoid printing twice (needed to ensure
792 // that the auto traits are sorted *and* printed via cx).
793 let mut auto_traits: Vec<_> = predicates.auto_traits().map(|did| {
794 (self.tcx().def_path_str(did), did)
797 // The auto traits come ordered by `DefPathHash`. While
798 // `DefPathHash` is *stable* in the sense that it depends on
799 // neither the host nor the phase of the moon, it depends
800 // "pseudorandomly" on the compiler version and the target.
802 // To avoid that causing instabilities in compiletest
803 // output, sort the auto-traits alphabetically.
806 for (_, def_id) in auto_traits {
812 p!(print_def_path(def_id, &[]));
823 ) -> Result<Self, Self::Error> {
824 define_scoped_cx!(self);
827 let mut inputs = inputs.iter();
828 if let Some(&ty) = inputs.next() {
831 p!(write(", "), print(ty));
838 if !output.is_unit() {
839 p!(write(" -> "), print(output));
845 fn pretty_print_const(
847 ct: &'tcx ty::Const<'tcx>,
848 ) -> Result<Self::Const, Self::Error> {
849 define_scoped_cx!(self);
851 let u8 = self.tcx().types.u8;
852 if let ty::FnDef(did, substs) = ct.ty.sty {
853 p!(print_value_path(did, substs));
856 if let ConstValue::Unevaluated(did, substs) = ct.val {
857 match self.tcx().def_kind(did) {
858 | Some(DefKind::Static)
859 | Some(DefKind::Const)
860 | Some(DefKind::AssocConst) => p!(print_value_path(did, substs)),
861 _ => if did.is_local() {
862 let span = self.tcx().def_span(did);
863 if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span) {
864 p!(write("{}", snip))
866 p!(write("_: "), print(ct.ty))
869 p!(write("_: "), print(ct.ty))
874 if let ConstValue::Infer(..) = ct.val {
875 p!(write("_: "), print(ct.ty));
878 if let ConstValue::Param(ParamConst { name, .. }) = ct.val {
879 p!(write("{}", name));
882 if let ConstValue::Scalar(Scalar::Raw { data, .. }) = ct.val {
885 p!(write("{}", if data == 0 { "false" } else { "true" }));
888 ty::Float(ast::FloatTy::F32) => {
889 p!(write("{}f32", Single::from_bits(data)));
892 ty::Float(ast::FloatTy::F64) => {
893 p!(write("{}f64", Double::from_bits(data)));
897 p!(write("{}{}", data, ui));
901 let ty = self.tcx().lift_to_global(&ct.ty).unwrap();
902 let size = self.tcx().layout_of(ty::ParamEnv::empty().and(ty))
905 p!(write("{}{}", sign_extend(data, size) as i128, i));
909 p!(write("{:?}", ::std::char::from_u32(data as u32).unwrap()));
915 if let ty::Ref(_, ref_ty, _) = ct.ty.sty {
916 let byte_str = match (ct.val, &ref_ty.sty) {
917 (ConstValue::Scalar(Scalar::Ptr(ptr)), ty::Array(t, n)) if *t == u8 => {
918 let n = n.unwrap_usize(self.tcx());
921 .unwrap_memory(ptr.alloc_id)
922 .get_bytes(&self.tcx(), ptr, Size::from_bytes(n)).unwrap())
924 (ConstValue::Slice { data, start, end }, ty::Slice(t)) if *t == u8 => {
925 Some(&data.bytes[start..end])
927 (ConstValue::Slice { data, start, end }, ty::Str) => {
928 let slice = &data.bytes[start..end];
929 let s = ::std::str::from_utf8(slice)
930 .expect("non utf8 str from miri");
931 p!(write("{:?}", s));
936 if let Some(byte_str) = byte_str {
939 for e in std::ascii::escape_default(c) {
940 self.write_char(e as char)?;
947 p!(write("{:?} : ", ct.val), print(ct.ty));
953 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
954 pub struct FmtPrinter<'a, 'tcx, F>(Box<FmtPrinterData<'a, 'tcx, F>>);
956 pub struct FmtPrinterData<'a, 'tcx, F> {
963 used_region_names: FxHashSet<InternedString>,
967 pub region_highlight_mode: RegionHighlightMode,
969 pub name_resolver: Option<Box<&'a dyn Fn(ty::sty::TyVid) -> Option<String>>>,
972 impl<F> Deref for FmtPrinter<'a, 'tcx, F> {
973 type Target = FmtPrinterData<'a, 'tcx, F>;
974 fn deref(&self) -> &Self::Target {
979 impl<F> DerefMut for FmtPrinter<'_, '_, F> {
980 fn deref_mut(&mut self) -> &mut Self::Target {
985 impl<F> FmtPrinter<'a, 'tcx, F> {
986 pub fn new(tcx: TyCtxt<'tcx>, fmt: F, ns: Namespace) -> Self {
987 FmtPrinter(Box::new(FmtPrinterData {
991 in_value: ns == Namespace::ValueNS,
992 used_region_names: Default::default(),
995 region_highlight_mode: RegionHighlightMode::default(),
1002 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1003 // (but also some things just print a `DefId` generally so maybe we need this?)
1004 fn guess_def_namespace(self, def_id: DefId) -> Namespace {
1005 match self.def_key(def_id).disambiguated_data.data {
1006 DefPathData::TypeNs(..)
1007 | DefPathData::CrateRoot
1008 | DefPathData::ImplTrait => Namespace::TypeNS,
1010 DefPathData::ValueNs(..)
1011 | DefPathData::AnonConst
1012 | DefPathData::ClosureExpr
1013 | DefPathData::Ctor => Namespace::ValueNS,
1015 DefPathData::MacroNs(..) => Namespace::MacroNS,
1017 _ => Namespace::TypeNS,
1021 /// Returns a string identifying this `DefId`. This string is
1022 /// suitable for user output.
1023 pub fn def_path_str(self, def_id: DefId) -> String {
1024 let ns = self.guess_def_namespace(def_id);
1025 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1026 let mut s = String::new();
1027 let _ = FmtPrinter::new(self, &mut s, ns)
1028 .print_def_path(def_id, &[]);
1033 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, F> {
1034 fn write_str(&mut self, s: &str) -> fmt::Result {
1035 self.fmt.write_str(s)
1039 impl<F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
1040 type Error = fmt::Error;
1045 type DynExistential = Self;
1048 fn tcx(&'a self) -> TyCtxt<'tcx> {
1055 substs: &'tcx [Kind<'tcx>],
1056 ) -> Result<Self::Path, Self::Error> {
1057 define_scoped_cx!(self);
1059 if substs.is_empty() {
1060 match self.try_print_visible_def_path(def_id)? {
1061 (cx, true) => return Ok(cx),
1062 (cx, false) => self = cx,
1066 let key = self.tcx.def_key(def_id);
1067 if let DefPathData::Impl = key.disambiguated_data.data {
1068 // Always use types for non-local impls, where types are always
1069 // available, and filename/line-number is mostly uninteresting.
1071 !def_id.is_local() || {
1072 // Otherwise, use filename/line-number if forced.
1073 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1078 // If no type info is available, fall back to
1079 // pretty printing some span information. This should
1080 // only occur very early in the compiler pipeline.
1081 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1082 let span = self.tcx.def_span(def_id);
1084 self = self.print_def_path(parent_def_id, &[])?;
1086 // HACK(eddyb) copy of `path_append` to avoid
1087 // constructing a `DisambiguatedDefPathData`.
1088 if !self.empty_path {
1089 write!(self, "::")?;
1091 write!(self, "<impl at {:?}>", span)?;
1092 self.empty_path = false;
1098 self.default_print_def_path(def_id, substs)
1103 region: ty::Region<'_>,
1104 ) -> Result<Self::Region, Self::Error> {
1105 self.pretty_print_region(region)
1111 ) -> Result<Self::Type, Self::Error> {
1112 self.pretty_print_type(ty)
1115 fn print_dyn_existential(
1117 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1118 ) -> Result<Self::DynExistential, Self::Error> {
1119 self.pretty_print_dyn_existential(predicates)
1124 ct: &'tcx ty::Const<'tcx>,
1125 ) -> Result<Self::Const, Self::Error> {
1126 self.pretty_print_const(ct)
1132 ) -> Result<Self::Path, Self::Error> {
1133 self.empty_path = true;
1134 if cnum == LOCAL_CRATE {
1135 if self.tcx.sess.rust_2018() {
1136 // We add the `crate::` keyword on Rust 2018, only when desired.
1137 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1138 write!(self, "{}", kw::Crate)?;
1139 self.empty_path = false;
1143 write!(self, "{}", self.tcx.crate_name(cnum))?;
1144 self.empty_path = false;
1151 trait_ref: Option<ty::TraitRef<'tcx>>,
1152 ) -> Result<Self::Path, Self::Error> {
1153 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1154 self.empty_path = false;
1158 fn path_append_impl(
1160 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1161 _disambiguated_data: &DisambiguatedDefPathData,
1163 trait_ref: Option<ty::TraitRef<'tcx>>,
1164 ) -> Result<Self::Path, Self::Error> {
1165 self = self.pretty_path_append_impl(|mut cx| {
1166 cx = print_prefix(cx)?;
1172 }, self_ty, trait_ref)?;
1173 self.empty_path = false;
1178 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1179 disambiguated_data: &DisambiguatedDefPathData,
1180 ) -> Result<Self::Path, Self::Error> {
1181 self = print_prefix(self)?;
1183 // Skip `::{{constructor}}` on tuple/unit structs.
1184 match disambiguated_data.data {
1185 DefPathData::Ctor => return Ok(self),
1189 // FIXME(eddyb) `name` should never be empty, but it
1190 // currently is for `extern { ... }` "foreign modules".
1191 let name = disambiguated_data.data.as_interned_str().as_str();
1192 if !name.is_empty() {
1193 if !self.empty_path {
1194 write!(self, "::")?;
1196 write!(self, "{}", name)?;
1198 // FIXME(eddyb) this will print e.g. `{{closure}}#3`, but it
1199 // might be nicer to use something else, e.g. `{closure#3}`.
1200 let dis = disambiguated_data.disambiguator;
1202 disambiguated_data.data.get_opt_name().is_none() ||
1203 dis != 0 && self.tcx.sess.verbose();
1205 write!(self, "#{}", dis)?;
1208 self.empty_path = false;
1213 fn path_generic_args(
1215 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1216 args: &[Kind<'tcx>],
1217 ) -> Result<Self::Path, Self::Error> {
1218 self = print_prefix(self)?;
1220 // Don't print `'_` if there's no unerased regions.
1221 let print_regions = args.iter().any(|arg| {
1222 match arg.unpack() {
1223 UnpackedKind::Lifetime(r) => *r != ty::ReErased,
1227 let args = args.iter().cloned().filter(|arg| {
1228 match arg.unpack() {
1229 UnpackedKind::Lifetime(_) => print_regions,
1234 if args.clone().next().is_some() {
1236 write!(self, "::")?;
1238 self.generic_delimiters(|cx| cx.comma_sep(args))
1245 impl<F: fmt::Write> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx, F> {
1246 fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> {
1247 self.0.name_resolver.as_ref().and_then(|func| func(id))
1250 fn print_value_path(
1253 substs: &'tcx [Kind<'tcx>],
1254 ) -> Result<Self::Path, Self::Error> {
1255 let was_in_value = std::mem::replace(&mut self.in_value, true);
1256 self = self.print_def_path(def_id, substs)?;
1257 self.in_value = was_in_value;
1262 fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
1264 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1266 self.pretty_in_binder(value)
1269 fn generic_delimiters(
1271 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1272 ) -> Result<Self, Self::Error> {
1275 let was_in_value = std::mem::replace(&mut self.in_value, false);
1276 let mut inner = f(self)?;
1277 inner.in_value = was_in_value;
1279 write!(inner, ">")?;
1283 fn region_should_not_be_omitted(
1285 region: ty::Region<'_>,
1287 let highlight = self.region_highlight_mode;
1288 if highlight.region_highlighted(region).is_some() {
1292 if self.tcx.sess.verbose() {
1296 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1299 ty::ReEarlyBound(ref data) => {
1300 data.name.as_symbol() != kw::Invalid &&
1301 data.name.as_symbol() != kw::UnderscoreLifetime
1304 ty::ReLateBound(_, br) |
1305 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1306 ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1307 if let ty::BrNamed(_, name) = br {
1308 if name.as_symbol() != kw::Invalid &&
1309 name.as_symbol() != kw::UnderscoreLifetime {
1314 if let Some((region, _)) = highlight.highlight_bound_region {
1324 ty::ReVar(_) if identify_regions => true,
1328 ty::ReErased => false,
1332 ty::ReClosureBound(_) => true,
1337 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1338 impl<F: fmt::Write> FmtPrinter<'_, '_, F> {
1339 pub fn pretty_print_region(
1341 region: ty::Region<'_>,
1342 ) -> Result<Self, fmt::Error> {
1343 define_scoped_cx!(self);
1345 // Watch out for region highlights.
1346 let highlight = self.region_highlight_mode;
1347 if let Some(n) = highlight.region_highlighted(region) {
1348 p!(write("'{}", n));
1352 if self.tcx.sess.verbose() {
1353 p!(write("{:?}", region));
1357 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1359 // These printouts are concise. They do not contain all the information
1360 // the user might want to diagnose an error, but there is basically no way
1361 // to fit that into a short string. Hence the recommendation to use
1362 // `explain_region()` or `note_and_explain_region()`.
1364 ty::ReEarlyBound(ref data) => {
1365 if data.name.as_symbol() != kw::Invalid {
1366 p!(write("{}", data.name));
1370 ty::ReLateBound(_, br) |
1371 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1372 ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1373 if let ty::BrNamed(_, name) = br {
1374 if name.as_symbol() != kw::Invalid &&
1375 name.as_symbol() != kw::UnderscoreLifetime {
1376 p!(write("{}", name));
1381 if let Some((region, counter)) = highlight.highlight_bound_region {
1383 p!(write("'{}", counter));
1388 ty::ReScope(scope) if identify_regions => {
1390 region::ScopeData::Node =>
1391 p!(write("'{}s", scope.item_local_id().as_usize())),
1392 region::ScopeData::CallSite =>
1393 p!(write("'{}cs", scope.item_local_id().as_usize())),
1394 region::ScopeData::Arguments =>
1395 p!(write("'{}as", scope.item_local_id().as_usize())),
1396 region::ScopeData::Destruction =>
1397 p!(write("'{}ds", scope.item_local_id().as_usize())),
1398 region::ScopeData::Remainder(first_statement_index) => p!(write(
1400 scope.item_local_id().as_usize(),
1401 first_statement_index.index()
1406 ty::ReVar(region_vid) if identify_regions => {
1407 p!(write("{:?}", region_vid));
1414 p!(write("'static"));
1418 p!(write("'<empty>"));
1422 // The user should never encounter these in unsubstituted form.
1423 ty::ReClosureBound(vid) => {
1424 p!(write("{:?}", vid));
1435 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1436 // `region_index` and `used_region_names`.
1437 impl<F: fmt::Write> FmtPrinter<'_, 'tcx, F> {
1438 pub fn pretty_in_binder<T>(mut self, value: &ty::Binder<T>) -> Result<Self, fmt::Error>
1440 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1442 fn name_by_region_index(index: usize) -> InternedString {
1444 0 => InternedString::intern("'r"),
1445 1 => InternedString::intern("'s"),
1446 i => InternedString::intern(&format!("'t{}", i-2)),
1450 // Replace any anonymous late-bound regions with named
1451 // variants, using gensym'd identifiers, so that we can
1452 // clearly differentiate between named and unnamed regions in
1453 // the output. We'll probably want to tweak this over time to
1454 // decide just how much information to give.
1455 if self.binder_depth == 0 {
1456 self.prepare_late_bound_region_info(value);
1459 let mut empty = true;
1460 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1461 write!(cx, "{}", if empty {
1469 define_scoped_cx!(self);
1471 let old_region_index = self.region_index;
1472 let mut region_index = old_region_index;
1473 let new_value = self.tcx.replace_late_bound_regions(value, |br| {
1474 let _ = start_or_continue(&mut self, "for<", ", ");
1476 ty::BrNamed(_, name) => {
1477 let _ = write!(self, "{}", name);
1483 let name = name_by_region_index(region_index);
1485 if !self.used_region_names.contains(&name) {
1489 let _ = write!(self, "{}", name);
1490 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1493 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
1495 start_or_continue(&mut self, "", "> ")?;
1497 self.binder_depth += 1;
1498 self.region_index = region_index;
1499 let mut inner = new_value.print(self)?;
1500 inner.region_index = old_region_index;
1501 inner.binder_depth -= 1;
1505 fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
1506 where T: TypeFoldable<'tcx>
1509 struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet<InternedString>);
1510 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> {
1511 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
1513 ty::ReLateBound(_, ty::BrNamed(_, name)) => {
1514 self.0.insert(name);
1518 r.super_visit_with(self)
1522 self.used_region_names.clear();
1523 let mut collector = LateBoundRegionNameCollector(&mut self.used_region_names);
1524 value.visit_with(&mut collector);
1525 self.region_index = 0;
1529 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<T>
1531 T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
1534 type Error = P::Error;
1535 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
1540 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
1542 T: Print<'tcx, P, Output = P, Error = P::Error>,
1543 U: Print<'tcx, P, Output = P, Error = P::Error>,
1546 type Error = P::Error;
1547 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
1548 define_scoped_cx!(cx);
1549 p!(print(self.0), write(" : "), print(self.1));
1554 macro_rules! forward_display_to_print {
1556 $(impl fmt::Display for $ty {
1557 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1558 ty::tls::with(|tcx| {
1560 .expect("could not lift for printing")
1561 .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1569 macro_rules! define_print_and_forward_display {
1570 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
1571 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
1573 type Error = fmt::Error;
1574 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
1575 #[allow(unused_mut)]
1577 define_scoped_cx!($cx);
1579 #[allow(unreachable_code)]
1584 forward_display_to_print!($($ty),+);
1588 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
1589 impl fmt::Display for ty::RegionKind {
1590 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1591 ty::tls::with(|tcx| {
1592 self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1598 forward_display_to_print! {
1600 &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1601 &'tcx ty::Const<'tcx>,
1603 // HACK(eddyb) these are exhaustive instead of generic,
1604 // because `for<'tcx>` isn't possible yet.
1605 ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
1606 ty::Binder<ty::TraitRef<'tcx>>,
1607 ty::Binder<ty::FnSig<'tcx>>,
1608 ty::Binder<ty::TraitPredicate<'tcx>>,
1609 ty::Binder<ty::SubtypePredicate<'tcx>>,
1610 ty::Binder<ty::ProjectionPredicate<'tcx>>,
1611 ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1612 ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
1614 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1615 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1618 define_print_and_forward_display! {
1621 &'tcx ty::List<Ty<'tcx>> {
1623 let mut tys = self.iter();
1624 if let Some(&ty) = tys.next() {
1627 p!(write(", "), print(ty));
1633 ty::TypeAndMut<'tcx> {
1634 p!(write("{}", if self.mutbl == hir::MutMutable { "mut " } else { "" }),
1638 ty::ExistentialTraitRef<'tcx> {
1639 // Use a type that can't appear in defaults of type parameters.
1640 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1641 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
1642 p!(print(trait_ref))
1645 ty::ExistentialProjection<'tcx> {
1646 let name = cx.tcx().associated_item(self.item_def_id).ident;
1647 p!(write("{} = ", name), print(self.ty))
1650 ty::ExistentialPredicate<'tcx> {
1652 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
1653 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
1654 ty::ExistentialPredicate::AutoTrait(def_id) => {
1655 p!(print_def_path(def_id, &[]));
1661 if self.unsafety == hir::Unsafety::Unsafe {
1662 p!(write("unsafe "));
1665 if self.abi != Abi::Rust {
1666 p!(write("extern {} ", self.abi));
1669 p!(write("fn"), pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
1673 if cx.tcx().sess.verbose() {
1674 p!(write("{:?}", self));
1678 ty::TyVar(_) => p!(write("_")),
1679 ty::IntVar(_) => p!(write("{}", "{integer}")),
1680 ty::FloatVar(_) => p!(write("{}", "{float}")),
1681 ty::FreshTy(v) => p!(write("FreshTy({})", v)),
1682 ty::FreshIntTy(v) => p!(write("FreshIntTy({})", v)),
1683 ty::FreshFloatTy(v) => p!(write("FreshFloatTy({})", v))
1687 ty::TraitRef<'tcx> {
1688 p!(print_def_path(self.def_id, self.substs));
1692 p!(write("{}", self.name))
1696 p!(write("{}", self.name))
1699 ty::SubtypePredicate<'tcx> {
1700 p!(print(self.a), write(" <: "), print(self.b))
1703 ty::TraitPredicate<'tcx> {
1704 p!(print(self.trait_ref.self_ty()), write(": "), print(self.trait_ref))
1707 ty::ProjectionPredicate<'tcx> {
1708 p!(print(self.projection_ty), write(" == "), print(self.ty))
1711 ty::ProjectionTy<'tcx> {
1712 p!(print_def_path(self.item_def_id, self.substs));
1717 ty::ClosureKind::Fn => p!(write("Fn")),
1718 ty::ClosureKind::FnMut => p!(write("FnMut")),
1719 ty::ClosureKind::FnOnce => p!(write("FnOnce")),
1723 ty::Predicate<'tcx> {
1725 ty::Predicate::Trait(ref data) => p!(print(data)),
1726 ty::Predicate::Subtype(ref predicate) => p!(print(predicate)),
1727 ty::Predicate::RegionOutlives(ref predicate) => p!(print(predicate)),
1728 ty::Predicate::TypeOutlives(ref predicate) => p!(print(predicate)),
1729 ty::Predicate::Projection(ref predicate) => p!(print(predicate)),
1730 ty::Predicate::WellFormed(ty) => p!(print(ty), write(" well-formed")),
1731 ty::Predicate::ObjectSafe(trait_def_id) => {
1732 p!(write("the trait `"),
1733 print_def_path(trait_def_id, &[]),
1734 write("` is object-safe"))
1736 ty::Predicate::ClosureKind(closure_def_id, _closure_substs, kind) => {
1737 p!(write("the closure `"),
1738 print_value_path(closure_def_id, &[]),
1739 write("` implements the trait `{}`", kind))
1741 ty::Predicate::ConstEvaluatable(def_id, substs) => {
1742 p!(write("the constant `"),
1743 print_value_path(def_id, substs),
1744 write("` can be evaluated"))
1750 match self.unpack() {
1751 UnpackedKind::Lifetime(lt) => p!(print(lt)),
1752 UnpackedKind::Type(ty) => p!(print(ty)),
1753 UnpackedKind::Const(ct) => p!(print(ct)),