1 use crate::hir::def::Namespace;
2 use crate::hir::def_id::DefId;
3 use crate::middle::region;
4 use crate::ty::subst::{Kind, Subst, SubstsRef, UnpackedKind};
5 use crate::ty::{BrAnon, BrEnv, BrFresh, BrNamed};
6 use crate::ty::{Bool, Char, Adt};
7 use crate::ty::{Error, Str, Array, Slice, Float, FnDef, FnPtr};
8 use crate::ty::{Param, Bound, RawPtr, Ref, Never, Tuple};
9 use crate::ty::{Closure, Generator, GeneratorWitness, Foreign, Projection, Opaque};
10 use crate::ty::{Placeholder, UnnormalizedProjection, Dynamic, Int, Uint, Infer};
11 use crate::ty::{self, ParamConst, Ty, TypeFoldable};
12 use crate::ty::print::{FmtPrinter, PrettyPrinter, PrintCx, Print, Printer};
13 use crate::mir::interpret::ConstValue;
16 use std::fmt::{self, Write as _};
20 use rustc_target::spec::abi::Abi;
21 use syntax::ast::CRATE_NODE_ID;
22 use syntax::symbol::{Symbol, InternedString};
25 /// The "region highlights" are used to control region printing during
26 /// specific error messages. When a "region highlight" is enabled, it
27 /// gives an alternate way to print specific regions. For now, we
28 /// always print those regions using a number, so something like "`'0`".
30 /// Regions not selected by the region highlight mode are presently
32 #[derive(Copy, Clone, Default)]
33 pub struct RegionHighlightMode {
34 /// If enabled, when we see the selected region, use "`'N`"
35 /// instead of the ordinary behavior.
36 highlight_regions: [Option<(ty::RegionKind, usize)>; 3],
38 /// If enabled, when printing a "free region" that originated from
39 /// the given `ty::BoundRegion`, print it as "`'1`". Free regions that would ordinarily
40 /// have names print as normal.
42 /// This is used when you have a signature like `fn foo(x: &u32,
43 /// y: &'a u32)` and we want to give a name to the region of the
45 highlight_bound_region: Option<(ty::BoundRegion, usize)>,
49 /// Mechanism for highlighting of specific regions for display in NLL region inference errors.
50 /// Contains region to highlight and counter for number to use when highlighting.
51 static REGION_HIGHLIGHT_MODE: Cell<RegionHighlightMode> =
52 Cell::new(RegionHighlightMode::default())
55 impl RegionHighlightMode {
56 /// Reads and returns the current region highlight settings (accesses thread-local state).
57 pub fn get() -> Self {
58 REGION_HIGHLIGHT_MODE.with(|c| c.get())
61 // Internal helper to update current settings during the execution of `op`.
65 op: impl FnOnce() -> R,
67 REGION_HIGHLIGHT_MODE.with(|c| {
75 /// If `region` and `number` are both `Some`, invokes
76 /// `highlighting_region`; otherwise, just invokes `op` directly.
77 pub fn maybe_highlighting_region<R>(
78 region: Option<ty::Region<'_>>,
79 number: Option<usize>,
80 op: impl FnOnce() -> R,
82 if let Some(k) = region {
83 if let Some(n) = number {
84 return Self::highlighting_region(k, n, op);
91 /// During the execution of `op`, highlights the region inference
92 /// variable `vid` as `'N`. We can only highlight one region `vid`
94 pub fn highlighting_region<R>(
95 region: ty::Region<'_>,
97 op: impl FnOnce() -> R,
99 let old_mode = Self::get();
100 let mut new_mode = old_mode;
101 let first_avail_slot = new_mode.highlight_regions.iter_mut()
102 .filter(|s| s.is_none())
106 "can only highlight {} placeholders at a time",
107 old_mode.highlight_regions.len(),
110 *first_avail_slot = Some((*region, number));
111 Self::set(old_mode, new_mode, op)
114 /// Convenience wrapper for `highlighting_region`.
115 pub fn highlighting_region_vid<R>(
118 op: impl FnOnce() -> R,
120 Self::highlighting_region(&ty::ReVar(vid), number, op)
123 /// Returns `Some(n)` with the number to use for the given region, if any.
124 fn region_highlighted(&self, region: ty::Region<'_>) -> Option<usize> {
128 .filter_map(|h| match h {
129 Some((r, n)) if r == region => Some(*n),
135 /// During the execution of `op`, highlight the given bound
136 /// region. We can only highlight one bound region at a time. See
137 /// the field `highlight_bound_region` for more detailed notes.
138 pub fn highlighting_bound_region<R>(
141 op: impl FnOnce() -> R,
143 let old_mode = Self::get();
144 assert!(old_mode.highlight_bound_region.is_none());
148 highlight_bound_region: Some((br, number)),
155 /// Returns `Some(N)` if the placeholder `p` is highlighted to print as "`'N`".
156 pub fn placeholder_highlight(&self, p: ty::PlaceholderRegion) -> Option<usize> {
157 self.region_highlighted(&ty::RePlaceholder(p))
161 macro_rules! gen_display_debug_body {
163 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164 PrintCx::with(FmtPrinter { fmt: f }, |mut cx| {
165 $with(&cx.tcx.lift(self).expect("could not lift for printing"), &mut cx)
170 macro_rules! gen_display_debug {
171 ( ($($x:tt)+) $target:ty, display yes ) => {
172 impl<$($x)+> fmt::Display for $target {
173 gen_display_debug_body! { Print::print_display }
176 ( () $target:ty, display yes ) => {
177 impl fmt::Display for $target {
178 gen_display_debug_body! { Print::print_display }
181 ( ($($x:tt)+) $target:ty, debug yes ) => {
182 impl<$($x)+> fmt::Debug for $target {
183 gen_display_debug_body! { Print::print_debug }
186 ( () $target:ty, debug yes ) => {
187 impl fmt::Debug for $target {
188 gen_display_debug_body! { Print::print_debug }
191 ( $generic:tt $target:ty, $t:ident no ) => {};
193 macro_rules! gen_print_impl {
194 ( ($($x:tt)+) $target:ty, ($self:ident, $cx:ident) $disp:block $dbg:block ) => {
195 impl<$($x)+, P: PrettyPrinter> Print<'tcx, P> for $target {
196 type Output = fmt::Result;
197 fn print(&$self, $cx: &mut PrintCx<'_, '_, 'tcx, P>) -> fmt::Result {
203 ( () $target:ty, ($self:ident, $cx:ident) $disp:block $dbg:block ) => {
204 impl<P: PrettyPrinter> Print<'tcx, P> for $target {
205 type Output = fmt::Result;
206 fn print(&$self, $cx: &mut PrintCx<'_, '_, 'tcx, P>) -> fmt::Result {
212 ( $generic:tt $target:ty,
213 $vars:tt $gendisp:ident $disp:block $gendbg:ident $dbg:block ) => {
214 gen_print_impl! { $generic $target, $vars $disp $dbg }
215 gen_display_debug! { $generic $target, display $gendisp }
216 gen_display_debug! { $generic $target, debug $gendbg }
219 macro_rules! define_print {
220 ( $generic:tt $target:ty,
221 $vars:tt { display $disp:block debug $dbg:block } ) => {
222 gen_print_impl! { $generic $target, $vars yes $disp yes $dbg }
224 ( $generic:tt $target:ty,
225 $vars:tt { debug $dbg:block display $disp:block } ) => {
226 gen_print_impl! { $generic $target, $vars yes $disp yes $dbg }
228 ( $generic:tt $target:ty,
229 $vars:tt { debug $dbg:block } ) => {
230 gen_print_impl! { $generic $target, $vars no {
231 bug!(concat!("display not implemented for ", stringify!($target)));
234 ( $generic:tt $target:ty,
235 ($self:ident, $cx:ident) { display $disp:block } ) => {
236 gen_print_impl! { $generic $target, ($self, $cx) yes $disp no {
237 write!($cx.printer, "{:?}", $self)
241 macro_rules! define_print_multi {
242 ( [ $($generic:tt $target:ty),* ] $vars:tt $def:tt ) => {
243 $(define_print! { $generic $target, $vars $def })*
246 macro_rules! print_inner {
247 ( $cx:expr, write ($($data:expr),+) ) => {
248 write!($cx.printer, $($data),+)
250 ( $cx:expr, $kind:ident ($data:expr) ) => {
255 ( $cx:expr $(, $kind:ident $data:tt)+ ) => {
256 Ok(())$(.and_then(|_| print_inner!($cx, $kind $data)))+
260 impl<P: PrettyPrinter> PrintCx<'a, 'gcx, 'tcx, P> {
267 print!(self, write("("))?;
268 let mut inputs = inputs.iter();
269 if let Some(&ty) = inputs.next() {
270 print!(self, print_display(ty))?;
272 print!(self, write(", "), print_display(ty))?;
275 print!(self, write(", ..."))?;
278 print!(self, write(")"))?;
279 if !output.is_unit() {
280 print!(self, write(" -> "), print_display(output))?;
286 fn in_binder<T>(&mut self, value: &ty::Binder<T>) -> fmt::Result
287 where T: Print<'tcx, P, Output = fmt::Result> + TypeFoldable<'tcx>
289 fn name_by_region_index(index: usize) -> InternedString {
291 0 => Symbol::intern("'r"),
292 1 => Symbol::intern("'s"),
293 i => Symbol::intern(&format!("'t{}", i-2)),
297 // Replace any anonymous late-bound regions with named
298 // variants, using gensym'd identifiers, so that we can
299 // clearly differentiate between named and unnamed regions in
300 // the output. We'll probably want to tweak this over time to
301 // decide just how much information to give.
302 if self.binder_depth == 0 {
303 self.prepare_late_bound_region_info(value);
306 let mut empty = true;
307 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
310 print!(cx, write("{}", start))
312 print!(cx, write("{}", cont))
316 let old_region_index = self.region_index;
317 let mut region_index = old_region_index;
318 let new_value = self.tcx.replace_late_bound_regions(value, |br| {
319 let _ = start_or_continue(self, "for<", ", ");
321 ty::BrNamed(_, name) => {
322 let _ = print!(self, write("{}", name));
329 let name = name_by_region_index(region_index);
331 if !self.is_name_used(&name) {
335 let _ = print!(self, write("{}", name));
336 ty::BrNamed(self.tcx.hir().local_def_id(CRATE_NODE_ID), name)
339 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
341 start_or_continue(self, "", "> ")?;
343 // Push current state to gcx, and restore after writing new_value.
344 self.binder_depth += 1;
345 self.region_index = region_index;
346 let result = new_value.print_display(self);
347 self.region_index = old_region_index;
348 self.binder_depth -= 1;
352 fn is_name_used(&self, name: &InternedString) -> bool {
353 match self.used_region_names {
354 Some(ref names) => names.contains(name),
360 pub fn parameterized<F: fmt::Write>(
363 substs: SubstsRef<'_>,
366 PrintCx::with(FmtPrinter { fmt: f }, |mut cx| {
367 let substs = cx.tcx.lift(&substs).expect("could not lift for printing");
368 let _ = cx.print_def_path(did, Some(substs), ns, iter::empty())?;
374 ('tcx) &'tcx ty::List<ty::ExistentialPredicate<'tcx>>, (self, cx) {
376 // Generate the main trait ref, including associated types.
377 let mut first = true;
379 if let Some(principal) = self.principal() {
380 let mut resugared_principal = false;
382 // Special-case `Fn(...) -> ...` and resugar it.
383 if !cx.is_verbose && cx.tcx.lang_items().fn_trait_kind(principal.def_id).is_some() {
384 if let Tuple(ref args) = principal.substs.type_at(0).sty {
385 let mut projections = self.projection_bounds();
386 if let (Some(proj), None) = (projections.next(), projections.next()) {
387 let _ = cx.print_def_path(
393 cx.fn_sig(args, false, proj.ty)?;
394 resugared_principal = true;
399 if !resugared_principal {
400 // Use a type that can't appear in defaults of type parameters.
401 let dummy_self = cx.tcx.mk_infer(ty::FreshTy(0));
402 let principal = principal.with_self_ty(cx.tcx, dummy_self);
403 let _ = cx.print_def_path(
405 Some(principal.substs),
407 self.projection_bounds(),
414 // FIXME(eddyb) avoid printing twice (needed to ensure
415 // that the auto traits are sorted *and* printed via cx).
416 let mut auto_traits: Vec<_> = self.auto_traits().map(|did| {
417 (cx.tcx.def_path_str(did), did)
420 // The auto traits come ordered by `DefPathHash`. While
421 // `DefPathHash` is *stable* in the sense that it depends on
422 // neither the host nor the phase of the moon, it depends
423 // "pseudorandomly" on the compiler version and the target.
425 // To avoid that causing instabilities in compiletest
426 // output, sort the auto-traits alphabetically.
429 for (_, def_id) in auto_traits {
431 print!(cx, write(" + "))?;
435 let _ = cx.print_def_path(
448 impl fmt::Debug for ty::GenericParamDef {
449 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
450 let type_name = match self.kind {
451 ty::GenericParamDefKind::Lifetime => "Lifetime",
452 ty::GenericParamDefKind::Type { .. } => "Type",
453 ty::GenericParamDefKind::Const => "Const",
455 write!(f, "{}({}, {:?}, {})",
463 impl fmt::Debug for ty::TraitDef {
464 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
465 PrintCx::with(FmtPrinter { fmt: f }, |mut cx| {
466 let _ = cx.print_def_path(
477 impl fmt::Debug for ty::AdtDef {
478 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
479 PrintCx::with(FmtPrinter { fmt: f }, |mut cx| {
480 let _ = cx.print_def_path(
491 impl<'tcx> fmt::Debug for ty::ClosureUpvar<'tcx> {
492 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
493 write!(f, "ClosureUpvar({:?},{:?})",
499 impl fmt::Debug for ty::UpvarId {
500 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
501 PrintCx::with(FmtPrinter { fmt: f }, |mut cx| {
502 print!(cx, write("UpvarId({:?};`{}`;{:?})",
503 self.var_path.hir_id,
504 cx.tcx.hir().name_by_hir_id(self.var_path.hir_id),
505 self.closure_expr_id))
510 impl<'tcx> fmt::Debug for ty::UpvarBorrow<'tcx> {
511 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
512 write!(f, "UpvarBorrow({:?}, {:?})",
513 self.kind, self.region)
518 ('tcx) &'tcx ty::List<Ty<'tcx>>, (self, cx) {
520 print!(cx, write("{{"))?;
521 let mut tys = self.iter();
522 if let Some(&ty) = tys.next() {
523 print!(cx, print(ty))?;
525 print!(cx, write(", "), print(ty))?;
528 print!(cx, write("}}"))
534 ('tcx) ty::TypeAndMut<'tcx>, (self, cx) {
537 write("{}", if self.mutbl == hir::MutMutable { "mut " } else { "" }),
544 ('tcx) ty::ExistentialTraitRef<'tcx>, (self, cx) {
546 let dummy_self = cx.tcx.mk_infer(ty::FreshTy(0));
548 ty::Binder::bind(*self)
549 .with_self_ty(cx.tcx, dummy_self)
554 self.print_display(cx)
560 ('tcx) ty::adjustment::Adjustment<'tcx>, (self, cx) {
562 print!(cx, write("{:?} -> ", self.kind), print(self.target))
568 () ty::BoundRegion, (self, cx) {
571 return self.print_debug(cx);
574 if let BrNamed(_, name) = *self {
575 if name != "" && name != "'_" {
576 return print!(cx, write("{}", name));
580 let highlight = RegionHighlightMode::get();
581 if let Some((region, counter)) = highlight.highlight_bound_region {
583 return print!(cx, write("'{}", counter));
591 BrAnon(n) => print!(cx, write("BrAnon({:?})", n)),
592 BrFresh(n) => print!(cx, write("BrFresh({:?})", n)),
593 BrNamed(did, name) => {
594 print!(cx, write("BrNamed({:?}:{:?}, {})",
595 did.krate, did.index, name))
597 BrEnv => print!(cx, write("BrEnv")),
603 // HACK(eddyb) (see `ty::RegionKind::display_outputs_anything`)
605 // NB: this must be kept in sync with the printing logic above.
606 impl ty::BoundRegion {
607 fn display_outputs_anything<P>(&self, cx: &mut PrintCx<'_, '_, '_, P>) -> bool {
612 if let BrNamed(_, name) = *self {
613 if name != "" && name != "'_" {
618 let highlight = RegionHighlightMode::get();
619 if let Some((region, _)) = highlight.highlight_bound_region {
630 () ty::PlaceholderRegion, (self, cx) {
633 return self.print_debug(cx);
636 let highlight = RegionHighlightMode::get();
637 if let Some(counter) = highlight.placeholder_highlight(*self) {
638 return print!(cx, write("'{}", counter));
641 print!(cx, print_display(self.name))
646 // HACK(eddyb) (see `ty::RegionKind::display_outputs_anything`)
648 // NB: this must be kept in sync with the printing logic above.
649 impl ty::PlaceholderRegion {
650 fn display_outputs_anything<P>(&self, cx: &mut PrintCx<'_, '_, '_, P>) -> bool {
655 let highlight = RegionHighlightMode::get();
656 if highlight.placeholder_highlight(*self).is_some() {
660 self.name.display_outputs_anything(cx)
665 () ty::RegionKind, (self, cx) {
668 return self.print_debug(cx);
671 // Watch out for region highlights.
672 if let Some(n) = RegionHighlightMode::get().region_highlighted(self) {
673 return print!(cx, write("'{:?}", n));
676 // These printouts are concise. They do not contain all the information
677 // the user might want to diagnose an error, but there is basically no way
678 // to fit that into a short string. Hence the recommendation to use
679 // `explain_region()` or `note_and_explain_region()`.
681 ty::ReEarlyBound(ref data) => {
682 if data.name != "'_" {
683 print!(cx, write("{}", data.name))
688 ty::ReLateBound(_, br) |
689 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) => {
690 print!(cx, print_display(br))
692 ty::RePlaceholder(p) => {
693 print!(cx, print_display(p))
695 ty::ReScope(scope) if cx.identify_regions => {
697 region::ScopeData::Node =>
698 print!(cx, write("'{}s", scope.item_local_id().as_usize())),
699 region::ScopeData::CallSite =>
700 print!(cx, write("'{}cs", scope.item_local_id().as_usize())),
701 region::ScopeData::Arguments =>
702 print!(cx, write("'{}as", scope.item_local_id().as_usize())),
703 region::ScopeData::Destruction =>
704 print!(cx, write("'{}ds", scope.item_local_id().as_usize())),
705 region::ScopeData::Remainder(first_statement_index) => print!(cx, write(
707 scope.item_local_id().as_usize(),
708 first_statement_index.index()
712 ty::ReVar(region_vid) if cx.identify_regions => {
713 print!(cx, print_debug(region_vid))
715 ty::ReVar(region_vid) => {
716 print!(cx, print_display(region_vid))
719 ty::ReErased => Ok(()),
720 ty::ReStatic => print!(cx, write("'static")),
721 ty::ReEmpty => print!(cx, write("'<empty>")),
723 // The user should never encounter these in unsubstituted form.
724 ty::ReClosureBound(vid) => print!(cx, write("{:?}", vid)),
729 ty::ReEarlyBound(ref data) => {
730 print!(cx, write("ReEarlyBound({}, {})",
735 ty::ReClosureBound(ref vid) => {
736 print!(cx, write("ReClosureBound({:?})",
740 ty::ReLateBound(binder_id, ref bound_region) => {
741 print!(cx, write("ReLateBound({:?}, {:?})",
746 ty::ReFree(ref fr) => print!(cx, write("{:?}", fr)),
749 print!(cx, write("ReScope({:?})", id))
752 ty::ReStatic => print!(cx, write("ReStatic")),
754 ty::ReVar(ref vid) => {
755 print!(cx, write("{:?}", vid))
758 ty::RePlaceholder(placeholder) => {
759 print!(cx, write("RePlaceholder({:?})", placeholder))
762 ty::ReEmpty => print!(cx, write("ReEmpty")),
764 ty::ReErased => print!(cx, write("ReErased"))
770 // HACK(eddyb) Trying to print a lifetime might not print anything, which
771 // may need special handling in the caller (of `ty::RegionKind::print`).
772 // To avoid printing to a temporary string, the `display_outputs_anything`
773 // method can instead be used to determine this, ahead of time.
775 // NB: this must be kept in sync with the printing logic above.
776 impl ty::RegionKind {
777 // HACK(eddyb) `pub(crate)` only for `ty::print`.
778 pub(crate) fn display_outputs_anything<P>(&self, cx: &mut PrintCx<'_, '_, '_, P>) -> bool {
783 if RegionHighlightMode::get().region_highlighted(self).is_some() {
788 ty::ReEarlyBound(ref data) => {
789 data.name != "" && data.name != "'_"
792 ty::ReLateBound(_, br) |
793 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) => {
794 br.display_outputs_anything(cx)
797 ty::RePlaceholder(p) => p.display_outputs_anything(cx),
800 ty::ReVar(_) if cx.identify_regions => true,
802 ty::ReVar(region_vid) => region_vid.display_outputs_anything(cx),
805 ty::ReErased => false,
809 ty::ReClosureBound(_) => true,
815 () ty::FreeRegion, (self, cx) {
817 print!(cx, write("ReFree({:?}, {:?})", self.scope, self.bound_region))
823 () ty::Variance, (self, cx) {
825 cx.printer.write_str(match *self {
826 ty::Covariant => "+",
827 ty::Contravariant => "-",
828 ty::Invariant => "o",
829 ty::Bivariant => "*",
836 ('tcx) ty::FnSig<'tcx>, (self, cx) {
838 if self.unsafety == hir::Unsafety::Unsafe {
839 print!(cx, write("unsafe "))?;
842 if self.abi != Abi::Rust {
843 print!(cx, write("extern {} ", self.abi))?;
846 print!(cx, write("fn"))?;
847 cx.fn_sig(self.inputs(), self.c_variadic, self.output())
850 print!(cx, write("({:?}; c_variadic: {})->{:?}",
851 self.inputs(), self.c_variadic, self.output()))
856 impl fmt::Debug for ty::TyVid {
857 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
858 write!(f, "_#{}t", self.index)
862 impl<'tcx> fmt::Debug for ty::ConstVid<'tcx> {
863 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
864 write!(f, "_#{}f", self.index)
868 impl fmt::Debug for ty::IntVid {
869 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
870 write!(f, "_#{}i", self.index)
874 impl fmt::Debug for ty::FloatVid {
875 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
876 write!(f, "_#{}f", self.index)
881 () ty::RegionVid, (self, cx) {
884 return self.print_debug(cx);
887 let highlight = RegionHighlightMode::get();
888 if let Some(counter) = highlight.region_highlighted(&ty::ReVar(*self)) {
889 return print!(cx, write("'{:?}", counter));
895 // HACK(eddyb) this is duplicated from `display` printing,
896 // to keep NLL borrowck working even with `-Zverbose`.
897 let highlight = RegionHighlightMode::get();
898 if let Some(counter) = highlight.region_highlighted(&ty::ReVar(*self)) {
899 return print!(cx, write("'{:?}", counter));
902 print!(cx, write("'_#{}r", self.index()))
907 // HACK(eddyb) (see `ty::RegionKind::display_outputs_anything`)
909 // NB: this must be kept in sync with the printing logic above.
911 fn display_outputs_anything<P>(&self, cx: &mut PrintCx<'_, '_, '_, P>) -> bool {
916 let highlight = RegionHighlightMode::get();
917 if highlight.region_highlighted(&ty::ReVar(*self)).is_some() {
926 () ty::InferTy, (self, cx) {
929 return self.print_debug(cx);
932 ty::TyVar(_) => print!(cx, write("_")),
933 ty::IntVar(_) => print!(cx, write("{}", "{integer}")),
934 ty::FloatVar(_) => print!(cx, write("{}", "{float}")),
935 ty::FreshTy(v) => print!(cx, write("FreshTy({})", v)),
936 ty::FreshIntTy(v) => print!(cx, write("FreshIntTy({})", v)),
937 ty::FreshFloatTy(v) => print!(cx, write("FreshFloatTy({})", v))
942 ty::TyVar(ref v) => print!(cx, write("{:?}", v)),
943 ty::IntVar(ref v) => print!(cx, write("{:?}", v)),
944 ty::FloatVar(ref v) => print!(cx, write("{:?}", v)),
945 ty::FreshTy(v) => print!(cx, write("FreshTy({:?})", v)),
946 ty::FreshIntTy(v) => print!(cx, write("FreshIntTy({:?})", v)),
947 ty::FreshFloatTy(v) => print!(cx, write("FreshFloatTy({:?})", v))
953 impl fmt::Debug for ty::IntVarValue {
954 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
956 ty::IntType(ref v) => v.fmt(f),
957 ty::UintType(ref v) => v.fmt(f),
962 impl fmt::Debug for ty::FloatVarValue {
963 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
968 // The generic impl doesn't work yet because projections are not
969 // normalized under HRTB.
970 /*impl<T> fmt::Display for ty::Binder<T>
971 where T: fmt::Display + for<'a> ty::Lift<'a>,
972 for<'a> <T as ty::Lift<'a>>::Lifted: fmt::Display + TypeFoldable<'a>
974 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
975 PrintCx::with(|cx| cx.in_binder(cx.tcx.lift(self)
976 .expect("could not lift for printing")))
980 define_print_multi! {
982 ('tcx) ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
983 ('tcx) ty::Binder<ty::TraitRef<'tcx>>,
984 ('tcx) ty::Binder<ty::FnSig<'tcx>>,
985 ('tcx) ty::Binder<ty::TraitPredicate<'tcx>>,
986 ('tcx) ty::Binder<ty::SubtypePredicate<'tcx>>,
987 ('tcx) ty::Binder<ty::ProjectionPredicate<'tcx>>,
988 ('tcx) ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
989 ('tcx) ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>
999 ('tcx) ty::TraitRef<'tcx>, (self, cx) {
1001 let _ = cx.print_def_path(
1010 let _ = cx.path_qualified(self.self_ty(), Some(*self))?;
1017 ('tcx) ty::Ty<'tcx>, (self, cx) {
1020 Bool => print!(cx, write("bool")),
1021 Char => print!(cx, write("char")),
1022 Int(t) => print!(cx, write("{}", t.ty_to_string())),
1023 Uint(t) => print!(cx, write("{}", t.ty_to_string())),
1024 Float(t) => print!(cx, write("{}", t.ty_to_string())),
1026 print!(cx, write("*{} ", match tm.mutbl {
1027 hir::MutMutable => "mut",
1028 hir::MutImmutable => "const",
1032 Ref(r, ty, mutbl) => {
1033 print!(cx, write("&"))?;
1034 if r.display_outputs_anything(cx) {
1035 print!(cx, print_display(r), write(" "))?;
1037 ty::TypeAndMut { ty, mutbl }.print(cx)
1039 Never => print!(cx, write("!")),
1041 print!(cx, write("("))?;
1042 let mut tys = tys.iter();
1043 if let Some(&ty) = tys.next() {
1044 print!(cx, print(ty), write(","))?;
1045 if let Some(&ty) = tys.next() {
1046 print!(cx, write(" "), print(ty))?;
1048 print!(cx, write(", "), print(ty))?;
1052 print!(cx, write(")"))
1054 FnDef(def_id, substs) => {
1055 let sig = cx.tcx.fn_sig(def_id).subst(cx.tcx, substs);
1056 print!(cx, print(sig), write(" {{"))?;
1057 let _ = cx.print_def_path(
1063 print!(cx, write("}}"))
1065 FnPtr(ref bare_fn) => {
1068 Infer(infer_ty) => print!(cx, write("{}", infer_ty)),
1069 Error => print!(cx, write("[type error]")),
1070 Param(ref param_ty) => print!(cx, write("{}", param_ty)),
1071 Bound(debruijn, bound_ty) => {
1072 match bound_ty.kind {
1073 ty::BoundTyKind::Anon => {
1074 if debruijn == ty::INNERMOST {
1075 print!(cx, write("^{}", bound_ty.var.index()))
1077 print!(cx, write("^{}_{}", debruijn.index(), bound_ty.var.index()))
1081 ty::BoundTyKind::Param(p) => print!(cx, write("{}", p)),
1084 Adt(def, substs) => {
1085 let _ = cx.print_def_path(
1093 Dynamic(data, r) => {
1094 let print_r = r.display_outputs_anything(cx);
1096 print!(cx, write("("))?;
1098 print!(cx, write("dyn "))?;
1101 print!(cx, write(" + "), print_display(r), write(")"))?;
1105 Foreign(def_id) => {
1106 let _ = cx.print_def_path(
1114 Projection(ref data) => data.print(cx),
1115 UnnormalizedProjection(ref data) => {
1116 print!(cx, write("Unnormalized("))?;
1118 print!(cx, write(")"))
1120 Placeholder(placeholder) => {
1121 print!(cx, write("Placeholder({:?})", placeholder))
1123 Opaque(def_id, substs) => {
1125 return print!(cx, write("Opaque({:?}, {:?})", def_id, substs));
1128 let def_key = cx.tcx.def_key(def_id);
1129 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
1130 print!(cx, write("{}", name))?;
1131 let mut substs = substs.iter();
1132 // FIXME(eddyb) print this with `print_def_path`.
1133 if let Some(first) = substs.next() {
1134 print!(cx, write("::<"))?;
1135 print!(cx, write("{}", first))?;
1136 for subst in substs {
1137 print!(cx, write(", {}", subst))?;
1139 print!(cx, write(">"))?;
1143 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1144 // by looking up the projections associated with the def_id.
1145 let bounds = cx.tcx.predicates_of(def_id).instantiate(cx.tcx, substs);
1147 let mut first = true;
1148 let mut is_sized = false;
1149 print!(cx, write("impl"))?;
1150 for predicate in bounds.predicates {
1151 if let Some(trait_ref) = predicate.to_opt_poly_trait_ref() {
1152 // Don't print +Sized, but rather +?Sized if absent.
1153 if Some(trait_ref.def_id()) == cx.tcx.lang_items().sized_trait() {
1159 write("{}", if first { " " } else { "+" }),
1165 print!(cx, write("{}?Sized", if first { " " } else { "+" }))?;
1167 print!(cx, write(" Sized"))?;
1171 Str => print!(cx, write("str")),
1172 Generator(did, substs, movability) => {
1173 let upvar_tys = substs.upvar_tys(did, cx.tcx);
1174 let witness = substs.witness(did, cx.tcx);
1175 if movability == hir::GeneratorMovability::Movable {
1176 print!(cx, write("[generator"))?;
1178 print!(cx, write("[static generator"))?;
1181 // FIXME(eddyb) should use `def_span`.
1182 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(did) {
1183 print!(cx, write("@{:?}", cx.tcx.hir().span_by_hir_id(hir_id)))?;
1185 cx.tcx.with_freevars(hir_id, |freevars| {
1186 for (freevar, upvar_ty) in freevars.iter().zip(upvar_tys) {
1190 cx.tcx.hir().name(freevar.var_id())),
1197 // cross-crate closure types should only be
1198 // visible in codegen bug reports, I imagine.
1199 print!(cx, write("@{:?}", did))?;
1201 for (index, upvar_ty) in upvar_tys.enumerate() {
1203 write("{}{}:", sep, index),
1209 print!(cx, write(" "), print(witness), write("]"))
1211 GeneratorWitness(types) => {
1212 cx.in_binder(&types)
1214 Closure(did, substs) => {
1215 let upvar_tys = substs.upvar_tys(did, cx.tcx);
1216 print!(cx, write("[closure"))?;
1218 // FIXME(eddyb) should use `def_span`.
1219 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(did) {
1220 if cx.tcx.sess.opts.debugging_opts.span_free_formats {
1221 print!(cx, write("@{:?}", hir_id))?;
1223 print!(cx, write("@{:?}", cx.tcx.hir().span_by_hir_id(hir_id)))?;
1226 cx.tcx.with_freevars(hir_id, |freevars| {
1227 for (freevar, upvar_ty) in freevars.iter().zip(upvar_tys) {
1231 cx.tcx.hir().name(freevar.var_id())),
1238 // cross-crate closure types should only be
1239 // visible in codegen bug reports, I imagine.
1240 print!(cx, write("@{:?}", did))?;
1242 for (index, upvar_ty) in upvar_tys.enumerate() {
1244 write("{}{}:", sep, index),
1252 " closure_kind_ty={:?} closure_sig_ty={:?}",
1253 substs.closure_kind_ty(did, cx.tcx),
1254 substs.closure_sig_ty(did, cx.tcx)
1258 print!(cx, write("]"))
1261 print!(cx, write("["), print(ty), write("; "))?;
1263 ty::LazyConst::Unevaluated(_def_id, _substs) => {
1264 print!(cx, write("_"))?;
1266 ty::LazyConst::Evaluated(c) => {
1268 ConstValue::Infer(..) => print!(cx, write("_"))?,
1269 ConstValue::Param(ParamConst { name, .. }) =>
1270 print!(cx, write("{}", name))?,
1271 _ => print!(cx, write("{}", c.unwrap_usize(cx.tcx)))?,
1275 print!(cx, write("]"))
1278 print!(cx, write("["), print(ty), write("]"))
1283 self.print_display(cx)
1289 ('tcx) ConstValue<'tcx>, (self, cx) {
1292 ConstValue::Infer(..) => print!(cx, write("_")),
1293 ConstValue::Param(ParamConst { name, .. }) => print!(cx, write("{}", name)),
1294 _ => print!(cx, write("{:?}", self)),
1301 ('tcx) ty::Const<'tcx>, (self, cx) {
1303 print!(cx, write("{} : {}", self.val, self.ty))
1309 ('tcx) ty::LazyConst<'tcx>, (self, cx) {
1312 // FIXME(const_generics) this should print at least the type.
1313 ty::LazyConst::Unevaluated(..) => print!(cx, write("_ : _")),
1314 ty::LazyConst::Evaluated(c) => print!(cx, write("{}", c)),
1321 () ty::ParamTy, (self, cx) {
1323 print!(cx, write("{}", self.name))
1326 print!(cx, write("{}/#{}", self.name, self.idx))
1332 () ty::ParamConst, (self, cx) {
1334 print!(cx, write("{}", self.name))
1337 print!(cx, write("{}/#{}", self.name, self.index))
1342 // Similar problem to `Binder<T>`, can't define a generic impl.
1343 define_print_multi! {
1345 ('tcx) ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1346 ('tcx) ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1350 print!(cx, print(self.0), write(" : "), print(self.1))
1356 ('tcx) ty::SubtypePredicate<'tcx>, (self, cx) {
1358 print!(cx, print(self.a), write(" <: "), print(self.b))
1364 ('tcx) ty::TraitPredicate<'tcx>, (self, cx) {
1366 print!(cx, write("TraitPredicate({:?})",
1370 print!(cx, print(self.trait_ref.self_ty()), write(": "), print(self.trait_ref))
1376 ('tcx) ty::ProjectionPredicate<'tcx>, (self, cx) {
1379 write("ProjectionPredicate("),
1380 print(self.projection_ty),
1386 print!(cx, print(self.projection_ty), write(" == "), print(self.ty))
1392 ('tcx) ty::ProjectionTy<'tcx>, (self, cx) {
1394 let _ = cx.print_def_path(
1406 () ty::ClosureKind, (self, cx) {
1409 ty::ClosureKind::Fn => print!(cx, write("Fn")),
1410 ty::ClosureKind::FnMut => print!(cx, write("FnMut")),
1411 ty::ClosureKind::FnOnce => print!(cx, write("FnOnce")),
1418 ('tcx) ty::Predicate<'tcx>, (self, cx) {
1421 ty::Predicate::Trait(ref data) => data.print(cx),
1422 ty::Predicate::Subtype(ref predicate) => predicate.print(cx),
1423 ty::Predicate::RegionOutlives(ref predicate) => predicate.print(cx),
1424 ty::Predicate::TypeOutlives(ref predicate) => predicate.print(cx),
1425 ty::Predicate::Projection(ref predicate) => predicate.print(cx),
1426 ty::Predicate::WellFormed(ty) => print!(cx, print(ty), write(" well-formed")),
1427 ty::Predicate::ObjectSafe(trait_def_id) => {
1428 print!(cx, write("the trait `"))?;
1429 let _ = cx.print_def_path(
1435 print!(cx, write("` is object-safe"))
1437 ty::Predicate::ClosureKind(closure_def_id, _closure_substs, kind) => {
1438 print!(cx, write("the closure `"))?;
1439 let _ = cx.print_def_path(
1445 print!(cx, write("` implements the trait `{}`", kind))
1447 ty::Predicate::ConstEvaluatable(def_id, substs) => {
1448 print!(cx, write("the constant `"))?;
1449 let _ = cx.print_def_path(
1455 print!(cx, write("` can be evaluated"))
1461 ty::Predicate::Trait(ref a) => a.print(cx),
1462 ty::Predicate::Subtype(ref pair) => pair.print(cx),
1463 ty::Predicate::RegionOutlives(ref pair) => pair.print(cx),
1464 ty::Predicate::TypeOutlives(ref pair) => pair.print(cx),
1465 ty::Predicate::Projection(ref pair) => pair.print(cx),
1466 ty::Predicate::WellFormed(ty) => ty.print(cx),
1467 ty::Predicate::ObjectSafe(trait_def_id) => {
1468 print!(cx, write("ObjectSafe({:?})", trait_def_id))
1470 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
1471 print!(cx, write("ClosureKind({:?}, {:?}, {:?})",
1472 closure_def_id, closure_substs, kind))
1474 ty::Predicate::ConstEvaluatable(def_id, substs) => {
1475 print!(cx, write("ConstEvaluatable({:?}, {:?})", def_id, substs))
1483 ('tcx) Kind<'tcx>, (self, cx) {
1485 match self.unpack() {
1486 UnpackedKind::Lifetime(lt) => print!(cx, print(lt)),
1487 UnpackedKind::Type(ty) => print!(cx, print(ty)),
1488 UnpackedKind::Const(ct) => print!(cx, print(ct)),
1492 match self.unpack() {
1493 UnpackedKind::Lifetime(lt) => print!(cx, print(lt)),
1494 UnpackedKind::Type(ty) => print!(cx, print(ty)),
1495 UnpackedKind::Const(ct) => print!(cx, print(ct)),