1 use crate::hir::map::{DefPathData, DisambiguatedDefPathData};
2 use crate::middle::cstore::{ExternCrate, ExternCrateSource};
3 use crate::middle::region;
4 use crate::mir::interpret::{sign_extend, truncate, ConstValue, Scalar};
5 use crate::ty::layout::{Integer, IntegerExt, Size};
6 use crate::ty::subst::{GenericArg, GenericArgKind, Subst};
7 use crate::ty::{self, DefIdTree, ParamConst, Ty, TyCtxt, TypeFoldable};
9 use rustc_hir::def::{DefKind, Namespace};
10 use rustc_hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
12 use rustc_apfloat::ieee::{Double, Single};
13 use rustc_apfloat::Float;
14 use rustc_span::symbol::{kw, Symbol};
15 use rustc_target::spec::abi::Abi;
17 use syntax::attr::{SignedInt, UnsignedInt};
20 use std::collections::BTreeMap;
21 use std::fmt::{self, Write as _};
22 use std::ops::{Deref, DerefMut};
24 // `pretty` is a separate module only for organization.
28 (@write($($data:expr),+)) => {
29 write!(scoped_cx!(), $($data),+)?
31 (@print($x:expr)) => {
32 scoped_cx!() = $x.print(scoped_cx!())?
34 (@$method:ident($($arg:expr),*)) => {
35 scoped_cx!() = scoped_cx!().$method($($arg),*)?
37 ($($kind:ident $data:tt),+) => {{
41 macro_rules! define_scoped_cx {
43 #[allow(unused_macros)]
44 macro_rules! scoped_cx {
53 static FORCE_IMPL_FILENAME_LINE: Cell<bool> = Cell::new(false);
54 static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = Cell::new(false);
55 static NO_QUERIES: Cell<bool> = Cell::new(false);
58 /// Avoids running any queries during any prints that occur
59 /// during the closure. This may alter the appearance of some
60 /// types (e.g. forcing verbose printing for opaque types).
61 /// This method is used during some queries (e.g. `predicates_of`
62 /// for opaque types), to ensure that any debug printing that
63 /// occurs during the query computation does not end up recursively
64 /// calling the same query.
65 pub fn with_no_queries<F: FnOnce() -> R, R>(f: F) -> R {
66 NO_QUERIES.with(|no_queries| {
67 let old = no_queries.get();
75 /// Force us to name impls with just the filename/line number. We
76 /// normally try to use types. But at some points, notably while printing
77 /// cycle errors, this can result in extra or suboptimal error output,
78 /// so this variable disables that check.
79 pub fn with_forced_impl_filename_line<F: FnOnce() -> R, R>(f: F) -> R {
80 FORCE_IMPL_FILENAME_LINE.with(|force| {
81 let old = force.get();
89 /// Adds the `crate::` prefix to paths where appropriate.
90 pub fn with_crate_prefix<F: FnOnce() -> R, R>(f: F) -> R {
91 SHOULD_PREFIX_WITH_CRATE.with(|flag| {
100 /// The "region highlights" are used to control region printing during
101 /// specific error messages. When a "region highlight" is enabled, it
102 /// gives an alternate way to print specific regions. For now, we
103 /// always print those regions using a number, so something like "`'0`".
105 /// Regions not selected by the region highlight mode are presently
107 #[derive(Copy, Clone, Default)]
108 pub struct RegionHighlightMode {
109 /// If enabled, when we see the selected region, use "`'N`"
110 /// instead of the ordinary behavior.
111 highlight_regions: [Option<(ty::RegionKind, usize)>; 3],
113 /// If enabled, when printing a "free region" that originated from
114 /// the given `ty::BoundRegion`, print it as "`'1`". Free regions that would ordinarily
115 /// have names print as normal.
117 /// This is used when you have a signature like `fn foo(x: &u32,
118 /// y: &'a u32)` and we want to give a name to the region of the
120 highlight_bound_region: Option<(ty::BoundRegion, usize)>,
123 impl RegionHighlightMode {
124 /// If `region` and `number` are both `Some`, invokes
125 /// `highlighting_region`.
126 pub fn maybe_highlighting_region(
128 region: Option<ty::Region<'_>>,
129 number: Option<usize>,
131 if let Some(k) = region {
132 if let Some(n) = number {
133 self.highlighting_region(k, n);
138 /// Highlights the region inference variable `vid` as `'N`.
139 pub fn highlighting_region(&mut self, region: ty::Region<'_>, number: usize) {
140 let num_slots = self.highlight_regions.len();
141 let first_avail_slot =
142 self.highlight_regions.iter_mut().filter(|s| s.is_none()).next().unwrap_or_else(|| {
143 bug!("can only highlight {} placeholders at a time", num_slots,)
145 *first_avail_slot = Some((*region, number));
148 /// Convenience wrapper for `highlighting_region`.
149 pub fn highlighting_region_vid(&mut self, vid: ty::RegionVid, number: usize) {
150 self.highlighting_region(&ty::ReVar(vid), number)
153 /// Returns `Some(n)` with the number to use for the given region, if any.
154 fn region_highlighted(&self, region: ty::Region<'_>) -> Option<usize> {
155 self.highlight_regions
157 .filter_map(|h| match h {
158 Some((r, n)) if r == region => Some(*n),
164 /// Highlight the given bound region.
165 /// We can only highlight one bound region at a time. See
166 /// the field `highlight_bound_region` for more detailed notes.
167 pub fn highlighting_bound_region(&mut self, br: ty::BoundRegion, number: usize) {
168 assert!(self.highlight_bound_region.is_none());
169 self.highlight_bound_region = Some((br, number));
173 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
174 pub trait PrettyPrinter<'tcx>:
181 DynExistential = Self,
185 /// Like `print_def_path` but for value paths.
189 substs: &'tcx [GenericArg<'tcx>],
190 ) -> Result<Self::Path, Self::Error> {
191 self.print_def_path(def_id, substs)
194 fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
196 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
198 value.skip_binder().print(self)
201 /// Prints comma-separated elements.
202 fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
204 T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
206 if let Some(first) = elems.next() {
207 self = first.print(self)?;
209 self.write_str(", ")?;
210 self = elem.print(self)?;
216 /// Prints `<...>` around what `f` prints.
217 fn generic_delimiters(
219 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
220 ) -> Result<Self, Self::Error>;
222 /// Returns `true` if the region should be printed in
223 /// optional positions, e.g., `&'a T` or `dyn Tr + 'b`.
224 /// This is typically the case for all non-`'_` regions.
225 fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool;
227 // Defaults (should not be overriden):
229 /// If possible, this returns a global path resolving to `def_id` that is visible
230 /// from at least one local module, and returns `true`. If the crate defining `def_id` is
231 /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
232 fn try_print_visible_def_path(self, def_id: DefId) -> Result<(Self, bool), Self::Error> {
233 let mut callers = Vec::new();
234 self.try_print_visible_def_path_recur(def_id, &mut callers)
237 /// Does the work of `try_print_visible_def_path`, building the
238 /// full definition path recursively before attempting to
239 /// post-process it into the valid and visible version that
240 /// accounts for re-exports.
242 /// This method should only be callled by itself or
243 /// `try_print_visible_def_path`.
245 /// `callers` is a chain of visible_parent's leading to `def_id`,
246 /// to support cycle detection during recursion.
247 fn try_print_visible_def_path_recur(
250 callers: &mut Vec<DefId>,
251 ) -> Result<(Self, bool), Self::Error> {
252 define_scoped_cx!(self);
254 debug!("try_print_visible_def_path: def_id={:?}", def_id);
256 // If `def_id` is a direct or injected extern crate, return the
257 // path to the crate followed by the path to the item within the crate.
258 if def_id.index == CRATE_DEF_INDEX {
259 let cnum = def_id.krate;
261 if cnum == LOCAL_CRATE {
262 return Ok((self.path_crate(cnum)?, true));
265 // In local mode, when we encounter a crate other than
266 // LOCAL_CRATE, execution proceeds in one of two ways:
268 // 1. For a direct dependency, where user added an
269 // `extern crate` manually, we put the `extern
270 // crate` as the parent. So you wind up with
271 // something relative to the current crate.
272 // 2. For an extern inferred from a path or an indirect crate,
273 // where there is no explicit `extern crate`, we just prepend
275 match self.tcx().extern_crate(def_id) {
277 src: ExternCrateSource::Extern(def_id),
278 dependency_of: LOCAL_CRATE,
282 debug!("try_print_visible_def_path: def_id={:?}", def_id);
284 if !span.is_dummy() {
285 self.print_def_path(def_id, &[])?
287 self.path_crate(cnum)?
293 return Ok((self.path_crate(cnum)?, true));
299 if def_id.is_local() {
300 return Ok((self, false));
303 let visible_parent_map = self.tcx().visible_parent_map(LOCAL_CRATE);
305 let mut cur_def_key = self.tcx().def_key(def_id);
306 debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
308 // For a constructor, we want the name of its parent rather than <unnamed>.
309 match cur_def_key.disambiguated_data.data {
310 DefPathData::Ctor => {
315 .expect("`DefPathData::Ctor` / `VariantData` missing a parent"),
318 cur_def_key = self.tcx().def_key(parent);
323 let visible_parent = match visible_parent_map.get(&def_id).cloned() {
324 Some(parent) => parent,
325 None => return Ok((self, false)),
327 if callers.contains(&visible_parent) {
328 return Ok((self, false));
330 callers.push(visible_parent);
331 // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
332 // knowing ahead of time whether the entire path will succeed or not.
333 // To support printers that do not implement `PrettyPrinter`, a `Vec` or
334 // linked list on the stack would need to be built, before any printing.
335 match self.try_print_visible_def_path_recur(visible_parent, callers)? {
336 (cx, false) => return Ok((cx, false)),
337 (cx, true) => self = cx,
340 let actual_parent = self.tcx().parent(def_id);
342 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
343 visible_parent, actual_parent,
346 let mut data = cur_def_key.disambiguated_data.data;
348 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
349 data, visible_parent, actual_parent,
353 // In order to output a path that could actually be imported (valid and visible),
354 // we need to handle re-exports correctly.
356 // For example, take `std::os::unix::process::CommandExt`, this trait is actually
357 // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
359 // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is
360 // private so the "true" path to `CommandExt` isn't accessible.
362 // In this case, the `visible_parent_map` will look something like this:
364 // (child) -> (parent)
365 // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
366 // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
367 // `std::sys::unix::ext` -> `std::os`
369 // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
372 // When printing the path to `CommandExt` and looking at the `cur_def_key` that
373 // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
374 // to the parent - resulting in a mangled path like
375 // `std::os::ext::process::CommandExt`.
377 // Instead, we must detect that there was a re-export and instead print `unix`
378 // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
379 // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
380 // the visible parent (`std::os`). If these do not match, then we iterate over
381 // the children of the visible parent (as was done when computing
382 // `visible_parent_map`), looking for the specific child we currently have and then
383 // have access to the re-exported name.
384 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
387 .item_children(visible_parent)
389 .find(|child| child.res.def_id() == def_id)
390 .map(|child| child.ident.name);
391 if let Some(reexport) = reexport {
395 // Re-exported `extern crate` (#43189).
396 DefPathData::CrateRoot => {
397 data = DefPathData::TypeNs(self.tcx().original_crate_name(def_id.krate));
401 debug!("try_print_visible_def_path: data={:?}", data);
403 Ok((self.path_append(Ok, &DisambiguatedDefPathData { data, disambiguator: 0 })?, true))
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.
424 return self_ty.print(self);
431 self.generic_delimiters(|mut cx| {
432 define_scoped_cx!(cx);
435 if let Some(trait_ref) = trait_ref {
436 p!(write(" as "), print(trait_ref.print_only_trait_path()));
442 fn pretty_path_append_impl(
444 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
446 trait_ref: Option<ty::TraitRef<'tcx>>,
447 ) -> Result<Self::Path, Self::Error> {
448 self = print_prefix(self)?;
450 self.generic_delimiters(|mut cx| {
451 define_scoped_cx!(cx);
454 if let Some(trait_ref) = trait_ref {
455 p!(print(trait_ref.print_only_trait_path()), write(" for "));
463 fn pretty_print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
464 define_scoped_cx!(self);
467 ty::Bool => p!(write("bool")),
468 ty::Char => p!(write("char")),
469 ty::Int(t) => p!(write("{}", t.name_str())),
470 ty::Uint(t) => p!(write("{}", t.name_str())),
471 ty::Float(t) => p!(write("{}", t.name_str())),
472 ty::RawPtr(ref tm) => {
476 hir::Mutability::Mut => "mut",
477 hir::Mutability::Not => "const",
482 ty::Ref(r, ty, mutbl) => {
484 if self.region_should_not_be_omitted(r) {
485 p!(print(r), write(" "));
487 p!(print(ty::TypeAndMut { ty, mutbl }))
489 ty::Never => p!(write("!")),
490 ty::Tuple(ref tys) => {
492 let mut tys = tys.iter();
493 if let Some(&ty) = tys.next() {
494 p!(print(ty), write(","));
495 if let Some(&ty) = tys.next() {
496 p!(write(" "), print(ty));
498 p!(write(", "), print(ty));
504 ty::FnDef(def_id, substs) => {
505 let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs);
506 p!(print(sig), write(" {{"), print_value_path(def_id, substs), write("}}"));
508 ty::FnPtr(ref bare_fn) => p!(print(bare_fn)),
509 ty::Infer(infer_ty) => {
510 if let ty::TyVar(ty_vid) = infer_ty {
511 if let Some(name) = self.infer_ty_name(ty_vid) {
512 p!(write("{}", name))
514 p!(write("{}", infer_ty))
517 p!(write("{}", infer_ty))
520 ty::Error => p!(write("[type error]")),
521 ty::Param(ref param_ty) => p!(write("{}", param_ty)),
522 ty::Bound(debruijn, bound_ty) => match bound_ty.kind {
523 ty::BoundTyKind::Anon => {
524 if debruijn == ty::INNERMOST {
525 p!(write("^{}", bound_ty.var.index()))
527 p!(write("^{}_{}", debruijn.index(), bound_ty.var.index()))
531 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
533 ty::Adt(def, substs) => {
534 p!(print_def_path(def.did, substs));
536 ty::Dynamic(data, r) => {
537 let print_r = self.region_should_not_be_omitted(r);
541 p!(write("dyn "), print(data));
543 p!(write(" + "), print(r), write(")"));
546 ty::Foreign(def_id) => {
547 p!(print_def_path(def_id, &[]));
549 ty::Projection(ref data) => p!(print(data)),
550 ty::UnnormalizedProjection(ref data) => {
551 p!(write("Unnormalized("), print(data), write(")"))
553 ty::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
554 ty::Opaque(def_id, substs) => {
555 // FIXME(eddyb) print this with `print_def_path`.
556 // We use verbose printing in 'NO_QUERIES' mode, to
557 // avoid needing to call `predicates_of`. This should
558 // only affect certain debug messages (e.g. messages printed
559 // from `rustc::ty` during the computation of `tcx.predicates_of`),
560 // and should have no effect on any compiler output.
561 if self.tcx().sess.verbose() || NO_QUERIES.with(|q| q.get()) {
562 p!(write("Opaque({:?}, {:?})", def_id, substs));
566 return Ok(with_no_queries(|| {
567 let def_key = self.tcx().def_key(def_id);
568 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
569 p!(write("{}", name));
570 let mut substs = substs.iter();
571 // FIXME(eddyb) print this with `print_def_path`.
572 if let Some(first) = substs.next() {
575 for subst in substs {
576 p!(write(", "), print(subst));
582 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
583 // by looking up the projections associated with the def_id.
584 let bounds = self.tcx().predicates_of(def_id).instantiate(self.tcx(), substs);
586 let mut first = true;
587 let mut is_sized = false;
589 for predicate in bounds.predicates {
590 if let Some(trait_ref) = predicate.to_opt_poly_trait_ref() {
591 // Don't print +Sized, but rather +?Sized if absent.
592 if Some(trait_ref.def_id()) == self.tcx().lang_items().sized_trait() {
598 write("{}", if first { " " } else { "+" }),
599 print(trait_ref.print_only_trait_path())
605 p!(write("{}?Sized", if first { " " } else { "+" }));
612 ty::Str => p!(write("str")),
613 ty::Generator(did, substs, movability) => {
614 let upvar_tys = substs.as_generator().upvar_tys(did, self.tcx());
615 let witness = substs.as_generator().witness(did, self.tcx());
617 hir::Movability::Movable => p!(write("[generator")),
618 hir::Movability::Static => p!(write("[static generator")),
621 // FIXME(eddyb) should use `def_span`.
622 if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
623 p!(write("@{:?}", self.tcx().hir().span(hir_id)));
625 for (&var_id, upvar_ty) in
626 self.tcx().upvars(did).as_ref().iter().flat_map(|v| v.keys()).zip(upvar_tys)
628 p!(write("{}{}:", sep, self.tcx().hir().name(var_id)), print(upvar_ty));
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() {
637 p!(write("{}{}:", sep, index), print(upvar_ty));
642 p!(write(" "), print(witness), write("]"))
644 ty::GeneratorWitness(types) => {
645 p!(in_binder(&types));
647 ty::Closure(did, substs) => {
648 let upvar_tys = substs.as_closure().upvar_tys(did, self.tcx());
649 p!(write("[closure"));
651 // FIXME(eddyb) should use `def_span`.
652 if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
653 if self.tcx().sess.opts.debugging_opts.span_free_formats {
654 p!(write("@"), print_def_path(did, substs));
656 p!(write("@{:?}", self.tcx().hir().span(hir_id)));
659 for (&var_id, upvar_ty) in
660 self.tcx().upvars(did).as_ref().iter().flat_map(|v| v.keys()).zip(upvar_tys)
662 p!(write("{}{}:", sep, self.tcx().hir().name(var_id)), print(upvar_ty));
666 // Cross-crate closure types should only be
667 // visible in codegen bug reports, I imagine.
668 p!(write("@{:?}", did));
670 for (index, upvar_ty) in upvar_tys.enumerate() {
671 p!(write("{}{}:", sep, index), print(upvar_ty));
676 if self.tcx().sess.verbose() {
678 " closure_kind_ty={:?} closure_sig_ty={:?}",
679 substs.as_closure().kind_ty(did, self.tcx()),
680 substs.as_closure().sig_ty(did, self.tcx())
686 ty::Array(ty, sz) => {
687 p!(write("["), print(ty), write("; "));
688 if self.tcx().sess.verbose() {
689 p!(write("{:?}", sz));
690 } else if let ty::ConstKind::Unevaluated(..) = sz.val {
691 // do not try to evalute unevaluated constants. If we are const evaluating an
692 // array length anon const, rustc will (with debug assertions) print the
693 // constant's path. Which will end up here again.
695 } else if let Some(n) = sz.try_eval_usize(self.tcx(), ty::ParamEnv::empty()) {
702 ty::Slice(ty) => p!(write("["), print(ty), write("]")),
708 fn infer_ty_name(&self, _: ty::TyVid) -> Option<String> {
712 fn pretty_print_dyn_existential(
714 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
715 ) -> Result<Self::DynExistential, Self::Error> {
716 define_scoped_cx!(self);
718 // Generate the main trait ref, including associated types.
719 let mut first = true;
721 if let Some(principal) = predicates.principal() {
722 p!(print_def_path(principal.def_id, &[]));
724 let mut resugared = false;
726 // Special-case `Fn(...) -> ...` and resugar it.
727 let fn_trait_kind = self.tcx().lang_items().fn_trait_kind(principal.def_id);
728 if !self.tcx().sess.verbose() && fn_trait_kind.is_some() {
729 if let ty::Tuple(ref args) = principal.substs.type_at(0).kind {
730 let mut projections = predicates.projection_bounds();
731 if let (Some(proj), None) = (projections.next(), projections.next()) {
732 let tys: Vec<_> = args.iter().map(|k| k.expect_ty()).collect();
733 p!(pretty_fn_sig(&tys, false, proj.ty));
739 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
740 // in order to place the projections inside the `<...>`.
742 // Use a type that can't appear in defaults of type parameters.
743 let dummy_self = self.tcx().mk_ty_infer(ty::FreshTy(0));
744 let principal = principal.with_self_ty(self.tcx(), dummy_self);
746 let args = self.generic_args_to_print(
747 self.tcx().generics_of(principal.def_id),
751 // Don't print `'_` if there's no unerased regions.
752 let print_regions = args.iter().any(|arg| match arg.unpack() {
753 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
756 let mut args = args.iter().cloned().filter(|arg| match arg.unpack() {
757 GenericArgKind::Lifetime(_) => print_regions,
760 let mut projections = predicates.projection_bounds();
762 let arg0 = args.next();
763 let projection0 = projections.next();
764 if arg0.is_some() || projection0.is_some() {
765 let args = arg0.into_iter().chain(args);
766 let projections = projection0.into_iter().chain(projections);
768 p!(generic_delimiters(|mut cx| {
769 cx = cx.comma_sep(args)?;
770 if arg0.is_some() && projection0.is_some() {
773 cx.comma_sep(projections)
781 // FIXME(eddyb) avoid printing twice (needed to ensure
782 // that the auto traits are sorted *and* printed via cx).
783 let mut auto_traits: Vec<_> =
784 predicates.auto_traits().map(|did| (self.tcx().def_path_str(did), did)).collect();
786 // The auto traits come ordered by `DefPathHash`. While
787 // `DefPathHash` is *stable* in the sense that it depends on
788 // neither the host nor the phase of the moon, it depends
789 // "pseudorandomly" on the compiler version and the target.
791 // To avoid that causing instabilities in compiletest
792 // output, sort the auto-traits alphabetically.
795 for (_, def_id) in auto_traits {
801 p!(print_def_path(def_id, &[]));
812 ) -> Result<Self, Self::Error> {
813 define_scoped_cx!(self);
816 let mut inputs = inputs.iter();
817 if let Some(&ty) = inputs.next() {
820 p!(write(", "), print(ty));
827 if !output.is_unit() {
828 p!(write(" -> "), print(output));
834 fn pretty_print_const(mut self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
835 define_scoped_cx!(self);
837 if self.tcx().sess.verbose() {
838 p!(write("Const({:?}: {:?})", ct.val, ct.ty));
842 match (ct.val, &ct.ty.kind) {
843 (_, ty::FnDef(did, substs)) => p!(print_value_path(*did, substs)),
844 (ty::ConstKind::Unevaluated(did, substs, promoted), _) => {
845 if let Some(promoted) = promoted {
846 p!(print_value_path(did, substs));
847 p!(write("::{:?}", promoted));
849 match self.tcx().def_kind(did) {
850 Some(DefKind::Static)
851 | Some(DefKind::Const)
852 | Some(DefKind::AssocConst) => p!(print_value_path(did, substs)),
855 let span = self.tcx().def_span(did);
856 if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span)
858 p!(write("{}", snip))
860 p!(write("_: "), print(ct.ty))
863 p!(write("_: "), print(ct.ty))
869 (ty::ConstKind::Infer(..), _) => p!(write("_: "), print(ct.ty)),
870 (ty::ConstKind::Param(ParamConst { name, .. }), _) => p!(write("{}", name)),
871 (ty::ConstKind::Value(value), _) => return self.pretty_print_const_value(value, ct.ty),
875 p!(write("{:?} : ", ct.val), print(ct.ty))
881 fn pretty_print_const_value(
883 ct: ConstValue<'tcx>,
885 ) -> Result<Self::Const, Self::Error> {
886 define_scoped_cx!(self);
888 if self.tcx().sess.verbose() {
889 p!(write("ConstValue({:?}: {:?})", ct, ty));
893 let u8 = self.tcx().types.u8;
895 match (ct, &ty.kind) {
896 (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Bool) => {
897 p!(write("{}", if data == 0 { "false" } else { "true" }))
899 (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Float(ast::FloatTy::F32)) => {
900 p!(write("{}f32", Single::from_bits(data)))
902 (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Float(ast::FloatTy::F64)) => {
903 p!(write("{}f64", Double::from_bits(data)))
905 (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Uint(ui)) => {
906 let bit_size = Integer::from_attr(&self.tcx(), UnsignedInt(*ui)).size();
907 let max = truncate(u128::max_value(), bit_size);
909 let ui_str = ui.name_str();
911 p!(write("std::{}::MAX", ui_str))
913 p!(write("{}{}", data, ui_str))
916 (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Int(i)) => {
917 let bit_size = Integer::from_attr(&self.tcx(), SignedInt(*i)).size().bits() as u128;
918 let min = 1u128 << (bit_size - 1);
921 let ty = self.tcx().lift(&ty).unwrap();
922 let size = self.tcx().layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size;
923 let i_str = i.name_str();
925 d if d == min => p!(write("std::{}::MIN", i_str)),
926 d if d == max => p!(write("std::{}::MAX", i_str)),
927 _ => p!(write("{}{}", sign_extend(data, size) as i128, i_str)),
930 (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Char) => {
931 p!(write("{:?}", ::std::char::from_u32(data as u32).unwrap()))
933 (ConstValue::Scalar(_), ty::RawPtr(_)) => p!(write("{{pointer}}")),
934 (ConstValue::Scalar(Scalar::Ptr(ptr)), ty::FnPtr(_)) => {
936 let alloc_map = self.tcx().alloc_map.lock();
937 alloc_map.unwrap_fn(ptr.alloc_id)
939 p!(print_value_path(instance.def_id(), instance.substs));
942 let printed = if let ty::Ref(_, ref_ty, _) = ty.kind {
943 let byte_str = match (ct, &ref_ty.kind) {
944 (ConstValue::Scalar(Scalar::Ptr(ptr)), ty::Array(t, n)) if *t == u8 => {
945 let n = n.eval_usize(self.tcx(), ty::ParamEnv::empty());
950 .unwrap_memory(ptr.alloc_id)
951 .get_bytes(&self.tcx(), ptr, Size::from_bytes(n))
955 (ConstValue::Slice { data, start, end }, ty::Slice(t)) if *t == u8 => {
956 // The `inspect` here is okay since we checked the bounds, and there are
957 // no relocations (we have an active slice reference here). We don't use
958 // this result to affect interpreter execution.
959 Some(data.inspect_with_undef_and_ptr_outside_interpreter(start..end))
964 if let Some(byte_str) = byte_str {
967 for e in std::ascii::escape_default(c) {
968 self.write_char(e as char)?;
973 } else if let (ConstValue::Slice { data, start, end }, ty::Str) =
976 // The `inspect` here is okay since we checked the bounds, and there are no
977 // relocations (we have an active `str` reference here). We don't use this
978 // result to affect interpreter execution.
979 let slice = data.inspect_with_undef_and_ptr_outside_interpreter(start..end);
980 let s = ::std::str::from_utf8(slice).expect("non utf8 str from miri");
981 p!(write("{:?}", s));
991 p!(write("{:?} : ", ct), print(ty))
999 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
1000 pub struct FmtPrinter<'a, 'tcx, F>(Box<FmtPrinterData<'a, 'tcx, F>>);
1002 pub struct FmtPrinterData<'a, 'tcx, F> {
1009 used_region_names: FxHashSet<Symbol>,
1010 region_index: usize,
1011 binder_depth: usize,
1013 pub region_highlight_mode: RegionHighlightMode,
1015 pub name_resolver: Option<Box<&'a dyn Fn(ty::sty::TyVid) -> Option<String>>>,
1018 impl<F> Deref for FmtPrinter<'a, 'tcx, F> {
1019 type Target = FmtPrinterData<'a, 'tcx, F>;
1020 fn deref(&self) -> &Self::Target {
1025 impl<F> DerefMut for FmtPrinter<'_, '_, F> {
1026 fn deref_mut(&mut self) -> &mut Self::Target {
1031 impl<F> FmtPrinter<'a, 'tcx, F> {
1032 pub fn new(tcx: TyCtxt<'tcx>, fmt: F, ns: Namespace) -> Self {
1033 FmtPrinter(Box::new(FmtPrinterData {
1037 in_value: ns == Namespace::ValueNS,
1038 used_region_names: Default::default(),
1041 region_highlight_mode: RegionHighlightMode::default(),
1042 name_resolver: None,
1047 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1048 // (but also some things just print a `DefId` generally so maybe we need this?)
1049 fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
1050 match tcx.def_key(def_id).disambiguated_data.data {
1051 DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::ImplTrait => {
1055 DefPathData::ValueNs(..)
1056 | DefPathData::AnonConst
1057 | DefPathData::ClosureExpr
1058 | DefPathData::Ctor => Namespace::ValueNS,
1060 DefPathData::MacroNs(..) => Namespace::MacroNS,
1062 _ => Namespace::TypeNS,
1067 /// Returns a string identifying this `DefId`. This string is
1068 /// suitable for user output.
1069 pub fn def_path_str(self, def_id: DefId) -> String {
1070 self.def_path_str_with_substs(def_id, &[])
1073 pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1074 let ns = guess_def_namespace(self, def_id);
1075 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1076 let mut s = String::new();
1077 let _ = FmtPrinter::new(self, &mut s, ns).print_def_path(def_id, substs);
1082 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, F> {
1083 fn write_str(&mut self, s: &str) -> fmt::Result {
1084 self.fmt.write_str(s)
1088 impl<F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
1089 type Error = fmt::Error;
1094 type DynExistential = Self;
1097 fn tcx(&'a self) -> TyCtxt<'tcx> {
1104 substs: &'tcx [GenericArg<'tcx>],
1105 ) -> Result<Self::Path, Self::Error> {
1106 define_scoped_cx!(self);
1108 if substs.is_empty() {
1109 match self.try_print_visible_def_path(def_id)? {
1110 (cx, true) => return Ok(cx),
1111 (cx, false) => self = cx,
1115 let key = self.tcx.def_key(def_id);
1116 if let DefPathData::Impl = key.disambiguated_data.data {
1117 // Always use types for non-local impls, where types are always
1118 // available, and filename/line-number is mostly uninteresting.
1119 let use_types = !def_id.is_local() || {
1120 // Otherwise, use filename/line-number if forced.
1121 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1126 // If no type info is available, fall back to
1127 // pretty printing some span information. This should
1128 // only occur very early in the compiler pipeline.
1129 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1130 let span = self.tcx.def_span(def_id);
1132 self = self.print_def_path(parent_def_id, &[])?;
1134 // HACK(eddyb) copy of `path_append` to avoid
1135 // constructing a `DisambiguatedDefPathData`.
1136 if !self.empty_path {
1137 write!(self, "::")?;
1139 write!(self, "<impl at {:?}>", span)?;
1140 self.empty_path = false;
1146 self.default_print_def_path(def_id, substs)
1149 fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
1150 self.pretty_print_region(region)
1153 fn print_type(self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1154 self.pretty_print_type(ty)
1157 fn print_dyn_existential(
1159 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1160 ) -> Result<Self::DynExistential, Self::Error> {
1161 self.pretty_print_dyn_existential(predicates)
1164 fn print_const(self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1165 self.pretty_print_const(ct)
1168 fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1169 self.empty_path = true;
1170 if cnum == LOCAL_CRATE {
1171 if self.tcx.sess.rust_2018() {
1172 // We add the `crate::` keyword on Rust 2018, only when desired.
1173 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1174 write!(self, "{}", kw::Crate)?;
1175 self.empty_path = false;
1179 write!(self, "{}", self.tcx.crate_name(cnum))?;
1180 self.empty_path = false;
1188 trait_ref: Option<ty::TraitRef<'tcx>>,
1189 ) -> Result<Self::Path, Self::Error> {
1190 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1191 self.empty_path = false;
1195 fn path_append_impl(
1197 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1198 _disambiguated_data: &DisambiguatedDefPathData,
1200 trait_ref: Option<ty::TraitRef<'tcx>>,
1201 ) -> Result<Self::Path, Self::Error> {
1202 self = self.pretty_path_append_impl(
1204 cx = print_prefix(cx)?;
1214 self.empty_path = false;
1220 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1221 disambiguated_data: &DisambiguatedDefPathData,
1222 ) -> Result<Self::Path, Self::Error> {
1223 self = print_prefix(self)?;
1225 // Skip `::{{constructor}}` on tuple/unit structs.
1226 match disambiguated_data.data {
1227 DefPathData::Ctor => return Ok(self),
1231 // FIXME(eddyb) `name` should never be empty, but it
1232 // currently is for `extern { ... }` "foreign modules".
1233 let name = disambiguated_data.data.as_symbol().as_str();
1234 if !name.is_empty() {
1235 if !self.empty_path {
1236 write!(self, "::")?;
1238 if ast::Ident::from_str(&name).is_raw_guess() {
1239 write!(self, "r#")?;
1241 write!(self, "{}", name)?;
1243 // FIXME(eddyb) this will print e.g. `{{closure}}#3`, but it
1244 // might be nicer to use something else, e.g. `{closure#3}`.
1245 let dis = disambiguated_data.disambiguator;
1246 let print_dis = disambiguated_data.data.get_opt_name().is_none()
1247 || dis != 0 && self.tcx.sess.verbose();
1249 write!(self, "#{}", dis)?;
1252 self.empty_path = false;
1258 fn path_generic_args(
1260 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1261 args: &[GenericArg<'tcx>],
1262 ) -> Result<Self::Path, Self::Error> {
1263 self = print_prefix(self)?;
1265 // Don't print `'_` if there's no unerased regions.
1266 let print_regions = args.iter().any(|arg| match arg.unpack() {
1267 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
1270 let args = args.iter().cloned().filter(|arg| match arg.unpack() {
1271 GenericArgKind::Lifetime(_) => print_regions,
1275 if args.clone().next().is_some() {
1277 write!(self, "::")?;
1279 self.generic_delimiters(|cx| cx.comma_sep(args))
1286 impl<F: fmt::Write> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx, F> {
1287 fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> {
1288 self.0.name_resolver.as_ref().and_then(|func| func(id))
1291 fn print_value_path(
1294 substs: &'tcx [GenericArg<'tcx>],
1295 ) -> Result<Self::Path, Self::Error> {
1296 let was_in_value = std::mem::replace(&mut self.in_value, true);
1297 self = self.print_def_path(def_id, substs)?;
1298 self.in_value = was_in_value;
1303 fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
1305 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1307 self.pretty_in_binder(value)
1310 fn generic_delimiters(
1312 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1313 ) -> Result<Self, Self::Error> {
1316 let was_in_value = std::mem::replace(&mut self.in_value, false);
1317 let mut inner = f(self)?;
1318 inner.in_value = was_in_value;
1320 write!(inner, ">")?;
1324 fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool {
1325 let highlight = self.region_highlight_mode;
1326 if highlight.region_highlighted(region).is_some() {
1330 if self.tcx.sess.verbose() {
1334 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1337 ty::ReEarlyBound(ref data) => {
1338 data.name != kw::Invalid && data.name != kw::UnderscoreLifetime
1341 ty::ReLateBound(_, br)
1342 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1343 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1344 if let ty::BrNamed(_, name) = br {
1345 if name != kw::Invalid && name != kw::UnderscoreLifetime {
1350 if let Some((region, _)) = highlight.highlight_bound_region {
1359 ty::ReScope(_) | ty::ReVar(_) if identify_regions => true,
1361 ty::ReVar(_) | ty::ReScope(_) | ty::ReErased => false,
1363 ty::ReStatic | ty::ReEmpty | ty::ReClosureBound(_) => true,
1368 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1369 impl<F: fmt::Write> FmtPrinter<'_, '_, F> {
1370 pub fn pretty_print_region(mut self, region: ty::Region<'_>) -> Result<Self, fmt::Error> {
1371 define_scoped_cx!(self);
1373 // Watch out for region highlights.
1374 let highlight = self.region_highlight_mode;
1375 if let Some(n) = highlight.region_highlighted(region) {
1376 p!(write("'{}", n));
1380 if self.tcx.sess.verbose() {
1381 p!(write("{:?}", region));
1385 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1387 // These printouts are concise. They do not contain all the information
1388 // the user might want to diagnose an error, but there is basically no way
1389 // to fit that into a short string. Hence the recommendation to use
1390 // `explain_region()` or `note_and_explain_region()`.
1392 ty::ReEarlyBound(ref data) => {
1393 if data.name != kw::Invalid {
1394 p!(write("{}", data.name));
1398 ty::ReLateBound(_, br)
1399 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1400 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1401 if let ty::BrNamed(_, name) = br {
1402 if name != kw::Invalid && name != kw::UnderscoreLifetime {
1403 p!(write("{}", name));
1408 if let Some((region, counter)) = highlight.highlight_bound_region {
1410 p!(write("'{}", counter));
1415 ty::ReScope(scope) if identify_regions => {
1417 region::ScopeData::Node => p!(write("'{}s", scope.item_local_id().as_usize())),
1418 region::ScopeData::CallSite => {
1419 p!(write("'{}cs", scope.item_local_id().as_usize()))
1421 region::ScopeData::Arguments => {
1422 p!(write("'{}as", scope.item_local_id().as_usize()))
1424 region::ScopeData::Destruction => {
1425 p!(write("'{}ds", scope.item_local_id().as_usize()))
1427 region::ScopeData::Remainder(first_statement_index) => p!(write(
1429 scope.item_local_id().as_usize(),
1430 first_statement_index.index()
1435 ty::ReVar(region_vid) if identify_regions => {
1436 p!(write("{:?}", region_vid));
1440 ty::ReScope(_) | ty::ReErased => {}
1442 p!(write("'static"));
1446 p!(write("'<empty>"));
1450 // The user should never encounter these in unsubstituted form.
1451 ty::ReClosureBound(vid) => {
1452 p!(write("{:?}", vid));
1463 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1464 // `region_index` and `used_region_names`.
1465 impl<F: fmt::Write> FmtPrinter<'_, 'tcx, F> {
1466 pub fn name_all_regions<T>(
1468 value: &ty::Binder<T>,
1469 ) -> Result<(Self, (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)), fmt::Error>
1471 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1473 fn name_by_region_index(index: usize) -> Symbol {
1475 0 => Symbol::intern("'r"),
1476 1 => Symbol::intern("'s"),
1477 i => Symbol::intern(&format!("'t{}", i - 2)),
1481 // Replace any anonymous late-bound regions with named
1482 // variants, using new unique identifiers, so that we can
1483 // clearly differentiate between named and unnamed regions in
1484 // the output. We'll probably want to tweak this over time to
1485 // decide just how much information to give.
1486 if self.binder_depth == 0 {
1487 self.prepare_late_bound_region_info(value);
1490 let mut empty = true;
1491 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1504 define_scoped_cx!(self);
1506 let mut region_index = self.region_index;
1507 let new_value = self.tcx.replace_late_bound_regions(value, |br| {
1508 let _ = start_or_continue(&mut self, "for<", ", ");
1510 ty::BrNamed(_, name) => {
1511 let _ = write!(self, "{}", name);
1514 ty::BrAnon(_) | ty::BrEnv => {
1516 let name = name_by_region_index(region_index);
1518 if !self.used_region_names.contains(&name) {
1522 let _ = write!(self, "{}", name);
1523 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1526 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
1528 start_or_continue(&mut self, "", "> ")?;
1530 self.binder_depth += 1;
1531 self.region_index = region_index;
1532 Ok((self, new_value))
1535 pub fn pretty_in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, fmt::Error>
1537 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1539 let old_region_index = self.region_index;
1540 let (new, new_value) = self.name_all_regions(value)?;
1541 let mut inner = new_value.0.print(new)?;
1542 inner.region_index = old_region_index;
1543 inner.binder_depth -= 1;
1547 fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
1549 T: TypeFoldable<'tcx>,
1551 struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet<Symbol>);
1552 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> {
1553 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
1555 ty::ReLateBound(_, ty::BrNamed(_, name)) => {
1556 self.0.insert(name);
1560 r.super_visit_with(self)
1564 self.used_region_names.clear();
1565 let mut collector = LateBoundRegionNameCollector(&mut self.used_region_names);
1566 value.visit_with(&mut collector);
1567 self.region_index = 0;
1571 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<T>
1573 T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
1576 type Error = P::Error;
1577 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
1582 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
1584 T: Print<'tcx, P, Output = P, Error = P::Error>,
1585 U: Print<'tcx, P, Output = P, Error = P::Error>,
1588 type Error = P::Error;
1589 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
1590 define_scoped_cx!(cx);
1591 p!(print(self.0), write(" : "), print(self.1));
1596 macro_rules! forward_display_to_print {
1598 $(impl fmt::Display for $ty {
1599 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1600 ty::tls::with(|tcx| {
1602 .expect("could not lift for printing")
1603 .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1611 macro_rules! define_print_and_forward_display {
1612 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
1613 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
1615 type Error = fmt::Error;
1616 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
1617 #[allow(unused_mut)]
1619 define_scoped_cx!($cx);
1621 #[allow(unreachable_code)]
1626 forward_display_to_print!($($ty),+);
1630 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
1631 impl fmt::Display for ty::RegionKind {
1632 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1633 ty::tls::with(|tcx| {
1634 self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1640 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
1641 /// the trait path. That is, it will print `Trait<U>` instead of
1642 /// `<T as Trait<U>>`.
1643 #[derive(Copy, Clone, TypeFoldable, Lift)]
1644 pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
1646 impl fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
1647 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1648 fmt::Display::fmt(self, f)
1652 impl ty::TraitRef<'tcx> {
1653 pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
1654 TraitRefPrintOnlyTraitPath(self)
1658 impl ty::Binder<ty::TraitRef<'tcx>> {
1659 pub fn print_only_trait_path(self) -> ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>> {
1660 self.map_bound(|tr| tr.print_only_trait_path())
1664 forward_display_to_print! {
1666 &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1667 &'tcx ty::Const<'tcx>,
1669 // HACK(eddyb) these are exhaustive instead of generic,
1670 // because `for<'tcx>` isn't possible yet.
1671 ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
1672 ty::Binder<ty::TraitRef<'tcx>>,
1673 ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>>,
1674 ty::Binder<ty::FnSig<'tcx>>,
1675 ty::Binder<ty::TraitPredicate<'tcx>>,
1676 ty::Binder<ty::SubtypePredicate<'tcx>>,
1677 ty::Binder<ty::ProjectionPredicate<'tcx>>,
1678 ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1679 ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
1681 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1682 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1685 define_print_and_forward_display! {
1688 &'tcx ty::List<Ty<'tcx>> {
1690 let mut tys = self.iter();
1691 if let Some(&ty) = tys.next() {
1694 p!(write(", "), print(ty));
1700 ty::TypeAndMut<'tcx> {
1701 p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
1704 ty::ExistentialTraitRef<'tcx> {
1705 // Use a type that can't appear in defaults of type parameters.
1706 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1707 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
1708 p!(print(trait_ref.print_only_trait_path()))
1711 ty::ExistentialProjection<'tcx> {
1712 let name = cx.tcx().associated_item(self.item_def_id).ident;
1713 p!(write("{} = ", name), print(self.ty))
1716 ty::ExistentialPredicate<'tcx> {
1718 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
1719 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
1720 ty::ExistentialPredicate::AutoTrait(def_id) => {
1721 p!(print_def_path(def_id, &[]));
1727 p!(write("{}", self.unsafety.prefix_str()));
1729 if self.abi != Abi::Rust {
1730 p!(write("extern {} ", self.abi));
1733 p!(write("fn"), pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
1737 if cx.tcx().sess.verbose() {
1738 p!(write("{:?}", self));
1742 ty::TyVar(_) => p!(write("_")),
1743 ty::IntVar(_) => p!(write("{}", "{integer}")),
1744 ty::FloatVar(_) => p!(write("{}", "{float}")),
1745 ty::FreshTy(v) => p!(write("FreshTy({})", v)),
1746 ty::FreshIntTy(v) => p!(write("FreshIntTy({})", v)),
1747 ty::FreshFloatTy(v) => p!(write("FreshFloatTy({})", v))
1751 ty::TraitRef<'tcx> {
1752 p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
1755 TraitRefPrintOnlyTraitPath<'tcx> {
1756 p!(print_def_path(self.0.def_id, self.0.substs));
1760 p!(write("{}", self.name))
1764 p!(write("{}", self.name))
1767 ty::SubtypePredicate<'tcx> {
1768 p!(print(self.a), write(" <: "), print(self.b))
1771 ty::TraitPredicate<'tcx> {
1772 p!(print(self.trait_ref.self_ty()), write(": "),
1773 print(self.trait_ref.print_only_trait_path()))
1776 ty::ProjectionPredicate<'tcx> {
1777 p!(print(self.projection_ty), write(" == "), print(self.ty))
1780 ty::ProjectionTy<'tcx> {
1781 p!(print_def_path(self.item_def_id, self.substs));
1786 ty::ClosureKind::Fn => p!(write("Fn")),
1787 ty::ClosureKind::FnMut => p!(write("FnMut")),
1788 ty::ClosureKind::FnOnce => p!(write("FnOnce")),
1792 ty::Predicate<'tcx> {
1794 ty::Predicate::Trait(ref data, constness) => {
1795 if let ast::Constness::Const = constness {
1796 p!(write("const "));
1800 ty::Predicate::Subtype(ref predicate) => p!(print(predicate)),
1801 ty::Predicate::RegionOutlives(ref predicate) => p!(print(predicate)),
1802 ty::Predicate::TypeOutlives(ref predicate) => p!(print(predicate)),
1803 ty::Predicate::Projection(ref predicate) => p!(print(predicate)),
1804 ty::Predicate::WellFormed(ty) => p!(print(ty), write(" well-formed")),
1805 ty::Predicate::ObjectSafe(trait_def_id) => {
1806 p!(write("the trait `"),
1807 print_def_path(trait_def_id, &[]),
1808 write("` is object-safe"))
1810 ty::Predicate::ClosureKind(closure_def_id, _closure_substs, kind) => {
1811 p!(write("the closure `"),
1812 print_value_path(closure_def_id, &[]),
1813 write("` implements the trait `{}`", kind))
1815 ty::Predicate::ConstEvaluatable(def_id, substs) => {
1816 p!(write("the constant `"),
1817 print_value_path(def_id, substs),
1818 write("` can be evaluated"))
1824 match self.unpack() {
1825 GenericArgKind::Lifetime(lt) => p!(print(lt)),
1826 GenericArgKind::Type(ty) => p!(print(ty)),
1827 GenericArgKind::Const(ct) => p!(print(ct)),