2 use crate::hir::def::{Namespace, Def};
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,
179 /// Like `print_def_path` but for value paths.
183 substs: &'tcx [Kind<'tcx>],
184 ) -> Result<Self::Path, Self::Error> {
185 self.print_def_path(def_id, substs)
190 value: &ty::Binder<T>,
191 ) -> Result<Self, Self::Error>
192 where T: Print<'gcx, 'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>
194 value.skip_binder().print(self)
197 /// Print comma-separated elements.
200 mut elems: impl Iterator<Item = T>,
201 ) -> Result<Self, Self::Error>
202 where T: Print<'gcx, 'tcx, Self, Output = Self, Error = Self::Error>
204 if let Some(first) = elems.next() {
205 self = first.print(self)?;
207 self.write_str(", ")?;
208 self = elem.print(self)?;
214 /// Print `<...>` around what `f` prints.
215 fn generic_delimiters(
217 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
218 ) -> Result<Self, Self::Error>;
220 /// Return `true` if the region should be printed in
221 /// optional positions, e.g. `&'a T` or `dyn Tr + 'b`.
222 /// This is typically the case for all non-`'_` regions.
223 fn region_should_not_be_omitted(
225 region: ty::Region<'_>,
228 // Defaults (should not be overriden):
230 /// If possible, this returns a global path resolving to `def_id` that is visible
231 /// from at least one local module and returns true. If the crate defining `def_id` is
232 /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
233 fn try_print_visible_def_path(
236 ) -> Result<(Self, bool), Self::Error> {
237 define_scoped_cx!(self);
239 debug!("try_print_visible_def_path: def_id={:?}", def_id);
241 // If `def_id` is a direct or injected extern crate, return the
242 // path to the crate followed by the path to the item within the crate.
243 if def_id.index == CRATE_DEF_INDEX {
244 let cnum = def_id.krate;
246 if cnum == LOCAL_CRATE {
247 return Ok((self.path_crate(cnum)?, true));
250 // In local mode, when we encounter a crate other than
251 // LOCAL_CRATE, execution proceeds in one of two ways:
253 // 1. for a direct dependency, where user added an
254 // `extern crate` manually, we put the `extern
255 // crate` as the parent. So you wind up with
256 // something relative to the current crate.
257 // 2. for an extern inferred from a path or an indirect crate,
258 // where there is no explicit `extern crate`, we just prepend
260 match self.tcx().extern_crate(def_id) {
262 src: ExternCrateSource::Extern(def_id),
267 debug!("try_print_visible_def_path: def_id={:?}", def_id);
268 return Ok((if !span.is_dummy() {
269 self.print_def_path(def_id, &[])?
271 self.path_crate(cnum)?
275 return Ok((self.path_crate(cnum)?, true));
281 if def_id.is_local() {
282 return Ok((self, false));
285 let visible_parent_map = self.tcx().visible_parent_map(LOCAL_CRATE);
287 let mut cur_def_key = self.tcx().def_key(def_id);
288 debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
290 // For a constructor we want the name of its parent rather than <unnamed>.
291 match cur_def_key.disambiguated_data.data {
292 DefPathData::Ctor => {
295 index: cur_def_key.parent
296 .expect("DefPathData::Ctor/VariantData missing a parent"),
299 cur_def_key = self.tcx().def_key(parent);
304 let visible_parent = match visible_parent_map.get(&def_id).cloned() {
305 Some(parent) => parent,
306 None => return Ok((self, false)),
308 // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
309 // knowing ahead of time whether the entire path will succeed or not.
310 // To support printers that do not implement `PrettyPrinter`, a `Vec` or
311 // linked list on the stack would need to be built, before any printing.
312 match self.try_print_visible_def_path(visible_parent)? {
313 (cx, false) => return Ok((cx, false)),
314 (cx, true) => self = cx,
316 let actual_parent = self.tcx().parent(def_id);
318 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
319 visible_parent, actual_parent,
322 let mut data = cur_def_key.disambiguated_data.data;
324 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
325 data, visible_parent, actual_parent,
329 // In order to output a path that could actually be imported (valid and visible),
330 // we need to handle re-exports correctly.
332 // For example, take `std::os::unix::process::CommandExt`, this trait is actually
333 // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
335 // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is
336 // private so the "true" path to `CommandExt` isn't accessible.
338 // In this case, the `visible_parent_map` will look something like this:
340 // (child) -> (parent)
341 // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
342 // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
343 // `std::sys::unix::ext` -> `std::os`
345 // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
348 // When printing the path to `CommandExt` and looking at the `cur_def_key` that
349 // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
350 // to the parent - resulting in a mangled path like
351 // `std::os::ext::process::CommandExt`.
353 // Instead, we must detect that there was a re-export and instead print `unix`
354 // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
355 // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
356 // the visible parent (`std::os`). If these do not match, then we iterate over
357 // the children of the visible parent (as was done when computing
358 // `visible_parent_map`), looking for the specific child we currently have and then
359 // have access to the re-exported name.
360 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
361 let reexport = self.tcx().item_children(visible_parent)
363 .find(|child| child.res.def_id() == def_id)
364 .map(|child| child.ident.as_interned_str());
365 if let Some(reexport) = reexport {
369 // Re-exported `extern crate` (#43189).
370 DefPathData::CrateRoot => {
371 data = DefPathData::TypeNs(
372 self.tcx().original_crate_name(def_id.krate).as_interned_str(),
377 debug!("try_print_visible_def_path: data={:?}", data);
379 Ok((self.path_append(Ok, &DisambiguatedDefPathData {
385 fn pretty_path_qualified(
388 trait_ref: Option<ty::TraitRef<'tcx>>,
389 ) -> Result<Self::Path, Self::Error> {
390 if trait_ref.is_none() {
391 // Inherent impls. Try to print `Foo::bar` for an inherent
392 // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
393 // anything other than a simple path.
395 ty::Adt(..) | ty::Foreign(_) |
396 ty::Bool | ty::Char | ty::Str |
397 ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
398 return self_ty.print(self);
405 self.generic_delimiters(|mut cx| {
406 define_scoped_cx!(cx);
409 if let Some(trait_ref) = trait_ref {
410 p!(write(" as "), print(trait_ref));
416 fn pretty_path_append_impl(
418 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
420 trait_ref: Option<ty::TraitRef<'tcx>>,
421 ) -> Result<Self::Path, Self::Error> {
422 self = print_prefix(self)?;
424 self.generic_delimiters(|mut cx| {
425 define_scoped_cx!(cx);
428 if let Some(trait_ref) = trait_ref {
429 p!(print(trait_ref), write(" for "));
437 fn pretty_print_type(
440 ) -> Result<Self::Type, Self::Error> {
441 define_scoped_cx!(self);
444 ty::Bool => p!(write("bool")),
445 ty::Char => p!(write("char")),
446 ty::Int(t) => p!(write("{}", t.ty_to_string())),
447 ty::Uint(t) => p!(write("{}", t.ty_to_string())),
448 ty::Float(t) => p!(write("{}", t.ty_to_string())),
449 ty::RawPtr(ref tm) => {
450 p!(write("*{} ", match tm.mutbl {
451 hir::MutMutable => "mut",
452 hir::MutImmutable => "const",
456 ty::Ref(r, ty, mutbl) => {
458 if self.region_should_not_be_omitted(r) {
459 p!(print(r), write(" "));
461 p!(print(ty::TypeAndMut { ty, mutbl }))
463 ty::Never => p!(write("!")),
464 ty::Tuple(ref tys) => {
466 let mut tys = tys.iter();
467 if let Some(&ty) = tys.next() {
468 p!(print(ty), write(","));
469 if let Some(&ty) = tys.next() {
470 p!(write(" "), print(ty));
472 p!(write(", "), print(ty));
478 ty::FnDef(def_id, substs) => {
479 let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs);
480 p!(print(sig), write(" {{"), print_value_path(def_id, substs), write("}}"));
482 ty::FnPtr(ref bare_fn) => {
485 ty::Infer(infer_ty) => p!(write("{}", infer_ty)),
486 ty::Error => p!(write("[type error]")),
487 ty::Param(ref param_ty) => p!(write("{}", param_ty)),
488 ty::Bound(debruijn, bound_ty) => {
489 match bound_ty.kind {
490 ty::BoundTyKind::Anon => {
491 if debruijn == ty::INNERMOST {
492 p!(write("^{}", bound_ty.var.index()))
494 p!(write("^{}_{}", debruijn.index(), bound_ty.var.index()))
498 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
501 ty::Adt(def, substs) => {
502 p!(print_def_path(def.did, substs));
504 ty::Dynamic(data, r) => {
505 let print_r = self.region_should_not_be_omitted(r);
509 p!(write("dyn "), print(data));
511 p!(write(" + "), print(r), write(")"));
514 ty::Foreign(def_id) => {
515 p!(print_def_path(def_id, &[]));
517 ty::Projection(ref data) => p!(print(data)),
518 ty::UnnormalizedProjection(ref data) => {
519 p!(write("Unnormalized("), print(data), write(")"))
521 ty::Placeholder(placeholder) => {
522 p!(write("Placeholder({:?})", placeholder))
524 ty::Opaque(def_id, substs) => {
525 // FIXME(eddyb) print this with `print_def_path`.
526 if self.tcx().sess.verbose() {
527 p!(write("Opaque({:?}, {:?})", def_id, substs));
531 let def_key = self.tcx().def_key(def_id);
532 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
533 p!(write("{}", name));
534 let mut substs = substs.iter();
535 // FIXME(eddyb) print this with `print_def_path`.
536 if let Some(first) = substs.next() {
539 for subst in substs {
540 p!(write(", "), print(subst));
546 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
547 // by looking up the projections associated with the def_id.
548 let bounds = self.tcx().predicates_of(def_id).instantiate(self.tcx(), substs);
550 let mut first = true;
551 let mut is_sized = false;
553 for predicate in bounds.predicates {
554 if let Some(trait_ref) = predicate.to_opt_poly_trait_ref() {
555 // Don't print +Sized, but rather +?Sized if absent.
556 if Some(trait_ref.def_id()) == self.tcx().lang_items().sized_trait() {
562 write("{}", if first { " " } else { "+" }),
568 p!(write("{}?Sized", if first { " " } else { "+" }));
573 ty::Str => p!(write("str")),
574 ty::Generator(did, substs, movability) => {
575 let upvar_tys = substs.upvar_tys(did, self.tcx());
576 let witness = substs.witness(did, self.tcx());
577 if movability == hir::GeneratorMovability::Movable {
578 p!(write("[generator"));
580 p!(write("[static generator"));
583 // FIXME(eddyb) should use `def_span`.
584 if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
585 p!(write("@{:?}", self.tcx().hir().span_by_hir_id(hir_id)));
587 for (upvar, upvar_ty) in self.tcx().upvars(did)
589 .map_or(&[][..], |v| &v[..])
596 self.tcx().hir().name_by_hir_id(upvar.var_id())),
601 // cross-crate closure types should only be
602 // visible in codegen bug reports, I imagine.
603 p!(write("@{:?}", did));
605 for (index, upvar_ty) in upvar_tys.enumerate() {
607 write("{}{}:", sep, index),
613 p!(write(" "), print(witness), write("]"))
615 ty::GeneratorWitness(types) => {
616 p!(in_binder(&types));
618 ty::Closure(did, substs) => {
619 let upvar_tys = substs.upvar_tys(did, self.tcx());
620 p!(write("[closure"));
622 // FIXME(eddyb) should use `def_span`.
623 if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
624 if self.tcx().sess.opts.debugging_opts.span_free_formats {
625 p!(write("@{:?}", hir_id));
627 p!(write("@{:?}", self.tcx().hir().span_by_hir_id(hir_id)));
630 for (upvar, upvar_ty) in self.tcx().upvars(did)
632 .map_or(&[][..], |v| &v[..])
639 self.tcx().hir().name_by_hir_id(upvar.var_id())),
644 // cross-crate closure types should only be
645 // visible in codegen bug reports, I imagine.
646 p!(write("@{:?}", did));
648 for (index, upvar_ty) in upvar_tys.enumerate() {
650 write("{}{}:", sep, index),
656 if self.tcx().sess.verbose() {
658 " closure_kind_ty={:?} closure_sig_ty={:?}",
659 substs.closure_kind_ty(did, self.tcx()),
660 substs.closure_sig_ty(did, self.tcx())
666 ty::Array(ty, sz) => {
667 p!(write("["), print(ty), write("; "));
669 ConstValue::Unevaluated(..) |
670 ConstValue::Infer(..) => p!(write("_")),
671 ConstValue::Param(ParamConst { name, .. }) =>
672 p!(write("{}", name)),
673 _ => p!(write("{}", sz.unwrap_usize(self.tcx()))),
678 p!(write("["), print(ty), write("]"))
685 fn pretty_print_dyn_existential(
687 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
688 ) -> Result<Self::DynExistential, Self::Error> {
689 define_scoped_cx!(self);
691 // Generate the main trait ref, including associated types.
692 let mut first = true;
694 if let Some(principal) = predicates.principal() {
695 p!(print_def_path(principal.def_id, &[]));
697 let mut resugared = false;
699 // Special-case `Fn(...) -> ...` and resugar it.
700 let fn_trait_kind = self.tcx().lang_items().fn_trait_kind(principal.def_id);
701 if !self.tcx().sess.verbose() && fn_trait_kind.is_some() {
702 if let ty::Tuple(ref args) = principal.substs.type_at(0).sty {
703 let mut projections = predicates.projection_bounds();
704 if let (Some(proj), None) = (projections.next(), projections.next()) {
705 let tys: Vec<_> = args.iter().map(|k| k.expect_ty()).collect();
706 p!(pretty_fn_sig(&tys, false, proj.ty));
712 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
713 // in order to place the projections inside the `<...>`.
715 // Use a type that can't appear in defaults of type parameters.
716 let dummy_self = self.tcx().mk_ty_infer(ty::FreshTy(0));
717 let principal = principal.with_self_ty(self.tcx(), dummy_self);
719 let args = self.generic_args_to_print(
720 self.tcx().generics_of(principal.def_id),
724 // Don't print `'_` if there's no unerased regions.
725 let print_regions = args.iter().any(|arg| {
727 UnpackedKind::Lifetime(r) => *r != ty::ReErased,
731 let mut args = args.iter().cloned().filter(|arg| {
733 UnpackedKind::Lifetime(_) => print_regions,
737 let mut projections = predicates.projection_bounds();
739 let arg0 = args.next();
740 let projection0 = projections.next();
741 if arg0.is_some() || projection0.is_some() {
742 let args = arg0.into_iter().chain(args);
743 let projections = projection0.into_iter().chain(projections);
745 p!(generic_delimiters(|mut cx| {
746 cx = cx.comma_sep(args)?;
747 if arg0.is_some() && projection0.is_some() {
750 cx.comma_sep(projections)
758 // FIXME(eddyb) avoid printing twice (needed to ensure
759 // that the auto traits are sorted *and* printed via cx).
760 let mut auto_traits: Vec<_> = predicates.auto_traits().map(|did| {
761 (self.tcx().def_path_str(did), did)
764 // The auto traits come ordered by `DefPathHash`. While
765 // `DefPathHash` is *stable* in the sense that it depends on
766 // neither the host nor the phase of the moon, it depends
767 // "pseudorandomly" on the compiler version and the target.
769 // To avoid that causing instabilities in compiletest
770 // output, sort the auto-traits alphabetically.
773 for (_, def_id) in auto_traits {
779 p!(print_def_path(def_id, &[]));
790 ) -> Result<Self, Self::Error> {
791 define_scoped_cx!(self);
794 let mut inputs = inputs.iter();
795 if let Some(&ty) = inputs.next() {
798 p!(write(", "), print(ty));
805 if !output.is_unit() {
806 p!(write(" -> "), print(output));
813 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
814 pub struct FmtPrinter<'a, 'gcx, 'tcx, F>(Box<FmtPrinterData<'a, 'gcx, 'tcx, F>>);
816 pub struct FmtPrinterData<'a, 'gcx, 'tcx, F> {
817 tcx: TyCtxt<'a, 'gcx, 'tcx>,
823 used_region_names: FxHashSet<InternedString>,
827 pub region_highlight_mode: RegionHighlightMode,
830 impl<F> Deref for FmtPrinter<'a, 'gcx, 'tcx, F> {
831 type Target = FmtPrinterData<'a, 'gcx, 'tcx, F>;
832 fn deref(&self) -> &Self::Target {
837 impl<F> DerefMut for FmtPrinter<'_, '_, '_, F> {
838 fn deref_mut(&mut self) -> &mut Self::Target {
843 impl<F> FmtPrinter<'a, 'gcx, 'tcx, F> {
844 pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>, fmt: F, ns: Namespace) -> Self {
845 FmtPrinter(Box::new(FmtPrinterData {
849 in_value: ns == Namespace::ValueNS,
850 used_region_names: Default::default(),
853 region_highlight_mode: RegionHighlightMode::default(),
858 impl TyCtxt<'_, '_, '_> {
859 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
860 // (but also some things just print a `DefId` generally so maybe we need this?)
861 fn guess_def_namespace(self, def_id: DefId) -> Namespace {
862 match self.def_key(def_id).disambiguated_data.data {
863 DefPathData::TypeNs(..)
864 | DefPathData::CrateRoot
865 | DefPathData::ImplTrait => Namespace::TypeNS,
867 DefPathData::ValueNs(..)
868 | DefPathData::AnonConst
869 | DefPathData::ClosureExpr
870 | DefPathData::Ctor => Namespace::ValueNS,
872 DefPathData::MacroNs(..) => Namespace::MacroNS,
874 _ => Namespace::TypeNS,
878 /// Returns a string identifying this `DefId`. This string is
879 /// suitable for user output.
880 pub fn def_path_str(self, def_id: DefId) -> String {
881 let ns = self.guess_def_namespace(def_id);
882 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
883 let mut s = String::new();
884 let _ = FmtPrinter::new(self, &mut s, ns)
885 .print_def_path(def_id, &[]);
890 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, '_, F> {
891 fn write_str(&mut self, s: &str) -> fmt::Result {
892 self.fmt.write_str(s)
896 impl<F: fmt::Write> Printer<'gcx, 'tcx> for FmtPrinter<'_, 'gcx, 'tcx, F> {
897 type Error = fmt::Error;
902 type DynExistential = Self;
904 fn tcx(&'a self) -> TyCtxt<'a, 'gcx, 'tcx> {
911 substs: &'tcx [Kind<'tcx>],
912 ) -> Result<Self::Path, Self::Error> {
913 define_scoped_cx!(self);
915 if substs.is_empty() {
916 match self.try_print_visible_def_path(def_id)? {
917 (cx, true) => return Ok(cx),
918 (cx, false) => self = cx,
922 let key = self.tcx.def_key(def_id);
923 if let DefPathData::Impl = key.disambiguated_data.data {
924 // Always use types for non-local impls, where types are always
925 // available, and filename/line-number is mostly uninteresting.
927 !def_id.is_local() || {
928 // Otherwise, use filename/line-number if forced.
929 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
934 // If no type info is available, fall back to
935 // pretty printing some span information. This should
936 // only occur very early in the compiler pipeline.
937 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
938 let span = self.tcx.def_span(def_id);
940 self = self.print_def_path(parent_def_id, &[])?;
942 // HACK(eddyb) copy of `path_append` to avoid
943 // constructing a `DisambiguatedDefPathData`.
944 if !self.empty_path {
947 write!(self, "<impl at {:?}>", span)?;
948 self.empty_path = false;
954 self.default_print_def_path(def_id, substs)
959 region: ty::Region<'_>,
960 ) -> Result<Self::Region, Self::Error> {
961 self.pretty_print_region(region)
967 ) -> Result<Self::Type, Self::Error> {
968 self.pretty_print_type(ty)
971 fn print_dyn_existential(
973 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
974 ) -> Result<Self::DynExistential, Self::Error> {
975 self.pretty_print_dyn_existential(predicates)
981 ) -> Result<Self::Path, Self::Error> {
982 self.empty_path = true;
983 if cnum == LOCAL_CRATE {
984 if self.tcx.sess.rust_2018() {
985 // We add the `crate::` keyword on Rust 2018, only when desired.
986 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
987 write!(self, "{}", kw::Crate)?;
988 self.empty_path = false;
992 write!(self, "{}", self.tcx.crate_name(cnum))?;
993 self.empty_path = false;
1000 trait_ref: Option<ty::TraitRef<'tcx>>,
1001 ) -> Result<Self::Path, Self::Error> {
1002 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1003 self.empty_path = false;
1007 fn path_append_impl(
1009 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1010 _disambiguated_data: &DisambiguatedDefPathData,
1012 trait_ref: Option<ty::TraitRef<'tcx>>,
1013 ) -> Result<Self::Path, Self::Error> {
1014 self = self.pretty_path_append_impl(|mut cx| {
1015 cx = print_prefix(cx)?;
1021 }, self_ty, trait_ref)?;
1022 self.empty_path = false;
1027 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1028 disambiguated_data: &DisambiguatedDefPathData,
1029 ) -> Result<Self::Path, Self::Error> {
1030 self = print_prefix(self)?;
1032 // Skip `::{{constructor}}` on tuple/unit structs.
1033 match disambiguated_data.data {
1034 DefPathData::Ctor => return Ok(self),
1038 // FIXME(eddyb) `name` should never be empty, but it
1039 // currently is for `extern { ... }` "foreign modules".
1040 let name = disambiguated_data.data.as_interned_str().as_str();
1041 if !name.is_empty() {
1042 if !self.empty_path {
1043 write!(self, "::")?;
1045 write!(self, "{}", name)?;
1047 // FIXME(eddyb) this will print e.g. `{{closure}}#3`, but it
1048 // might be nicer to use something else, e.g. `{closure#3}`.
1049 let dis = disambiguated_data.disambiguator;
1051 disambiguated_data.data.get_opt_name().is_none() ||
1052 dis != 0 && self.tcx.sess.verbose();
1054 write!(self, "#{}", dis)?;
1057 self.empty_path = false;
1062 fn path_generic_args(
1064 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1065 args: &[Kind<'tcx>],
1066 ) -> Result<Self::Path, Self::Error> {
1067 self = print_prefix(self)?;
1069 // Don't print `'_` if there's no unerased regions.
1070 let print_regions = args.iter().any(|arg| {
1071 match arg.unpack() {
1072 UnpackedKind::Lifetime(r) => *r != ty::ReErased,
1076 let args = args.iter().cloned().filter(|arg| {
1077 match arg.unpack() {
1078 UnpackedKind::Lifetime(_) => print_regions,
1083 if args.clone().next().is_some() {
1085 write!(self, "::")?;
1087 self.generic_delimiters(|cx| cx.comma_sep(args))
1094 impl<F: fmt::Write> PrettyPrinter<'gcx, 'tcx> for FmtPrinter<'_, 'gcx, 'tcx, F> {
1095 fn print_value_path(
1098 substs: &'tcx [Kind<'tcx>],
1099 ) -> Result<Self::Path, Self::Error> {
1100 let was_in_value = std::mem::replace(&mut self.in_value, true);
1101 self = self.print_def_path(def_id, substs)?;
1102 self.in_value = was_in_value;
1109 value: &ty::Binder<T>,
1110 ) -> Result<Self, Self::Error>
1111 where T: Print<'gcx, 'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>
1113 self.pretty_in_binder(value)
1116 fn generic_delimiters(
1118 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1119 ) -> Result<Self, Self::Error> {
1122 let was_in_value = std::mem::replace(&mut self.in_value, false);
1123 let mut inner = f(self)?;
1124 inner.in_value = was_in_value;
1126 write!(inner, ">")?;
1130 fn region_should_not_be_omitted(
1132 region: ty::Region<'_>,
1134 let highlight = self.region_highlight_mode;
1135 if highlight.region_highlighted(region).is_some() {
1139 if self.tcx.sess.verbose() {
1143 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1146 ty::ReEarlyBound(ref data) => {
1147 data.name.as_symbol() != kw::Invalid &&
1148 data.name.as_symbol() != kw::UnderscoreLifetime
1151 ty::ReLateBound(_, br) |
1152 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1153 ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1154 if let ty::BrNamed(_, name) = br {
1155 if name.as_symbol() != kw::Invalid &&
1156 name.as_symbol() != kw::UnderscoreLifetime {
1161 if let Some((region, _)) = highlight.highlight_bound_region {
1171 ty::ReVar(_) if identify_regions => true,
1175 ty::ReErased => false,
1179 ty::ReClosureBound(_) => true,
1184 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1185 impl<F: fmt::Write> FmtPrinter<'_, '_, '_, F> {
1186 pub fn pretty_print_region(
1188 region: ty::Region<'_>,
1189 ) -> Result<Self, fmt::Error> {
1190 define_scoped_cx!(self);
1192 // Watch out for region highlights.
1193 let highlight = self.region_highlight_mode;
1194 if let Some(n) = highlight.region_highlighted(region) {
1195 p!(write("'{}", n));
1199 if self.tcx.sess.verbose() {
1200 p!(write("{:?}", region));
1204 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1206 // These printouts are concise. They do not contain all the information
1207 // the user might want to diagnose an error, but there is basically no way
1208 // to fit that into a short string. Hence the recommendation to use
1209 // `explain_region()` or `note_and_explain_region()`.
1211 ty::ReEarlyBound(ref data) => {
1212 if data.name.as_symbol() != kw::Invalid {
1213 p!(write("{}", data.name));
1217 ty::ReLateBound(_, br) |
1218 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1219 ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1220 if let ty::BrNamed(_, name) = br {
1221 if name.as_symbol() != kw::Invalid &&
1222 name.as_symbol() != kw::UnderscoreLifetime {
1223 p!(write("{}", name));
1228 if let Some((region, counter)) = highlight.highlight_bound_region {
1230 p!(write("'{}", counter));
1235 ty::ReScope(scope) if identify_regions => {
1237 region::ScopeData::Node =>
1238 p!(write("'{}s", scope.item_local_id().as_usize())),
1239 region::ScopeData::CallSite =>
1240 p!(write("'{}cs", scope.item_local_id().as_usize())),
1241 region::ScopeData::Arguments =>
1242 p!(write("'{}as", scope.item_local_id().as_usize())),
1243 region::ScopeData::Destruction =>
1244 p!(write("'{}ds", scope.item_local_id().as_usize())),
1245 region::ScopeData::Remainder(first_statement_index) => p!(write(
1247 scope.item_local_id().as_usize(),
1248 first_statement_index.index()
1253 ty::ReVar(region_vid) if identify_regions => {
1254 p!(write("{:?}", region_vid));
1261 p!(write("'static"));
1265 p!(write("'<empty>"));
1269 // The user should never encounter these in unsubstituted form.
1270 ty::ReClosureBound(vid) => {
1271 p!(write("{:?}", vid));
1282 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1283 // `region_index` and `used_region_names`.
1284 impl<F: fmt::Write> FmtPrinter<'_, 'gcx, 'tcx, F> {
1285 pub fn pretty_in_binder<T>(
1287 value: &ty::Binder<T>,
1288 ) -> Result<Self, fmt::Error>
1289 where T: Print<'gcx, 'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>
1291 fn name_by_region_index(index: usize) -> InternedString {
1293 0 => InternedString::intern("'r"),
1294 1 => InternedString::intern("'s"),
1295 i => InternedString::intern(&format!("'t{}", i-2)),
1299 // Replace any anonymous late-bound regions with named
1300 // variants, using gensym'd identifiers, so that we can
1301 // clearly differentiate between named and unnamed regions in
1302 // the output. We'll probably want to tweak this over time to
1303 // decide just how much information to give.
1304 if self.binder_depth == 0 {
1305 self.prepare_late_bound_region_info(value);
1308 let mut empty = true;
1309 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1310 write!(cx, "{}", if empty {
1318 define_scoped_cx!(self);
1320 let old_region_index = self.region_index;
1321 let mut region_index = old_region_index;
1322 let new_value = self.tcx.replace_late_bound_regions(value, |br| {
1323 let _ = start_or_continue(&mut self, "for<", ", ");
1325 ty::BrNamed(_, name) => {
1326 let _ = write!(self, "{}", name);
1333 let name = name_by_region_index(region_index);
1335 if !self.used_region_names.contains(&name) {
1339 let _ = write!(self, "{}", name);
1340 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1343 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
1345 start_or_continue(&mut self, "", "> ")?;
1347 self.binder_depth += 1;
1348 self.region_index = region_index;
1349 let mut inner = new_value.print(self)?;
1350 inner.region_index = old_region_index;
1351 inner.binder_depth -= 1;
1355 fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
1356 where T: TypeFoldable<'tcx>
1359 struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet<InternedString>);
1360 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> {
1361 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
1363 ty::ReLateBound(_, ty::BrNamed(_, name)) => {
1364 self.0.insert(name);
1368 r.super_visit_with(self)
1372 self.used_region_names.clear();
1373 let mut collector = LateBoundRegionNameCollector(&mut self.used_region_names);
1374 value.visit_with(&mut collector);
1375 self.region_index = 0;
1379 impl<'gcx: 'tcx, 'tcx, T, P: PrettyPrinter<'gcx, 'tcx>> Print<'gcx, 'tcx, P>
1381 where T: Print<'gcx, 'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>
1384 type Error = P::Error;
1385 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
1390 impl<'gcx: 'tcx, 'tcx, T, U, P: PrettyPrinter<'gcx, 'tcx>> Print<'gcx, 'tcx, P>
1391 for ty::OutlivesPredicate<T, U>
1392 where T: Print<'gcx, 'tcx, P, Output = P, Error = P::Error>,
1393 U: Print<'gcx, 'tcx, P, Output = P, Error = P::Error>,
1396 type Error = P::Error;
1397 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
1398 define_scoped_cx!(cx);
1399 p!(print(self.0), write(" : "), print(self.1));
1404 macro_rules! forward_display_to_print {
1406 $(impl fmt::Display for $ty {
1407 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1408 ty::tls::with(|tcx| {
1410 .expect("could not lift for printing")
1411 .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1419 macro_rules! define_print_and_forward_display {
1420 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
1421 $(impl<'gcx: 'tcx, 'tcx, P: PrettyPrinter<'gcx, 'tcx>> Print<'gcx, 'tcx, P> for $ty {
1423 type Error = fmt::Error;
1424 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
1425 #[allow(unused_mut)]
1427 define_scoped_cx!($cx);
1429 #[allow(unreachable_code)]
1434 forward_display_to_print!($($ty),+);
1438 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
1439 impl fmt::Display for ty::RegionKind {
1440 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1441 ty::tls::with(|tcx| {
1442 self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1448 forward_display_to_print! {
1450 &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1452 // HACK(eddyb) these are exhaustive instead of generic,
1453 // because `for<'gcx: 'tcx, 'tcx>` isn't possible yet.
1454 ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
1455 ty::Binder<ty::TraitRef<'tcx>>,
1456 ty::Binder<ty::FnSig<'tcx>>,
1457 ty::Binder<ty::TraitPredicate<'tcx>>,
1458 ty::Binder<ty::SubtypePredicate<'tcx>>,
1459 ty::Binder<ty::ProjectionPredicate<'tcx>>,
1460 ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1461 ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
1463 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1464 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1467 define_print_and_forward_display! {
1470 &'tcx ty::List<Ty<'tcx>> {
1472 let mut tys = self.iter();
1473 if let Some(&ty) = tys.next() {
1476 p!(write(", "), print(ty));
1482 ty::TypeAndMut<'tcx> {
1483 p!(write("{}", if self.mutbl == hir::MutMutable { "mut " } else { "" }),
1487 ty::ExistentialTraitRef<'tcx> {
1488 // Use a type that can't appear in defaults of type parameters.
1489 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1490 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
1491 p!(print(trait_ref))
1494 ty::ExistentialProjection<'tcx> {
1495 let name = cx.tcx().associated_item(self.item_def_id).ident;
1496 p!(write("{} = ", name), print(self.ty))
1499 ty::ExistentialPredicate<'tcx> {
1501 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
1502 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
1503 ty::ExistentialPredicate::AutoTrait(def_id) => {
1504 p!(print_def_path(def_id, &[]));
1510 if self.unsafety == hir::Unsafety::Unsafe {
1511 p!(write("unsafe "));
1514 if self.abi != Abi::Rust {
1515 p!(write("extern {} ", self.abi));
1518 p!(write("fn"), pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
1522 if cx.tcx().sess.verbose() {
1523 p!(write("{:?}", self));
1527 ty::TyVar(_) => p!(write("_")),
1528 ty::IntVar(_) => p!(write("{}", "{integer}")),
1529 ty::FloatVar(_) => p!(write("{}", "{float}")),
1530 ty::FreshTy(v) => p!(write("FreshTy({})", v)),
1531 ty::FreshIntTy(v) => p!(write("FreshIntTy({})", v)),
1532 ty::FreshFloatTy(v) => p!(write("FreshFloatTy({})", v))
1536 ty::TraitRef<'tcx> {
1537 p!(print_def_path(self.def_id, self.substs));
1540 &'tcx ty::Const<'tcx> {
1541 let u8 = cx.tcx().types.u8;
1542 if let ty::FnDef(did, substs) = self.ty.sty {
1543 p!(print_value_path(did, substs));
1546 if let ConstValue::Unevaluated(did, substs) = self.val {
1547 match cx.tcx().describe_def(did) {
1548 | Some(Def::Static(_, _))
1549 | Some(Def::Const(_, false))
1550 | Some(Def::AssociatedConst(_)) => p!(write("{}", cx.tcx().def_path_str(did))),
1551 _ => p!(write("_")),
1555 if let ConstValue::Infer(..) = self.val {
1556 p!(write("_: "), print(self.ty));
1559 if let ConstValue::Param(ParamConst { name, .. }) = self.val {
1560 p!(write("{}", name));
1563 if let ConstValue::Scalar(Scalar::Bits { bits, .. }) = self.val {
1566 p!(write("{}", if bits == 0 { "false" } else { "true" }));
1569 ty::Float(ast::FloatTy::F32) => {
1570 p!(write("{}f32", Single::from_bits(bits)));
1573 ty::Float(ast::FloatTy::F64) => {
1574 p!(write("{}f64", Double::from_bits(bits)));
1578 p!(write("{}{}", bits, ui));
1582 let ty = cx.tcx().lift_to_global(&self.ty).unwrap();
1583 let size = cx.tcx().layout_of(ty::ParamEnv::empty().and(ty))
1586 p!(write("{}{}", sign_extend(bits, size) as i128, i));
1590 p!(write("{:?}", ::std::char::from_u32(bits as u32).unwrap()));
1596 if let ty::Ref(_, ref_ty, _) = self.ty.sty {
1597 let byte_str = match (self.val, &ref_ty.sty) {
1598 (ConstValue::Scalar(Scalar::Ptr(ptr)), ty::Array(t, n)) if *t == u8 => {
1599 let n = n.unwrap_usize(cx.tcx());
1602 .unwrap_memory(ptr.alloc_id)
1603 .get_bytes(&cx.tcx(), ptr, Size::from_bytes(n)).unwrap())
1605 (ConstValue::Slice { data, start, end }, ty::Slice(t)) if *t == u8 => {
1606 Some(&data.bytes[start..end])
1608 (ConstValue::Slice { data, start, end }, ty::Str) => {
1609 let slice = &data.bytes[start..end];
1610 let s = ::std::str::from_utf8(slice)
1611 .expect("non utf8 str from miri");
1612 p!(write("{:?}", s));
1617 if let Some(byte_str) = byte_str {
1619 for &c in byte_str {
1620 for e in std::ascii::escape_default(c) {
1621 p!(write("{}", e as char));
1628 p!(write("{:?} : ", self.val), print(self.ty));
1632 p!(write("{}", self.name))
1636 p!(write("{}", self.name))
1639 ty::SubtypePredicate<'tcx> {
1640 p!(print(self.a), write(" <: "), print(self.b))
1643 ty::TraitPredicate<'tcx> {
1644 p!(print(self.trait_ref.self_ty()), write(": "), print(self.trait_ref))
1647 ty::ProjectionPredicate<'tcx> {
1648 p!(print(self.projection_ty), write(" == "), print(self.ty))
1651 ty::ProjectionTy<'tcx> {
1652 p!(print_def_path(self.item_def_id, self.substs));
1657 ty::ClosureKind::Fn => p!(write("Fn")),
1658 ty::ClosureKind::FnMut => p!(write("FnMut")),
1659 ty::ClosureKind::FnOnce => p!(write("FnOnce")),
1663 ty::Predicate<'tcx> {
1665 ty::Predicate::Trait(ref data) => p!(print(data)),
1666 ty::Predicate::Subtype(ref predicate) => p!(print(predicate)),
1667 ty::Predicate::RegionOutlives(ref predicate) => p!(print(predicate)),
1668 ty::Predicate::TypeOutlives(ref predicate) => p!(print(predicate)),
1669 ty::Predicate::Projection(ref predicate) => p!(print(predicate)),
1670 ty::Predicate::WellFormed(ty) => p!(print(ty), write(" well-formed")),
1671 ty::Predicate::ObjectSafe(trait_def_id) => {
1672 p!(write("the trait `"),
1673 print_def_path(trait_def_id, &[]),
1674 write("` is object-safe"))
1676 ty::Predicate::ClosureKind(closure_def_id, _closure_substs, kind) => {
1677 p!(write("the closure `"),
1678 print_value_path(closure_def_id, &[]),
1679 write("` implements the trait `{}`", kind))
1681 ty::Predicate::ConstEvaluatable(def_id, substs) => {
1682 p!(write("the constant `"),
1683 print_value_path(def_id, substs),
1684 write("` can be evaluated"))
1690 match self.unpack() {
1691 UnpackedKind::Lifetime(lt) => p!(print(lt)),
1692 UnpackedKind::Type(ty) => p!(print(ty)),
1693 UnpackedKind::Const(ct) => p!(print(ct)),