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(
836 ct: &'tcx ty::Const<'tcx>,
838 ) -> Result<Self::Const, Self::Error> {
839 define_scoped_cx!(self);
841 if self.tcx().sess.verbose() {
842 p!(write("Const({:?}: {:?})", ct.val, ct.ty));
846 macro_rules! print_underscore {
850 p!(write(": "), print(ct.ty));
855 match (ct.val, &ct.ty.kind) {
856 (_, ty::FnDef(did, substs)) => p!(print_value_path(*did, substs)),
857 (ty::ConstKind::Unevaluated(did, substs, promoted), _) => {
858 if let Some(promoted) = promoted {
859 p!(print_value_path(did, substs));
860 p!(write("::{:?}", promoted));
862 match self.tcx().def_kind(did) {
863 Some(DefKind::Static)
864 | Some(DefKind::Const)
865 | Some(DefKind::AssocConst) => p!(print_value_path(did, substs)),
868 let span = self.tcx().def_span(did);
869 if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span)
871 p!(write("{}", snip))
882 (ty::ConstKind::Infer(..), _) => print_underscore!(),
883 (ty::ConstKind::Param(ParamConst { name, .. }), _) => p!(write("{}", name)),
884 (ty::ConstKind::Value(value), _) => {
885 return self.pretty_print_const_value(value, ct.ty, print_ty);
890 p!(write("{:?}", ct.val));
892 p!(write(": "), print(ct.ty));
899 fn pretty_print_const_value(
901 ct: ConstValue<'tcx>,
904 ) -> Result<Self::Const, Self::Error> {
905 define_scoped_cx!(self);
907 if self.tcx().sess.verbose() {
908 p!(write("ConstValue({:?}: {:?})", ct, ty));
912 let u8 = self.tcx().types.u8;
914 match (ct, &ty.kind) {
915 (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Bool) => {
916 p!(write("{}", if data == 0 { "false" } else { "true" }))
918 (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Float(ast::FloatTy::F32)) => {
919 p!(write("{}f32", Single::from_bits(data)))
921 (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Float(ast::FloatTy::F64)) => {
922 p!(write("{}f64", Double::from_bits(data)))
924 (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Uint(ui)) => {
925 let bit_size = Integer::from_attr(&self.tcx(), UnsignedInt(*ui)).size();
926 let max = truncate(u128::max_value(), bit_size);
928 let ui_str = ui.name_str();
930 p!(write("std::{}::MAX", ui_str))
932 p!(write("{}{}", data, ui_str))
935 (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Int(i)) => {
936 let bit_size = Integer::from_attr(&self.tcx(), SignedInt(*i)).size().bits() as u128;
937 let min = 1u128 << (bit_size - 1);
940 let ty = self.tcx().lift(&ty).unwrap();
941 let size = self.tcx().layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size;
942 let i_str = i.name_str();
944 d if d == min => p!(write("std::{}::MIN", i_str)),
945 d if d == max => p!(write("std::{}::MAX", i_str)),
946 _ => p!(write("{}{}", sign_extend(data, size) as i128, i_str)),
949 (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Char) => {
950 p!(write("{:?}", ::std::char::from_u32(data as u32).unwrap()))
952 (ConstValue::Scalar(_), ty::RawPtr(_)) => p!(write("{{pointer}}")),
953 (ConstValue::Scalar(Scalar::Ptr(ptr)), ty::FnPtr(_)) => {
955 let alloc_map = self.tcx().alloc_map.lock();
956 alloc_map.unwrap_fn(ptr.alloc_id)
958 p!(print_value_path(instance.def_id(), instance.substs));
961 let printed = if let ty::Ref(_, ref_ty, _) = ty.kind {
962 let byte_str = match (ct, &ref_ty.kind) {
963 (ConstValue::Scalar(Scalar::Ptr(ptr)), ty::Array(t, n)) if *t == u8 => {
964 let n = n.eval_usize(self.tcx(), ty::ParamEnv::empty());
969 .unwrap_memory(ptr.alloc_id)
970 .get_bytes(&self.tcx(), ptr, Size::from_bytes(n))
974 (ConstValue::Slice { data, start, end }, ty::Slice(t)) if *t == u8 => {
975 // The `inspect` here is okay since we checked the bounds, and there are
976 // no relocations (we have an active slice reference here). We don't use
977 // this result to affect interpreter execution.
978 Some(data.inspect_with_undef_and_ptr_outside_interpreter(start..end))
983 if let Some(byte_str) = byte_str {
986 for e in std::ascii::escape_default(c) {
987 self.write_char(e as char)?;
992 } else if let (ConstValue::Slice { data, start, end }, ty::Str) =
995 // The `inspect` here is okay since we checked the bounds, and there are no
996 // relocations (we have an active `str` reference here). We don't use this
997 // result to affect interpreter execution.
998 let slice = data.inspect_with_undef_and_ptr_outside_interpreter(start..end);
999 let s = ::std::str::from_utf8(slice).expect("non utf8 str from miri");
1000 p!(write("{:?}", s));
1010 p!(write("{:?}", ct));
1012 p!(write(": "), print(ty));
1021 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
1022 pub struct FmtPrinter<'a, 'tcx, F>(Box<FmtPrinterData<'a, 'tcx, F>>);
1024 pub struct FmtPrinterData<'a, 'tcx, F> {
1031 used_region_names: FxHashSet<Symbol>,
1032 region_index: usize,
1033 binder_depth: usize,
1035 pub region_highlight_mode: RegionHighlightMode,
1037 pub name_resolver: Option<Box<&'a dyn Fn(ty::sty::TyVid) -> Option<String>>>,
1040 impl<F> Deref for FmtPrinter<'a, 'tcx, F> {
1041 type Target = FmtPrinterData<'a, 'tcx, F>;
1042 fn deref(&self) -> &Self::Target {
1047 impl<F> DerefMut for FmtPrinter<'_, '_, F> {
1048 fn deref_mut(&mut self) -> &mut Self::Target {
1053 impl<F> FmtPrinter<'a, 'tcx, F> {
1054 pub fn new(tcx: TyCtxt<'tcx>, fmt: F, ns: Namespace) -> Self {
1055 FmtPrinter(Box::new(FmtPrinterData {
1059 in_value: ns == Namespace::ValueNS,
1060 used_region_names: Default::default(),
1063 region_highlight_mode: RegionHighlightMode::default(),
1064 name_resolver: None,
1069 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1070 // (but also some things just print a `DefId` generally so maybe we need this?)
1071 fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
1072 match tcx.def_key(def_id).disambiguated_data.data {
1073 DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::ImplTrait => {
1077 DefPathData::ValueNs(..)
1078 | DefPathData::AnonConst
1079 | DefPathData::ClosureExpr
1080 | DefPathData::Ctor => Namespace::ValueNS,
1082 DefPathData::MacroNs(..) => Namespace::MacroNS,
1084 _ => Namespace::TypeNS,
1089 /// Returns a string identifying this `DefId`. This string is
1090 /// suitable for user output.
1091 pub fn def_path_str(self, def_id: DefId) -> String {
1092 self.def_path_str_with_substs(def_id, &[])
1095 pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1096 let ns = guess_def_namespace(self, def_id);
1097 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1098 let mut s = String::new();
1099 let _ = FmtPrinter::new(self, &mut s, ns).print_def_path(def_id, substs);
1104 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, F> {
1105 fn write_str(&mut self, s: &str) -> fmt::Result {
1106 self.fmt.write_str(s)
1110 impl<F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
1111 type Error = fmt::Error;
1116 type DynExistential = Self;
1119 fn tcx(&'a self) -> TyCtxt<'tcx> {
1126 substs: &'tcx [GenericArg<'tcx>],
1127 ) -> Result<Self::Path, Self::Error> {
1128 define_scoped_cx!(self);
1130 if substs.is_empty() {
1131 match self.try_print_visible_def_path(def_id)? {
1132 (cx, true) => return Ok(cx),
1133 (cx, false) => self = cx,
1137 let key = self.tcx.def_key(def_id);
1138 if let DefPathData::Impl = key.disambiguated_data.data {
1139 // Always use types for non-local impls, where types are always
1140 // available, and filename/line-number is mostly uninteresting.
1141 let use_types = !def_id.is_local() || {
1142 // Otherwise, use filename/line-number if forced.
1143 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1148 // If no type info is available, fall back to
1149 // pretty printing some span information. This should
1150 // only occur very early in the compiler pipeline.
1151 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1152 let span = self.tcx.def_span(def_id);
1154 self = self.print_def_path(parent_def_id, &[])?;
1156 // HACK(eddyb) copy of `path_append` to avoid
1157 // constructing a `DisambiguatedDefPathData`.
1158 if !self.empty_path {
1159 write!(self, "::")?;
1161 write!(self, "<impl at {:?}>", span)?;
1162 self.empty_path = false;
1168 self.default_print_def_path(def_id, substs)
1171 fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
1172 self.pretty_print_region(region)
1175 fn print_type(self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1176 self.pretty_print_type(ty)
1179 fn print_dyn_existential(
1181 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1182 ) -> Result<Self::DynExistential, Self::Error> {
1183 self.pretty_print_dyn_existential(predicates)
1186 fn print_const(self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1187 self.pretty_print_const(ct, true)
1190 fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1191 self.empty_path = true;
1192 if cnum == LOCAL_CRATE {
1193 if self.tcx.sess.rust_2018() {
1194 // We add the `crate::` keyword on Rust 2018, only when desired.
1195 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1196 write!(self, "{}", kw::Crate)?;
1197 self.empty_path = false;
1201 write!(self, "{}", self.tcx.crate_name(cnum))?;
1202 self.empty_path = false;
1210 trait_ref: Option<ty::TraitRef<'tcx>>,
1211 ) -> Result<Self::Path, Self::Error> {
1212 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1213 self.empty_path = false;
1217 fn path_append_impl(
1219 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1220 _disambiguated_data: &DisambiguatedDefPathData,
1222 trait_ref: Option<ty::TraitRef<'tcx>>,
1223 ) -> Result<Self::Path, Self::Error> {
1224 self = self.pretty_path_append_impl(
1226 cx = print_prefix(cx)?;
1236 self.empty_path = false;
1242 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1243 disambiguated_data: &DisambiguatedDefPathData,
1244 ) -> Result<Self::Path, Self::Error> {
1245 self = print_prefix(self)?;
1247 // Skip `::{{constructor}}` on tuple/unit structs.
1248 match disambiguated_data.data {
1249 DefPathData::Ctor => return Ok(self),
1253 // FIXME(eddyb) `name` should never be empty, but it
1254 // currently is for `extern { ... }` "foreign modules".
1255 let name = disambiguated_data.data.as_symbol().as_str();
1256 if !name.is_empty() {
1257 if !self.empty_path {
1258 write!(self, "::")?;
1260 if ast::Ident::from_str(&name).is_raw_guess() {
1261 write!(self, "r#")?;
1263 write!(self, "{}", name)?;
1265 // FIXME(eddyb) this will print e.g. `{{closure}}#3`, but it
1266 // might be nicer to use something else, e.g. `{closure#3}`.
1267 let dis = disambiguated_data.disambiguator;
1268 let print_dis = disambiguated_data.data.get_opt_name().is_none()
1269 || dis != 0 && self.tcx.sess.verbose();
1271 write!(self, "#{}", dis)?;
1274 self.empty_path = false;
1280 fn path_generic_args(
1282 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1283 args: &[GenericArg<'tcx>],
1284 ) -> Result<Self::Path, Self::Error> {
1285 self = print_prefix(self)?;
1287 // Don't print `'_` if there's no unerased regions.
1288 let print_regions = args.iter().any(|arg| match arg.unpack() {
1289 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
1292 let args = args.iter().cloned().filter(|arg| match arg.unpack() {
1293 GenericArgKind::Lifetime(_) => print_regions,
1297 if args.clone().next().is_some() {
1299 write!(self, "::")?;
1301 self.generic_delimiters(|cx| cx.comma_sep(args))
1308 impl<F: fmt::Write> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx, F> {
1309 fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> {
1310 self.0.name_resolver.as_ref().and_then(|func| func(id))
1313 fn print_value_path(
1316 substs: &'tcx [GenericArg<'tcx>],
1317 ) -> Result<Self::Path, Self::Error> {
1318 let was_in_value = std::mem::replace(&mut self.in_value, true);
1319 self = self.print_def_path(def_id, substs)?;
1320 self.in_value = was_in_value;
1325 fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
1327 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1329 self.pretty_in_binder(value)
1332 fn generic_delimiters(
1334 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1335 ) -> Result<Self, Self::Error> {
1338 let was_in_value = std::mem::replace(&mut self.in_value, false);
1339 let mut inner = f(self)?;
1340 inner.in_value = was_in_value;
1342 write!(inner, ">")?;
1346 fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool {
1347 let highlight = self.region_highlight_mode;
1348 if highlight.region_highlighted(region).is_some() {
1352 if self.tcx.sess.verbose() {
1356 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1359 ty::ReEarlyBound(ref data) => {
1360 data.name != kw::Invalid && data.name != kw::UnderscoreLifetime
1363 ty::ReLateBound(_, br)
1364 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1365 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1366 if let ty::BrNamed(_, name) = br {
1367 if name != kw::Invalid && name != kw::UnderscoreLifetime {
1372 if let Some((region, _)) = highlight.highlight_bound_region {
1381 ty::ReScope(_) | ty::ReVar(_) if identify_regions => true,
1383 ty::ReVar(_) | ty::ReScope(_) | ty::ReErased => false,
1385 ty::ReStatic | ty::ReEmpty | ty::ReClosureBound(_) => true,
1390 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1391 impl<F: fmt::Write> FmtPrinter<'_, '_, F> {
1392 pub fn pretty_print_region(mut self, region: ty::Region<'_>) -> Result<Self, fmt::Error> {
1393 define_scoped_cx!(self);
1395 // Watch out for region highlights.
1396 let highlight = self.region_highlight_mode;
1397 if let Some(n) = highlight.region_highlighted(region) {
1398 p!(write("'{}", n));
1402 if self.tcx.sess.verbose() {
1403 p!(write("{:?}", region));
1407 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1409 // These printouts are concise. They do not contain all the information
1410 // the user might want to diagnose an error, but there is basically no way
1411 // to fit that into a short string. Hence the recommendation to use
1412 // `explain_region()` or `note_and_explain_region()`.
1414 ty::ReEarlyBound(ref data) => {
1415 if data.name != kw::Invalid {
1416 p!(write("{}", data.name));
1420 ty::ReLateBound(_, br)
1421 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1422 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1423 if let ty::BrNamed(_, name) = br {
1424 if name != kw::Invalid && name != kw::UnderscoreLifetime {
1425 p!(write("{}", name));
1430 if let Some((region, counter)) = highlight.highlight_bound_region {
1432 p!(write("'{}", counter));
1437 ty::ReScope(scope) if identify_regions => {
1439 region::ScopeData::Node => p!(write("'{}s", scope.item_local_id().as_usize())),
1440 region::ScopeData::CallSite => {
1441 p!(write("'{}cs", scope.item_local_id().as_usize()))
1443 region::ScopeData::Arguments => {
1444 p!(write("'{}as", scope.item_local_id().as_usize()))
1446 region::ScopeData::Destruction => {
1447 p!(write("'{}ds", scope.item_local_id().as_usize()))
1449 region::ScopeData::Remainder(first_statement_index) => p!(write(
1451 scope.item_local_id().as_usize(),
1452 first_statement_index.index()
1457 ty::ReVar(region_vid) if identify_regions => {
1458 p!(write("{:?}", region_vid));
1462 ty::ReScope(_) | ty::ReErased => {}
1464 p!(write("'static"));
1468 p!(write("'<empty>"));
1472 // The user should never encounter these in unsubstituted form.
1473 ty::ReClosureBound(vid) => {
1474 p!(write("{:?}", vid));
1485 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1486 // `region_index` and `used_region_names`.
1487 impl<F: fmt::Write> FmtPrinter<'_, 'tcx, F> {
1488 pub fn name_all_regions<T>(
1490 value: &ty::Binder<T>,
1491 ) -> Result<(Self, (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)), fmt::Error>
1493 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1495 fn name_by_region_index(index: usize) -> Symbol {
1497 0 => Symbol::intern("'r"),
1498 1 => Symbol::intern("'s"),
1499 i => Symbol::intern(&format!("'t{}", i - 2)),
1503 // Replace any anonymous late-bound regions with named
1504 // variants, using new unique identifiers, so that we can
1505 // clearly differentiate between named and unnamed regions in
1506 // the output. We'll probably want to tweak this over time to
1507 // decide just how much information to give.
1508 if self.binder_depth == 0 {
1509 self.prepare_late_bound_region_info(value);
1512 let mut empty = true;
1513 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1526 define_scoped_cx!(self);
1528 let mut region_index = self.region_index;
1529 let new_value = self.tcx.replace_late_bound_regions(value, |br| {
1530 let _ = start_or_continue(&mut self, "for<", ", ");
1532 ty::BrNamed(_, name) => {
1533 let _ = write!(self, "{}", name);
1536 ty::BrAnon(_) | ty::BrEnv => {
1538 let name = name_by_region_index(region_index);
1540 if !self.used_region_names.contains(&name) {
1544 let _ = write!(self, "{}", name);
1545 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1548 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
1550 start_or_continue(&mut self, "", "> ")?;
1552 self.binder_depth += 1;
1553 self.region_index = region_index;
1554 Ok((self, new_value))
1557 pub fn pretty_in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, fmt::Error>
1559 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1561 let old_region_index = self.region_index;
1562 let (new, new_value) = self.name_all_regions(value)?;
1563 let mut inner = new_value.0.print(new)?;
1564 inner.region_index = old_region_index;
1565 inner.binder_depth -= 1;
1569 fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
1571 T: TypeFoldable<'tcx>,
1573 struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet<Symbol>);
1574 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> {
1575 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
1577 ty::ReLateBound(_, ty::BrNamed(_, name)) => {
1578 self.0.insert(name);
1582 r.super_visit_with(self)
1586 self.used_region_names.clear();
1587 let mut collector = LateBoundRegionNameCollector(&mut self.used_region_names);
1588 value.visit_with(&mut collector);
1589 self.region_index = 0;
1593 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<T>
1595 T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
1598 type Error = P::Error;
1599 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
1604 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
1606 T: Print<'tcx, P, Output = P, Error = P::Error>,
1607 U: Print<'tcx, P, Output = P, Error = P::Error>,
1610 type Error = P::Error;
1611 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
1612 define_scoped_cx!(cx);
1613 p!(print(self.0), write(": "), print(self.1));
1618 macro_rules! forward_display_to_print {
1620 $(impl fmt::Display for $ty {
1621 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1622 ty::tls::with(|tcx| {
1624 .expect("could not lift for printing")
1625 .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1633 macro_rules! define_print_and_forward_display {
1634 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
1635 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
1637 type Error = fmt::Error;
1638 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
1639 #[allow(unused_mut)]
1641 define_scoped_cx!($cx);
1643 #[allow(unreachable_code)]
1648 forward_display_to_print!($($ty),+);
1652 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
1653 impl fmt::Display for ty::RegionKind {
1654 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1655 ty::tls::with(|tcx| {
1656 self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1662 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
1663 /// the trait path. That is, it will print `Trait<U>` instead of
1664 /// `<T as Trait<U>>`.
1665 #[derive(Copy, Clone, TypeFoldable, Lift)]
1666 pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
1668 impl fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
1669 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1670 fmt::Display::fmt(self, f)
1674 impl ty::TraitRef<'tcx> {
1675 pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
1676 TraitRefPrintOnlyTraitPath(self)
1680 impl ty::Binder<ty::TraitRef<'tcx>> {
1681 pub fn print_only_trait_path(self) -> ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>> {
1682 self.map_bound(|tr| tr.print_only_trait_path())
1686 forward_display_to_print! {
1688 &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1689 &'tcx ty::Const<'tcx>,
1691 // HACK(eddyb) these are exhaustive instead of generic,
1692 // because `for<'tcx>` isn't possible yet.
1693 ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
1694 ty::Binder<ty::TraitRef<'tcx>>,
1695 ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>>,
1696 ty::Binder<ty::FnSig<'tcx>>,
1697 ty::Binder<ty::TraitPredicate<'tcx>>,
1698 ty::Binder<ty::SubtypePredicate<'tcx>>,
1699 ty::Binder<ty::ProjectionPredicate<'tcx>>,
1700 ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1701 ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
1703 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1704 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1707 define_print_and_forward_display! {
1710 &'tcx ty::List<Ty<'tcx>> {
1712 let mut tys = self.iter();
1713 if let Some(&ty) = tys.next() {
1716 p!(write(", "), print(ty));
1722 ty::TypeAndMut<'tcx> {
1723 p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
1726 ty::ExistentialTraitRef<'tcx> {
1727 // Use a type that can't appear in defaults of type parameters.
1728 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1729 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
1730 p!(print(trait_ref.print_only_trait_path()))
1733 ty::ExistentialProjection<'tcx> {
1734 let name = cx.tcx().associated_item(self.item_def_id).ident;
1735 p!(write("{} = ", name), print(self.ty))
1738 ty::ExistentialPredicate<'tcx> {
1740 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
1741 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
1742 ty::ExistentialPredicate::AutoTrait(def_id) => {
1743 p!(print_def_path(def_id, &[]));
1749 p!(write("{}", self.unsafety.prefix_str()));
1751 if self.abi != Abi::Rust {
1752 p!(write("extern {} ", self.abi));
1755 p!(write("fn"), pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
1759 if cx.tcx().sess.verbose() {
1760 p!(write("{:?}", self));
1764 ty::TyVar(_) => p!(write("_")),
1765 ty::IntVar(_) => p!(write("{}", "{integer}")),
1766 ty::FloatVar(_) => p!(write("{}", "{float}")),
1767 ty::FreshTy(v) => p!(write("FreshTy({})", v)),
1768 ty::FreshIntTy(v) => p!(write("FreshIntTy({})", v)),
1769 ty::FreshFloatTy(v) => p!(write("FreshFloatTy({})", v))
1773 ty::TraitRef<'tcx> {
1774 p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
1777 TraitRefPrintOnlyTraitPath<'tcx> {
1778 p!(print_def_path(self.0.def_id, self.0.substs));
1782 p!(write("{}", self.name))
1786 p!(write("{}", self.name))
1789 ty::SubtypePredicate<'tcx> {
1790 p!(print(self.a), write(" <: "), print(self.b))
1793 ty::TraitPredicate<'tcx> {
1794 p!(print(self.trait_ref.self_ty()), write(": "),
1795 print(self.trait_ref.print_only_trait_path()))
1798 ty::ProjectionPredicate<'tcx> {
1799 p!(print(self.projection_ty), write(" == "), print(self.ty))
1802 ty::ProjectionTy<'tcx> {
1803 p!(print_def_path(self.item_def_id, self.substs));
1808 ty::ClosureKind::Fn => p!(write("Fn")),
1809 ty::ClosureKind::FnMut => p!(write("FnMut")),
1810 ty::ClosureKind::FnOnce => p!(write("FnOnce")),
1814 ty::Predicate<'tcx> {
1816 ty::Predicate::Trait(ref data, constness) => {
1817 if let ast::Constness::Const = constness {
1818 p!(write("const "));
1822 ty::Predicate::Subtype(ref predicate) => p!(print(predicate)),
1823 ty::Predicate::RegionOutlives(ref predicate) => p!(print(predicate)),
1824 ty::Predicate::TypeOutlives(ref predicate) => p!(print(predicate)),
1825 ty::Predicate::Projection(ref predicate) => p!(print(predicate)),
1826 ty::Predicate::WellFormed(ty) => p!(print(ty), write(" well-formed")),
1827 ty::Predicate::ObjectSafe(trait_def_id) => {
1828 p!(write("the trait `"),
1829 print_def_path(trait_def_id, &[]),
1830 write("` is object-safe"))
1832 ty::Predicate::ClosureKind(closure_def_id, _closure_substs, kind) => {
1833 p!(write("the closure `"),
1834 print_value_path(closure_def_id, &[]),
1835 write("` implements the trait `{}`", kind))
1837 ty::Predicate::ConstEvaluatable(def_id, substs) => {
1838 p!(write("the constant `"),
1839 print_value_path(def_id, substs),
1840 write("` can be evaluated"))
1846 match self.unpack() {
1847 GenericArgKind::Lifetime(lt) => p!(print(lt)),
1848 GenericArgKind::Type(ty) => p!(print(ty)),
1849 GenericArgKind::Const(ct) => p!(print(ct)),