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_attr::{SignedInt, UnsignedInt};
15 use rustc_span::symbol::{kw, Symbol};
16 use rustc_target::spec::abi::Abi;
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.replace(true);
74 /// Force us to name impls with just the filename/line number. We
75 /// normally try to use types. But at some points, notably while printing
76 /// cycle errors, this can result in extra or suboptimal error output,
77 /// so this variable disables that check.
78 pub fn with_forced_impl_filename_line<F: FnOnce() -> R, R>(f: F) -> R {
79 FORCE_IMPL_FILENAME_LINE.with(|force| {
80 let old = force.replace(true);
87 /// Adds the `crate::` prefix to paths where appropriate.
88 pub fn with_crate_prefix<F: FnOnce() -> R, R>(f: F) -> R {
89 SHOULD_PREFIX_WITH_CRATE.with(|flag| {
90 let old = flag.replace(true);
97 /// The "region highlights" are used to control region printing during
98 /// specific error messages. When a "region highlight" is enabled, it
99 /// gives an alternate way to print specific regions. For now, we
100 /// always print those regions using a number, so something like "`'0`".
102 /// Regions not selected by the region highlight mode are presently
104 #[derive(Copy, Clone, Default)]
105 pub struct RegionHighlightMode {
106 /// If enabled, when we see the selected region, use "`'N`"
107 /// instead of the ordinary behavior.
108 highlight_regions: [Option<(ty::RegionKind, usize)>; 3],
110 /// If enabled, when printing a "free region" that originated from
111 /// the given `ty::BoundRegion`, print it as "`'1`". Free regions that would ordinarily
112 /// have names print as normal.
114 /// This is used when you have a signature like `fn foo(x: &u32,
115 /// y: &'a u32)` and we want to give a name to the region of the
117 highlight_bound_region: Option<(ty::BoundRegion, usize)>,
120 impl RegionHighlightMode {
121 /// If `region` and `number` are both `Some`, invokes
122 /// `highlighting_region`.
123 pub fn maybe_highlighting_region(
125 region: Option<ty::Region<'_>>,
126 number: Option<usize>,
128 if let Some(k) = region {
129 if let Some(n) = number {
130 self.highlighting_region(k, n);
135 /// Highlights the region inference variable `vid` as `'N`.
136 pub fn highlighting_region(&mut self, region: ty::Region<'_>, number: usize) {
137 let num_slots = self.highlight_regions.len();
138 let first_avail_slot =
139 self.highlight_regions.iter_mut().find(|s| s.is_none()).unwrap_or_else(|| {
140 bug!("can only highlight {} placeholders at a time", num_slots,)
142 *first_avail_slot = Some((*region, number));
145 /// Convenience wrapper for `highlighting_region`.
146 pub fn highlighting_region_vid(&mut self, vid: ty::RegionVid, number: usize) {
147 self.highlighting_region(&ty::ReVar(vid), number)
150 /// Returns `Some(n)` with the number to use for the given region, if any.
151 fn region_highlighted(&self, region: ty::Region<'_>) -> Option<usize> {
152 self.highlight_regions
154 .filter_map(|h| match h {
155 Some((r, n)) if r == region => Some(*n),
161 /// Highlight the given bound region.
162 /// We can only highlight one bound region at a time. See
163 /// the field `highlight_bound_region` for more detailed notes.
164 pub fn highlighting_bound_region(&mut self, br: ty::BoundRegion, number: usize) {
165 assert!(self.highlight_bound_region.is_none());
166 self.highlight_bound_region = Some((br, number));
170 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
171 pub trait PrettyPrinter<'tcx>:
178 DynExistential = Self,
182 /// Like `print_def_path` but for value paths.
186 substs: &'tcx [GenericArg<'tcx>],
187 ) -> Result<Self::Path, Self::Error> {
188 self.print_def_path(def_id, substs)
191 fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
193 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
195 value.skip_binder().print(self)
198 /// Prints comma-separated elements.
199 fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
201 T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
203 if let Some(first) = elems.next() {
204 self = first.print(self)?;
206 self.write_str(", ")?;
207 self = elem.print(self)?;
213 /// Prints `<...>` around what `f` prints.
214 fn generic_delimiters(
216 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
217 ) -> Result<Self, Self::Error>;
219 /// Returns `true` if the region should be printed in
220 /// optional positions, e.g., `&'a T` or `dyn Tr + 'b`.
221 /// This is typically the case for all non-`'_` regions.
222 fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool;
224 // Defaults (should not be overriden):
226 /// If possible, this returns a global path resolving to `def_id` that is visible
227 /// from at least one local module, and returns `true`. If the crate defining `def_id` is
228 /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
229 fn try_print_visible_def_path(self, def_id: DefId) -> Result<(Self, bool), Self::Error> {
230 let mut callers = Vec::new();
231 self.try_print_visible_def_path_recur(def_id, &mut callers)
234 /// Does the work of `try_print_visible_def_path`, building the
235 /// full definition path recursively before attempting to
236 /// post-process it into the valid and visible version that
237 /// accounts for re-exports.
239 /// This method should only be callled by itself or
240 /// `try_print_visible_def_path`.
242 /// `callers` is a chain of visible_parent's leading to `def_id`,
243 /// to support cycle detection during recursion.
244 fn try_print_visible_def_path_recur(
247 callers: &mut Vec<DefId>,
248 ) -> Result<(Self, bool), Self::Error> {
249 define_scoped_cx!(self);
251 debug!("try_print_visible_def_path: def_id={:?}", def_id);
253 // If `def_id` is a direct or injected extern crate, return the
254 // path to the crate followed by the path to the item within the crate.
255 if def_id.index == CRATE_DEF_INDEX {
256 let cnum = def_id.krate;
258 if cnum == LOCAL_CRATE {
259 return Ok((self.path_crate(cnum)?, true));
262 // In local mode, when we encounter a crate other than
263 // LOCAL_CRATE, execution proceeds in one of two ways:
265 // 1. For a direct dependency, where user added an
266 // `extern crate` manually, we put the `extern
267 // crate` as the parent. So you wind up with
268 // something relative to the current crate.
269 // 2. For an extern inferred from a path or an indirect crate,
270 // where there is no explicit `extern crate`, we just prepend
272 match self.tcx().extern_crate(def_id) {
274 src: ExternCrateSource::Extern(def_id),
275 dependency_of: LOCAL_CRATE,
279 debug!("try_print_visible_def_path: def_id={:?}", def_id);
281 if !span.is_dummy() {
282 self.print_def_path(def_id, &[])?
284 self.path_crate(cnum)?
290 return Ok((self.path_crate(cnum)?, true));
296 if def_id.is_local() {
297 return Ok((self, false));
300 let visible_parent_map = self.tcx().visible_parent_map(LOCAL_CRATE);
302 let mut cur_def_key = self.tcx().def_key(def_id);
303 debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
305 // For a constructor, we want the name of its parent rather than <unnamed>.
306 match cur_def_key.disambiguated_data.data {
307 DefPathData::Ctor => {
312 .expect("`DefPathData::Ctor` / `VariantData` missing a parent"),
315 cur_def_key = self.tcx().def_key(parent);
320 let visible_parent = match visible_parent_map.get(&def_id).cloned() {
321 Some(parent) => parent,
322 None => return Ok((self, false)),
324 if callers.contains(&visible_parent) {
325 return Ok((self, false));
327 callers.push(visible_parent);
328 // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
329 // knowing ahead of time whether the entire path will succeed or not.
330 // To support printers that do not implement `PrettyPrinter`, a `Vec` or
331 // linked list on the stack would need to be built, before any printing.
332 match self.try_print_visible_def_path_recur(visible_parent, callers)? {
333 (cx, false) => return Ok((cx, false)),
334 (cx, true) => self = cx,
337 let actual_parent = self.tcx().parent(def_id);
339 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
340 visible_parent, actual_parent,
343 let mut data = cur_def_key.disambiguated_data.data;
345 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
346 data, visible_parent, actual_parent,
350 // In order to output a path that could actually be imported (valid and visible),
351 // we need to handle re-exports correctly.
353 // For example, take `std::os::unix::process::CommandExt`, this trait is actually
354 // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
356 // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is
357 // private so the "true" path to `CommandExt` isn't accessible.
359 // In this case, the `visible_parent_map` will look something like this:
361 // (child) -> (parent)
362 // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
363 // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
364 // `std::sys::unix::ext` -> `std::os`
366 // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
369 // When printing the path to `CommandExt` and looking at the `cur_def_key` that
370 // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
371 // to the parent - resulting in a mangled path like
372 // `std::os::ext::process::CommandExt`.
374 // Instead, we must detect that there was a re-export and instead print `unix`
375 // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
376 // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
377 // the visible parent (`std::os`). If these do not match, then we iterate over
378 // the children of the visible parent (as was done when computing
379 // `visible_parent_map`), looking for the specific child we currently have and then
380 // have access to the re-exported name.
381 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
384 .item_children(visible_parent)
386 .find(|child| child.res.def_id() == def_id)
387 .map(|child| child.ident.name);
388 if let Some(reexport) = reexport {
392 // Re-exported `extern crate` (#43189).
393 DefPathData::CrateRoot => {
394 data = DefPathData::TypeNs(self.tcx().original_crate_name(def_id.krate));
398 debug!("try_print_visible_def_path: data={:?}", data);
400 Ok((self.path_append(Ok, &DisambiguatedDefPathData { data, disambiguator: 0 })?, true))
403 fn pretty_path_qualified(
406 trait_ref: Option<ty::TraitRef<'tcx>>,
407 ) -> Result<Self::Path, Self::Error> {
408 if trait_ref.is_none() {
409 // Inherent impls. Try to print `Foo::bar` for an inherent
410 // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
411 // anything other than a simple path.
421 return self_ty.print(self);
428 self.generic_delimiters(|mut cx| {
429 define_scoped_cx!(cx);
432 if let Some(trait_ref) = trait_ref {
433 p!(write(" as "), print(trait_ref.print_only_trait_path()));
439 fn pretty_path_append_impl(
441 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
443 trait_ref: Option<ty::TraitRef<'tcx>>,
444 ) -> Result<Self::Path, Self::Error> {
445 self = print_prefix(self)?;
447 self.generic_delimiters(|mut cx| {
448 define_scoped_cx!(cx);
451 if let Some(trait_ref) = trait_ref {
452 p!(print(trait_ref.print_only_trait_path()), write(" for "));
460 fn pretty_print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
461 define_scoped_cx!(self);
464 ty::Bool => p!(write("bool")),
465 ty::Char => p!(write("char")),
466 ty::Int(t) => p!(write("{}", t.name_str())),
467 ty::Uint(t) => p!(write("{}", t.name_str())),
468 ty::Float(t) => p!(write("{}", t.name_str())),
469 ty::RawPtr(ref tm) => {
473 hir::Mutability::Mut => "mut",
474 hir::Mutability::Not => "const",
479 ty::Ref(r, ty, mutbl) => {
481 if self.region_should_not_be_omitted(r) {
482 p!(print(r), write(" "));
484 p!(print(ty::TypeAndMut { ty, mutbl }))
486 ty::Never => p!(write("!")),
487 ty::Tuple(ref tys) => {
489 let mut tys = tys.iter();
490 if let Some(&ty) = tys.next() {
491 p!(print(ty), write(","));
492 if let Some(&ty) = tys.next() {
493 p!(write(" "), print(ty));
495 p!(write(", "), print(ty));
501 ty::FnDef(def_id, substs) => {
502 let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs);
503 p!(print(sig), write(" {{"), print_value_path(def_id, substs), write("}}"));
505 ty::FnPtr(ref bare_fn) => p!(print(bare_fn)),
506 ty::Infer(infer_ty) => {
507 if let ty::TyVar(ty_vid) = infer_ty {
508 if let Some(name) = self.infer_ty_name(ty_vid) {
509 p!(write("{}", name))
511 p!(write("{}", infer_ty))
514 p!(write("{}", infer_ty))
517 ty::Error => p!(write("[type error]")),
518 ty::Param(ref param_ty) => p!(write("{}", param_ty)),
519 ty::Bound(debruijn, bound_ty) => match bound_ty.kind {
520 ty::BoundTyKind::Anon => {
521 if debruijn == ty::INNERMOST {
522 p!(write("^{}", bound_ty.var.index()))
524 p!(write("^{}_{}", debruijn.index(), bound_ty.var.index()))
528 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
530 ty::Adt(def, substs) => {
531 p!(print_def_path(def.did, substs));
533 ty::Dynamic(data, r) => {
534 let print_r = self.region_should_not_be_omitted(r);
538 p!(write("dyn "), print(data));
540 p!(write(" + "), print(r), write(")"));
543 ty::Foreign(def_id) => {
544 p!(print_def_path(def_id, &[]));
546 ty::Projection(ref data) => p!(print(data)),
547 ty::UnnormalizedProjection(ref data) => {
548 p!(write("Unnormalized("), print(data), write(")"))
550 ty::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
551 ty::Opaque(def_id, substs) => {
552 // FIXME(eddyb) print this with `print_def_path`.
553 // We use verbose printing in 'NO_QUERIES' mode, to
554 // avoid needing to call `predicates_of`. This should
555 // only affect certain debug messages (e.g. messages printed
556 // from `rustc::ty` during the computation of `tcx.predicates_of`),
557 // and should have no effect on any compiler output.
558 if self.tcx().sess.verbose() || NO_QUERIES.with(|q| q.get()) {
559 p!(write("Opaque({:?}, {:?})", def_id, substs));
563 return Ok(with_no_queries(|| {
564 let def_key = self.tcx().def_key(def_id);
565 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
566 p!(write("{}", name));
567 let mut substs = substs.iter();
568 // FIXME(eddyb) print this with `print_def_path`.
569 if let Some(first) = substs.next() {
572 for subst in substs {
573 p!(write(", "), print(subst));
579 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
580 // by looking up the projections associated with the def_id.
581 let bounds = self.tcx().predicates_of(def_id).instantiate(self.tcx(), substs);
583 let mut first = true;
584 let mut is_sized = false;
586 for predicate in bounds.predicates {
587 if let Some(trait_ref) = predicate.to_opt_poly_trait_ref() {
588 // Don't print +Sized, but rather +?Sized if absent.
589 if Some(trait_ref.def_id()) == self.tcx().lang_items().sized_trait() {
595 write("{}", if first { " " } else { "+" }),
596 print(trait_ref.print_only_trait_path())
602 p!(write("{}?Sized", if first { " " } else { "+" }));
609 ty::Str => p!(write("str")),
610 ty::Generator(did, substs, movability) => {
611 let upvar_tys = substs.as_generator().upvar_tys(did, self.tcx());
612 let witness = substs.as_generator().witness(did, self.tcx());
614 hir::Movability::Movable => p!(write("[generator")),
615 hir::Movability::Static => p!(write("[static generator")),
618 // FIXME(eddyb) should use `def_span`.
619 if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
620 p!(write("@{:?}", self.tcx().hir().span(hir_id)));
622 for (&var_id, upvar_ty) in
623 self.tcx().upvars(did).as_ref().iter().flat_map(|v| v.keys()).zip(upvar_tys)
625 p!(write("{}{}:", sep, self.tcx().hir().name(var_id)), print(upvar_ty));
629 // Cross-crate closure types should only be
630 // visible in codegen bug reports, I imagine.
631 p!(write("@{:?}", did));
633 for (index, upvar_ty) in upvar_tys.enumerate() {
634 p!(write("{}{}:", sep, index), print(upvar_ty));
639 p!(write(" "), print(witness), write("]"))
641 ty::GeneratorWitness(types) => {
642 p!(in_binder(&types));
644 ty::Closure(did, substs) => {
645 let upvar_tys = substs.as_closure().upvar_tys(did, self.tcx());
646 p!(write("[closure"));
648 // FIXME(eddyb) should use `def_span`.
649 if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
650 if self.tcx().sess.opts.debugging_opts.span_free_formats {
651 p!(write("@"), print_def_path(did, substs));
653 p!(write("@{:?}", self.tcx().hir().span(hir_id)));
656 for (&var_id, upvar_ty) in
657 self.tcx().upvars(did).as_ref().iter().flat_map(|v| v.keys()).zip(upvar_tys)
659 p!(write("{}{}:", sep, self.tcx().hir().name(var_id)), print(upvar_ty));
663 // Cross-crate closure types should only be
664 // visible in codegen bug reports, I imagine.
665 p!(write("@{:?}", did));
667 for (index, upvar_ty) in upvar_tys.enumerate() {
668 p!(write("{}{}:", sep, index), print(upvar_ty));
673 if self.tcx().sess.verbose() {
675 " closure_kind_ty={:?} closure_sig_ty={:?}",
676 substs.as_closure().kind_ty(did, self.tcx()),
677 substs.as_closure().sig_ty(did, self.tcx())
683 ty::Array(ty, sz) => {
684 p!(write("["), print(ty), write("; "));
685 if self.tcx().sess.verbose() {
686 p!(write("{:?}", sz));
687 } else if let ty::ConstKind::Unevaluated(..) = sz.val {
688 // do not try to evalute unevaluated constants. If we are const evaluating an
689 // array length anon const, rustc will (with debug assertions) print the
690 // constant's path. Which will end up here again.
692 } else if let Some(n) = sz.try_eval_usize(self.tcx(), ty::ParamEnv::empty()) {
699 ty::Slice(ty) => p!(write("["), print(ty), write("]")),
705 fn infer_ty_name(&self, _: ty::TyVid) -> Option<String> {
709 fn pretty_print_dyn_existential(
711 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
712 ) -> Result<Self::DynExistential, Self::Error> {
713 define_scoped_cx!(self);
715 // Generate the main trait ref, including associated types.
716 let mut first = true;
718 if let Some(principal) = predicates.principal() {
719 p!(print_def_path(principal.def_id, &[]));
721 let mut resugared = false;
723 // Special-case `Fn(...) -> ...` and resugar it.
724 let fn_trait_kind = self.tcx().fn_trait_kind_from_lang_item(principal.def_id);
725 if !self.tcx().sess.verbose() && fn_trait_kind.is_some() {
726 if let ty::Tuple(ref args) = principal.substs.type_at(0).kind {
727 let mut projections = predicates.projection_bounds();
728 if let (Some(proj), None) = (projections.next(), projections.next()) {
729 let tys: Vec<_> = args.iter().map(|k| k.expect_ty()).collect();
730 p!(pretty_fn_sig(&tys, false, proj.ty));
736 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
737 // in order to place the projections inside the `<...>`.
739 // Use a type that can't appear in defaults of type parameters.
740 let dummy_self = self.tcx().mk_ty_infer(ty::FreshTy(0));
741 let principal = principal.with_self_ty(self.tcx(), dummy_self);
743 let args = self.generic_args_to_print(
744 self.tcx().generics_of(principal.def_id),
748 // Don't print `'_` if there's no unerased regions.
749 let print_regions = args.iter().any(|arg| match arg.unpack() {
750 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
753 let mut args = args.iter().cloned().filter(|arg| match arg.unpack() {
754 GenericArgKind::Lifetime(_) => print_regions,
757 let mut projections = predicates.projection_bounds();
759 let arg0 = args.next();
760 let projection0 = projections.next();
761 if arg0.is_some() || projection0.is_some() {
762 let args = arg0.into_iter().chain(args);
763 let projections = projection0.into_iter().chain(projections);
765 p!(generic_delimiters(|mut cx| {
766 cx = cx.comma_sep(args)?;
767 if arg0.is_some() && projection0.is_some() {
770 cx.comma_sep(projections)
778 // FIXME(eddyb) avoid printing twice (needed to ensure
779 // that the auto traits are sorted *and* printed via cx).
780 let mut auto_traits: Vec<_> =
781 predicates.auto_traits().map(|did| (self.tcx().def_path_str(did), did)).collect();
783 // The auto traits come ordered by `DefPathHash`. While
784 // `DefPathHash` is *stable* in the sense that it depends on
785 // neither the host nor the phase of the moon, it depends
786 // "pseudorandomly" on the compiler version and the target.
788 // To avoid that causing instabilities in compiletest
789 // output, sort the auto-traits alphabetically.
792 for (_, def_id) in auto_traits {
798 p!(print_def_path(def_id, &[]));
809 ) -> Result<Self, Self::Error> {
810 define_scoped_cx!(self);
813 let mut inputs = inputs.iter();
814 if let Some(&ty) = inputs.next() {
817 p!(write(", "), print(ty));
824 if !output.is_unit() {
825 p!(write(" -> "), print(output));
831 fn pretty_print_const(
833 ct: &'tcx ty::Const<'tcx>,
835 ) -> Result<Self::Const, Self::Error> {
836 define_scoped_cx!(self);
838 if self.tcx().sess.verbose() {
839 p!(write("Const({:?}: {:?})", ct.val, ct.ty));
843 macro_rules! print_underscore {
847 p!(write(": "), print(ct.ty));
852 match (ct.val, &ct.ty.kind) {
853 (_, ty::FnDef(did, substs)) => p!(print_value_path(*did, substs)),
854 (ty::ConstKind::Unevaluated(did, substs, promoted), _) => {
855 if let Some(promoted) = promoted {
856 p!(print_value_path(did, substs));
857 p!(write("::{:?}", promoted));
859 match self.tcx().def_kind(did) {
860 Some(DefKind::Static)
861 | Some(DefKind::Const)
862 | Some(DefKind::AssocConst) => p!(print_value_path(did, substs)),
865 let span = self.tcx().def_span(did);
866 if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span)
868 p!(write("{}", snip))
879 (ty::ConstKind::Infer(..), _) => print_underscore!(),
880 (ty::ConstKind::Param(ParamConst { name, .. }), _) => p!(write("{}", name)),
881 (ty::ConstKind::Value(value), _) => {
882 return self.pretty_print_const_value(value, ct.ty, print_ty);
887 p!(write("{:?}", ct.val));
889 p!(write(": "), print(ct.ty));
896 fn pretty_print_const_value(
898 ct: ConstValue<'tcx>,
901 ) -> Result<Self::Const, Self::Error> {
902 define_scoped_cx!(self);
904 if self.tcx().sess.verbose() {
905 p!(write("ConstValue({:?}: {:?})", ct, ty));
909 let u8 = self.tcx().types.u8;
911 match (ct, &ty.kind) {
912 (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Bool) => {
913 p!(write("{}", if data == 0 { "false" } else { "true" }))
915 (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Float(ast::FloatTy::F32)) => {
916 p!(write("{}f32", Single::from_bits(data)))
918 (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Float(ast::FloatTy::F64)) => {
919 p!(write("{}f64", Double::from_bits(data)))
921 (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Uint(ui)) => {
922 let bit_size = Integer::from_attr(&self.tcx(), UnsignedInt(*ui)).size();
923 let max = truncate(u128::max_value(), bit_size);
925 let ui_str = ui.name_str();
927 p!(write("std::{}::MAX", ui_str))
929 p!(write("{}{}", data, ui_str))
932 (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Int(i)) => {
933 let bit_size = Integer::from_attr(&self.tcx(), SignedInt(*i)).size().bits() as u128;
934 let min = 1u128 << (bit_size - 1);
937 let ty = self.tcx().lift(&ty).unwrap();
938 let size = self.tcx().layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size;
939 let i_str = i.name_str();
941 d if d == min => p!(write("std::{}::MIN", i_str)),
942 d if d == max => p!(write("std::{}::MAX", i_str)),
943 _ => p!(write("{}{}", sign_extend(data, size) as i128, i_str)),
946 (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Char) => {
947 p!(write("{:?}", ::std::char::from_u32(data as u32).unwrap()))
949 (ConstValue::Scalar(_), ty::RawPtr(_)) => p!(write("{{pointer}}")),
950 (ConstValue::Scalar(Scalar::Ptr(ptr)), ty::FnPtr(_)) => {
952 let alloc_map = self.tcx().alloc_map.lock();
953 alloc_map.unwrap_fn(ptr.alloc_id)
955 p!(print_value_path(instance.def_id(), instance.substs));
958 let printed = if let ty::Ref(_, ref_ty, _) = ty.kind {
959 let byte_str = match (ct, &ref_ty.kind) {
960 (ConstValue::Scalar(Scalar::Ptr(ptr)), ty::Array(t, n)) if *t == u8 => {
961 let n = n.eval_usize(self.tcx(), ty::ParamEnv::empty());
966 .unwrap_memory(ptr.alloc_id)
967 .get_bytes(&self.tcx(), ptr, Size::from_bytes(n))
971 (ConstValue::Slice { data, start, end }, ty::Slice(t)) if *t == u8 => {
972 // The `inspect` here is okay since we checked the bounds, and there are
973 // no relocations (we have an active slice reference here). We don't use
974 // this result to affect interpreter execution.
975 Some(data.inspect_with_undef_and_ptr_outside_interpreter(start..end))
980 if let Some(byte_str) = byte_str {
983 for e in std::ascii::escape_default(c) {
984 self.write_char(e as char)?;
989 } else if let (ConstValue::Slice { data, start, end }, ty::Str) =
992 // The `inspect` here is okay since we checked the bounds, and there are no
993 // relocations (we have an active `str` reference here). We don't use this
994 // result to affect interpreter execution.
995 let slice = data.inspect_with_undef_and_ptr_outside_interpreter(start..end);
996 let s = ::std::str::from_utf8(slice).expect("non utf8 str from miri");
997 p!(write("{:?}", s));
1007 p!(write("{:?}", ct));
1009 p!(write(": "), print(ty));
1018 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
1019 pub struct FmtPrinter<'a, 'tcx, F>(Box<FmtPrinterData<'a, 'tcx, F>>);
1021 pub struct FmtPrinterData<'a, 'tcx, F> {
1028 used_region_names: FxHashSet<Symbol>,
1029 region_index: usize,
1030 binder_depth: usize,
1032 pub region_highlight_mode: RegionHighlightMode,
1034 pub name_resolver: Option<Box<&'a dyn Fn(ty::sty::TyVid) -> Option<String>>>,
1037 impl<F> Deref for FmtPrinter<'a, 'tcx, F> {
1038 type Target = FmtPrinterData<'a, 'tcx, F>;
1039 fn deref(&self) -> &Self::Target {
1044 impl<F> DerefMut for FmtPrinter<'_, '_, F> {
1045 fn deref_mut(&mut self) -> &mut Self::Target {
1050 impl<F> FmtPrinter<'a, 'tcx, F> {
1051 pub fn new(tcx: TyCtxt<'tcx>, fmt: F, ns: Namespace) -> Self {
1052 FmtPrinter(Box::new(FmtPrinterData {
1056 in_value: ns == Namespace::ValueNS,
1057 used_region_names: Default::default(),
1060 region_highlight_mode: RegionHighlightMode::default(),
1061 name_resolver: None,
1066 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1067 // (but also some things just print a `DefId` generally so maybe we need this?)
1068 fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
1069 match tcx.def_key(def_id).disambiguated_data.data {
1070 DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::ImplTrait => {
1074 DefPathData::ValueNs(..)
1075 | DefPathData::AnonConst
1076 | DefPathData::ClosureExpr
1077 | DefPathData::Ctor => Namespace::ValueNS,
1079 DefPathData::MacroNs(..) => Namespace::MacroNS,
1081 _ => Namespace::TypeNS,
1086 /// Returns a string identifying this `DefId`. This string is
1087 /// suitable for user output.
1088 pub fn def_path_str(self, def_id: DefId) -> String {
1089 self.def_path_str_with_substs(def_id, &[])
1092 pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1093 let ns = guess_def_namespace(self, def_id);
1094 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1095 let mut s = String::new();
1096 let _ = FmtPrinter::new(self, &mut s, ns).print_def_path(def_id, substs);
1101 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, F> {
1102 fn write_str(&mut self, s: &str) -> fmt::Result {
1103 self.fmt.write_str(s)
1107 impl<F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
1108 type Error = fmt::Error;
1113 type DynExistential = Self;
1116 fn tcx(&'a self) -> TyCtxt<'tcx> {
1123 substs: &'tcx [GenericArg<'tcx>],
1124 ) -> Result<Self::Path, Self::Error> {
1125 define_scoped_cx!(self);
1127 if substs.is_empty() {
1128 match self.try_print_visible_def_path(def_id)? {
1129 (cx, true) => return Ok(cx),
1130 (cx, false) => self = cx,
1134 let key = self.tcx.def_key(def_id);
1135 if let DefPathData::Impl = key.disambiguated_data.data {
1136 // Always use types for non-local impls, where types are always
1137 // available, and filename/line-number is mostly uninteresting.
1138 let use_types = !def_id.is_local() || {
1139 // Otherwise, use filename/line-number if forced.
1140 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1145 // If no type info is available, fall back to
1146 // pretty printing some span information. This should
1147 // only occur very early in the compiler pipeline.
1148 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1149 let span = self.tcx.def_span(def_id);
1151 self = self.print_def_path(parent_def_id, &[])?;
1153 // HACK(eddyb) copy of `path_append` to avoid
1154 // constructing a `DisambiguatedDefPathData`.
1155 if !self.empty_path {
1156 write!(self, "::")?;
1158 write!(self, "<impl at {:?}>", span)?;
1159 self.empty_path = false;
1165 self.default_print_def_path(def_id, substs)
1168 fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
1169 self.pretty_print_region(region)
1172 fn print_type(self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1173 self.pretty_print_type(ty)
1176 fn print_dyn_existential(
1178 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1179 ) -> Result<Self::DynExistential, Self::Error> {
1180 self.pretty_print_dyn_existential(predicates)
1183 fn print_const(self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1184 self.pretty_print_const(ct, true)
1187 fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1188 self.empty_path = true;
1189 if cnum == LOCAL_CRATE {
1190 if self.tcx.sess.rust_2018() {
1191 // We add the `crate::` keyword on Rust 2018, only when desired.
1192 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1193 write!(self, "{}", kw::Crate)?;
1194 self.empty_path = false;
1198 write!(self, "{}", self.tcx.crate_name(cnum))?;
1199 self.empty_path = false;
1207 trait_ref: Option<ty::TraitRef<'tcx>>,
1208 ) -> Result<Self::Path, Self::Error> {
1209 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1210 self.empty_path = false;
1214 fn path_append_impl(
1216 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1217 _disambiguated_data: &DisambiguatedDefPathData,
1219 trait_ref: Option<ty::TraitRef<'tcx>>,
1220 ) -> Result<Self::Path, Self::Error> {
1221 self = self.pretty_path_append_impl(
1223 cx = print_prefix(cx)?;
1233 self.empty_path = false;
1239 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1240 disambiguated_data: &DisambiguatedDefPathData,
1241 ) -> Result<Self::Path, Self::Error> {
1242 self = print_prefix(self)?;
1244 // Skip `::{{constructor}}` on tuple/unit structs.
1245 match disambiguated_data.data {
1246 DefPathData::Ctor => return Ok(self),
1250 // FIXME(eddyb) `name` should never be empty, but it
1251 // currently is for `extern { ... }` "foreign modules".
1252 let name = disambiguated_data.data.as_symbol().as_str();
1253 if !name.is_empty() {
1254 if !self.empty_path {
1255 write!(self, "::")?;
1257 if ast::Ident::from_str(&name).is_raw_guess() {
1258 write!(self, "r#")?;
1260 write!(self, "{}", name)?;
1262 // FIXME(eddyb) this will print e.g. `{{closure}}#3`, but it
1263 // might be nicer to use something else, e.g. `{closure#3}`.
1264 let dis = disambiguated_data.disambiguator;
1265 let print_dis = disambiguated_data.data.get_opt_name().is_none()
1266 || dis != 0 && self.tcx.sess.verbose();
1268 write!(self, "#{}", dis)?;
1271 self.empty_path = false;
1277 fn path_generic_args(
1279 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1280 args: &[GenericArg<'tcx>],
1281 ) -> Result<Self::Path, Self::Error> {
1282 self = print_prefix(self)?;
1284 // Don't print `'_` if there's no unerased regions.
1285 let print_regions = args.iter().any(|arg| match arg.unpack() {
1286 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
1289 let args = args.iter().cloned().filter(|arg| match arg.unpack() {
1290 GenericArgKind::Lifetime(_) => print_regions,
1294 if args.clone().next().is_some() {
1296 write!(self, "::")?;
1298 self.generic_delimiters(|cx| cx.comma_sep(args))
1305 impl<F: fmt::Write> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx, F> {
1306 fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> {
1307 self.0.name_resolver.as_ref().and_then(|func| func(id))
1310 fn print_value_path(
1313 substs: &'tcx [GenericArg<'tcx>],
1314 ) -> Result<Self::Path, Self::Error> {
1315 let was_in_value = std::mem::replace(&mut self.in_value, true);
1316 self = self.print_def_path(def_id, substs)?;
1317 self.in_value = was_in_value;
1322 fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
1324 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1326 self.pretty_in_binder(value)
1329 fn generic_delimiters(
1331 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1332 ) -> Result<Self, Self::Error> {
1335 let was_in_value = std::mem::replace(&mut self.in_value, false);
1336 let mut inner = f(self)?;
1337 inner.in_value = was_in_value;
1339 write!(inner, ">")?;
1343 fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool {
1344 let highlight = self.region_highlight_mode;
1345 if highlight.region_highlighted(region).is_some() {
1349 if self.tcx.sess.verbose() {
1353 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1356 ty::ReEarlyBound(ref data) => {
1357 data.name != kw::Invalid && data.name != kw::UnderscoreLifetime
1360 ty::ReLateBound(_, br)
1361 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1362 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1363 if let ty::BrNamed(_, name) = br {
1364 if name != kw::Invalid && name != kw::UnderscoreLifetime {
1369 if let Some((region, _)) = highlight.highlight_bound_region {
1378 ty::ReScope(_) | ty::ReVar(_) if identify_regions => true,
1380 ty::ReVar(_) | ty::ReScope(_) | ty::ReErased => false,
1382 ty::ReStatic | ty::ReEmpty(_) | ty::ReClosureBound(_) => true,
1387 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1388 impl<F: fmt::Write> FmtPrinter<'_, '_, F> {
1389 pub fn pretty_print_region(mut self, region: ty::Region<'_>) -> Result<Self, fmt::Error> {
1390 define_scoped_cx!(self);
1392 // Watch out for region highlights.
1393 let highlight = self.region_highlight_mode;
1394 if let Some(n) = highlight.region_highlighted(region) {
1395 p!(write("'{}", n));
1399 if self.tcx.sess.verbose() {
1400 p!(write("{:?}", region));
1404 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1406 // These printouts are concise. They do not contain all the information
1407 // the user might want to diagnose an error, but there is basically no way
1408 // to fit that into a short string. Hence the recommendation to use
1409 // `explain_region()` or `note_and_explain_region()`.
1411 ty::ReEarlyBound(ref data) => {
1412 if data.name != kw::Invalid {
1413 p!(write("{}", data.name));
1417 ty::ReLateBound(_, br)
1418 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1419 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1420 if let ty::BrNamed(_, name) = br {
1421 if name != kw::Invalid && name != kw::UnderscoreLifetime {
1422 p!(write("{}", name));
1427 if let Some((region, counter)) = highlight.highlight_bound_region {
1429 p!(write("'{}", counter));
1434 ty::ReScope(scope) if identify_regions => {
1436 region::ScopeData::Node => p!(write("'{}s", scope.item_local_id().as_usize())),
1437 region::ScopeData::CallSite => {
1438 p!(write("'{}cs", scope.item_local_id().as_usize()))
1440 region::ScopeData::Arguments => {
1441 p!(write("'{}as", scope.item_local_id().as_usize()))
1443 region::ScopeData::Destruction => {
1444 p!(write("'{}ds", scope.item_local_id().as_usize()))
1446 region::ScopeData::Remainder(first_statement_index) => p!(write(
1448 scope.item_local_id().as_usize(),
1449 first_statement_index.index()
1454 ty::ReVar(region_vid) if identify_regions => {
1455 p!(write("{:?}", region_vid));
1459 ty::ReScope(_) | ty::ReErased => {}
1461 p!(write("'static"));
1464 ty::ReEmpty(ty::UniverseIndex::ROOT) => {
1465 p!(write("'<empty>"));
1468 ty::ReEmpty(ui) => {
1469 p!(write("'<empty:{:?}>", ui));
1473 // The user should never encounter these in unsubstituted form.
1474 ty::ReClosureBound(vid) => {
1475 p!(write("{:?}", vid));
1486 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1487 // `region_index` and `used_region_names`.
1488 impl<F: fmt::Write> FmtPrinter<'_, 'tcx, F> {
1489 pub fn name_all_regions<T>(
1491 value: &ty::Binder<T>,
1492 ) -> Result<(Self, (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)), fmt::Error>
1494 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1496 fn name_by_region_index(index: usize) -> Symbol {
1498 0 => Symbol::intern("'r"),
1499 1 => Symbol::intern("'s"),
1500 i => Symbol::intern(&format!("'t{}", i - 2)),
1504 // Replace any anonymous late-bound regions with named
1505 // variants, using new unique identifiers, so that we can
1506 // clearly differentiate between named and unnamed regions in
1507 // the output. We'll probably want to tweak this over time to
1508 // decide just how much information to give.
1509 if self.binder_depth == 0 {
1510 self.prepare_late_bound_region_info(value);
1513 let mut empty = true;
1514 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1527 define_scoped_cx!(self);
1529 let mut region_index = self.region_index;
1530 let new_value = self.tcx.replace_late_bound_regions(value, |br| {
1531 let _ = start_or_continue(&mut self, "for<", ", ");
1533 ty::BrNamed(_, name) => {
1534 let _ = write!(self, "{}", name);
1537 ty::BrAnon(_) | ty::BrEnv => {
1539 let name = name_by_region_index(region_index);
1541 if !self.used_region_names.contains(&name) {
1545 let _ = write!(self, "{}", name);
1546 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1549 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
1551 start_or_continue(&mut self, "", "> ")?;
1553 self.binder_depth += 1;
1554 self.region_index = region_index;
1555 Ok((self, new_value))
1558 pub fn pretty_in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, fmt::Error>
1560 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1562 let old_region_index = self.region_index;
1563 let (new, new_value) = self.name_all_regions(value)?;
1564 let mut inner = new_value.0.print(new)?;
1565 inner.region_index = old_region_index;
1566 inner.binder_depth -= 1;
1570 fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
1572 T: TypeFoldable<'tcx>,
1574 struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet<Symbol>);
1575 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> {
1576 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
1578 ty::ReLateBound(_, ty::BrNamed(_, name)) => {
1579 self.0.insert(name);
1583 r.super_visit_with(self)
1587 self.used_region_names.clear();
1588 let mut collector = LateBoundRegionNameCollector(&mut self.used_region_names);
1589 value.visit_with(&mut collector);
1590 self.region_index = 0;
1594 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<T>
1596 T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
1599 type Error = P::Error;
1600 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
1605 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
1607 T: Print<'tcx, P, Output = P, Error = P::Error>,
1608 U: Print<'tcx, P, Output = P, Error = P::Error>,
1611 type Error = P::Error;
1612 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
1613 define_scoped_cx!(cx);
1614 p!(print(self.0), write(": "), print(self.1));
1619 macro_rules! forward_display_to_print {
1621 $(impl fmt::Display for $ty {
1622 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1623 ty::tls::with(|tcx| {
1625 .expect("could not lift for printing")
1626 .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1634 macro_rules! define_print_and_forward_display {
1635 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
1636 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
1638 type Error = fmt::Error;
1639 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
1640 #[allow(unused_mut)]
1642 define_scoped_cx!($cx);
1644 #[allow(unreachable_code)]
1649 forward_display_to_print!($($ty),+);
1653 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
1654 impl fmt::Display for ty::RegionKind {
1655 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1656 ty::tls::with(|tcx| {
1657 self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1663 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
1664 /// the trait path. That is, it will print `Trait<U>` instead of
1665 /// `<T as Trait<U>>`.
1666 #[derive(Copy, Clone, TypeFoldable, Lift)]
1667 pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
1669 impl fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
1670 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1671 fmt::Display::fmt(self, f)
1675 impl ty::TraitRef<'tcx> {
1676 pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
1677 TraitRefPrintOnlyTraitPath(self)
1681 impl ty::Binder<ty::TraitRef<'tcx>> {
1682 pub fn print_only_trait_path(self) -> ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>> {
1683 self.map_bound(|tr| tr.print_only_trait_path())
1687 forward_display_to_print! {
1689 &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1690 &'tcx ty::Const<'tcx>,
1692 // HACK(eddyb) these are exhaustive instead of generic,
1693 // because `for<'tcx>` isn't possible yet.
1694 ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
1695 ty::Binder<ty::TraitRef<'tcx>>,
1696 ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>>,
1697 ty::Binder<ty::FnSig<'tcx>>,
1698 ty::Binder<ty::TraitPredicate<'tcx>>,
1699 ty::Binder<ty::SubtypePredicate<'tcx>>,
1700 ty::Binder<ty::ProjectionPredicate<'tcx>>,
1701 ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1702 ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
1704 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1705 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1708 define_print_and_forward_display! {
1711 &'tcx ty::List<Ty<'tcx>> {
1713 let mut tys = self.iter();
1714 if let Some(&ty) = tys.next() {
1717 p!(write(", "), print(ty));
1723 ty::TypeAndMut<'tcx> {
1724 p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
1727 ty::ExistentialTraitRef<'tcx> {
1728 // Use a type that can't appear in defaults of type parameters.
1729 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1730 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
1731 p!(print(trait_ref.print_only_trait_path()))
1734 ty::ExistentialProjection<'tcx> {
1735 let name = cx.tcx().associated_item(self.item_def_id).ident;
1736 p!(write("{} = ", name), print(self.ty))
1739 ty::ExistentialPredicate<'tcx> {
1741 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
1742 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
1743 ty::ExistentialPredicate::AutoTrait(def_id) => {
1744 p!(print_def_path(def_id, &[]));
1750 p!(write("{}", self.unsafety.prefix_str()));
1752 if self.abi != Abi::Rust {
1753 p!(write("extern {} ", self.abi));
1756 p!(write("fn"), pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
1760 if cx.tcx().sess.verbose() {
1761 p!(write("{:?}", self));
1765 ty::TyVar(_) => p!(write("_")),
1766 ty::IntVar(_) => p!(write("{}", "{integer}")),
1767 ty::FloatVar(_) => p!(write("{}", "{float}")),
1768 ty::FreshTy(v) => p!(write("FreshTy({})", v)),
1769 ty::FreshIntTy(v) => p!(write("FreshIntTy({})", v)),
1770 ty::FreshFloatTy(v) => p!(write("FreshFloatTy({})", v))
1774 ty::TraitRef<'tcx> {
1775 p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
1778 TraitRefPrintOnlyTraitPath<'tcx> {
1779 p!(print_def_path(self.0.def_id, self.0.substs));
1783 p!(write("{}", self.name))
1787 p!(write("{}", self.name))
1790 ty::SubtypePredicate<'tcx> {
1791 p!(print(self.a), write(" <: "), print(self.b))
1794 ty::TraitPredicate<'tcx> {
1795 p!(print(self.trait_ref.self_ty()), write(": "),
1796 print(self.trait_ref.print_only_trait_path()))
1799 ty::ProjectionPredicate<'tcx> {
1800 p!(print(self.projection_ty), write(" == "), print(self.ty))
1803 ty::ProjectionTy<'tcx> {
1804 p!(print_def_path(self.item_def_id, self.substs));
1809 ty::ClosureKind::Fn => p!(write("Fn")),
1810 ty::ClosureKind::FnMut => p!(write("FnMut")),
1811 ty::ClosureKind::FnOnce => p!(write("FnOnce")),
1815 ty::Predicate<'tcx> {
1817 ty::Predicate::Trait(ref data, constness) => {
1818 if let hir::Constness::Const = constness {
1819 p!(write("const "));
1823 ty::Predicate::Subtype(ref predicate) => p!(print(predicate)),
1824 ty::Predicate::RegionOutlives(ref predicate) => p!(print(predicate)),
1825 ty::Predicate::TypeOutlives(ref predicate) => p!(print(predicate)),
1826 ty::Predicate::Projection(ref predicate) => p!(print(predicate)),
1827 ty::Predicate::WellFormed(ty) => p!(print(ty), write(" well-formed")),
1828 ty::Predicate::ObjectSafe(trait_def_id) => {
1829 p!(write("the trait `"),
1830 print_def_path(trait_def_id, &[]),
1831 write("` is object-safe"))
1833 ty::Predicate::ClosureKind(closure_def_id, _closure_substs, kind) => {
1834 p!(write("the closure `"),
1835 print_value_path(closure_def_id, &[]),
1836 write("` implements the trait `{}`", kind))
1838 ty::Predicate::ConstEvaluatable(def_id, substs) => {
1839 p!(write("the constant `"),
1840 print_value_path(def_id, substs),
1841 write("` can be evaluated"))
1847 match self.unpack() {
1848 GenericArgKind::Lifetime(lt) => p!(print(lt)),
1849 GenericArgKind::Type(ty) => p!(print(ty)),
1850 GenericArgKind::Const(ct) => p!(print(ct)),