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_tls_tcx(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 {
197 type Error = fmt::Error;
198 fn print(&$self, $cx: &mut PrintCx<'_, '_, 'tcx, P>) -> fmt::Result {
200 define_scoped_cx!($cx);
201 if $cx.config.is_debug $dbg
207 ( () $target:ty, ($self:ident, $cx:ident) $disp:block $dbg:block ) => {
208 impl<P: PrettyPrinter> Print<'tcx, P> for $target {
210 type Error = fmt::Error;
211 fn print(&$self, $cx: &mut PrintCx<'_, '_, 'tcx, P>) -> fmt::Result {
213 define_scoped_cx!($cx);
214 if $cx.config.is_debug $dbg
220 ( $generic:tt $target:ty,
221 $vars:tt $gendisp:ident $disp:block $gendbg:ident $dbg:block ) => {
222 gen_print_impl! { $generic $target, $vars $disp $dbg }
223 gen_display_debug! { $generic $target, display $gendisp }
224 gen_display_debug! { $generic $target, debug $gendbg }
227 macro_rules! define_print {
228 ( $generic:tt $target:ty,
229 $vars:tt { display $disp:block debug $dbg:block } ) => {
230 gen_print_impl! { $generic $target, $vars yes $disp yes $dbg }
232 ( $generic:tt $target:ty,
233 $vars:tt { debug $dbg:block display $disp:block } ) => {
234 gen_print_impl! { $generic $target, $vars yes $disp yes $dbg }
236 ( $generic:tt $target:ty,
237 $vars:tt { debug $dbg:block } ) => {
238 gen_print_impl! { $generic $target, $vars no {
239 bug!(concat!("display not implemented for ", stringify!($target)));
242 ( $generic:tt $target:ty,
243 ($self:ident, $cx:ident) { display $disp:block } ) => {
244 gen_print_impl! { $generic $target, ($self, $cx) yes $disp no {
245 write!($cx.printer, "{:?}", $self)?
249 macro_rules! define_print_multi {
250 ( [ $($generic:tt $target:ty),* ] $vars:tt $def:tt ) => {
251 $(define_print! { $generic $target, $vars $def })*
254 macro_rules! print_inner {
255 (write ($($data:expr),+)) => {
256 write!(scoped_cx!().printer, $($data),+)
258 ($kind:ident ($data:expr)) => {
259 $data.$kind(scoped_cx!())
263 ($($kind:ident $data:tt),+) => {
265 $(print_inner!($kind $data)?);+
269 macro_rules! define_scoped_cx {
271 #[allow(unused_macros)]
272 macro_rules! scoped_cx {
278 impl<P: PrettyPrinter> PrintCx<'a, 'gcx, 'tcx, P> {
285 define_scoped_cx!(self);
288 let mut inputs = inputs.iter();
289 if let Some(&ty) = inputs.next() {
290 p!(print_display(ty));
292 p!(write(", "), print_display(ty));
299 if !output.is_unit() {
300 p!(write(" -> "), print_display(output));
306 fn in_binder<T>(&mut self, value: &ty::Binder<T>) -> Result<T::Output, fmt::Error>
307 where T: Print<'tcx, P, Error = fmt::Error> + TypeFoldable<'tcx>
309 fn name_by_region_index(index: usize) -> InternedString {
311 0 => Symbol::intern("'r"),
312 1 => Symbol::intern("'s"),
313 i => Symbol::intern(&format!("'t{}", i-2)),
317 // Replace any anonymous late-bound regions with named
318 // variants, using gensym'd identifiers, so that we can
319 // clearly differentiate between named and unnamed regions in
320 // the output. We'll probably want to tweak this over time to
321 // decide just how much information to give.
322 if self.config.binder_depth == 0 {
323 self.prepare_late_bound_region_info(value);
326 let mut empty = true;
327 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
328 write!(cx.printer, "{}", if empty {
336 // NOTE(eddyb) this must be below `start_or_continue`'s definition
337 // as that also has a `define_scoped_cx` and that kind of shadowing
338 // is disallowed (name resolution thinks `scoped_cx!` is ambiguous).
339 define_scoped_cx!(self);
341 let old_region_index = self.config.region_index;
342 let mut region_index = old_region_index;
343 let new_value = self.tcx.replace_late_bound_regions(value, |br| {
344 let _ = start_or_continue(self, "for<", ", ");
346 ty::BrNamed(_, name) => {
347 let _ = write!(self.printer, "{}", name);
354 let name = name_by_region_index(region_index);
356 if !self.is_name_used(&name) {
360 let _ = write!(self.printer, "{}", name);
361 ty::BrNamed(self.tcx.hir().local_def_id(CRATE_NODE_ID), name)
364 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
366 start_or_continue(self, "", "> ")?;
368 // Push current state to gcx, and restore after writing new_value.
369 self.config.binder_depth += 1;
370 self.config.region_index = region_index;
371 let result = new_value.print_display(self);
372 self.config.region_index = old_region_index;
373 self.config.binder_depth -= 1;
377 fn is_name_used(&self, name: &InternedString) -> bool {
378 match self.config.used_region_names {
379 Some(ref names) => names.contains(name),
385 pub fn parameterized<F: fmt::Write>(
388 substs: SubstsRef<'_>,
391 PrintCx::with_tls_tcx(FmtPrinter { fmt: f }, |mut cx| {
392 let substs = cx.tcx.lift(&substs).expect("could not lift for printing");
393 let _ = cx.print_def_path(did, Some(substs), ns, iter::empty())?;
399 ('tcx) &'tcx ty::List<ty::ExistentialPredicate<'tcx>>, (self, cx) {
401 // Generate the main trait ref, including associated types.
402 let mut first = true;
404 if let Some(principal) = self.principal() {
405 let mut resugared_principal = false;
407 // Special-case `Fn(...) -> ...` and resugar it.
408 let fn_trait_kind = cx.tcx.lang_items().fn_trait_kind(principal.def_id);
409 if !cx.config.is_verbose && fn_trait_kind.is_some() {
410 if let ty::Tuple(ref args) = principal.substs.type_at(0).sty {
411 let mut projections = self.projection_bounds();
412 if let (Some(proj), None) = (projections.next(), projections.next()) {
413 let _ = cx.print_def_path(
419 cx.fn_sig(args, false, proj.ty)?;
420 resugared_principal = true;
425 if !resugared_principal {
426 // Use a type that can't appear in defaults of type parameters.
427 let dummy_self = cx.tcx.mk_infer(ty::FreshTy(0));
428 let principal = principal.with_self_ty(cx.tcx, dummy_self);
429 let _ = cx.print_def_path(
431 Some(principal.substs),
433 self.projection_bounds(),
440 // FIXME(eddyb) avoid printing twice (needed to ensure
441 // that the auto traits are sorted *and* printed via cx).
442 let mut auto_traits: Vec<_> = self.auto_traits().map(|did| {
443 (cx.tcx.def_path_str(did), did)
446 // The auto traits come ordered by `DefPathHash`. While
447 // `DefPathHash` is *stable* in the sense that it depends on
448 // neither the host nor the phase of the moon, it depends
449 // "pseudorandomly" on the compiler version and the target.
451 // To avoid that causing instabilities in compiletest
452 // output, sort the auto-traits alphabetically.
455 for (_, def_id) in auto_traits {
461 let _ = cx.print_def_path(
472 impl fmt::Debug for ty::GenericParamDef {
473 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
474 let type_name = match self.kind {
475 ty::GenericParamDefKind::Lifetime => "Lifetime",
476 ty::GenericParamDefKind::Type { .. } => "Type",
477 ty::GenericParamDefKind::Const => "Const",
479 write!(f, "{}({}, {:?}, {})",
487 impl fmt::Debug for ty::TraitDef {
488 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
489 PrintCx::with_tls_tcx(FmtPrinter { fmt: f }, |mut cx| {
490 let _ = cx.print_def_path(
501 impl fmt::Debug for ty::AdtDef {
502 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
503 PrintCx::with_tls_tcx(FmtPrinter { fmt: f }, |mut cx| {
504 let _ = cx.print_def_path(
515 impl<'tcx> fmt::Debug for ty::ClosureUpvar<'tcx> {
516 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
517 write!(f, "ClosureUpvar({:?},{:?})",
523 impl fmt::Debug for ty::UpvarId {
524 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
525 PrintCx::with_tls_tcx(FmtPrinter { fmt: f }, |mut cx| {
526 define_scoped_cx!(cx);
527 p!(write("UpvarId({:?};`{}`;{:?})",
528 self.var_path.hir_id,
529 cx.tcx.hir().name_by_hir_id(self.var_path.hir_id),
530 self.closure_expr_id));
536 impl<'tcx> fmt::Debug for ty::UpvarBorrow<'tcx> {
537 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
538 write!(f, "UpvarBorrow({:?}, {:?})",
539 self.kind, self.region)
544 ('tcx) &'tcx ty::List<Ty<'tcx>>, (self, cx) {
547 let mut tys = self.iter();
548 if let Some(&ty) = tys.next() {
551 p!(write(", "), print(ty));
560 ('tcx) ty::TypeAndMut<'tcx>, (self, cx) {
563 write("{}", if self.mutbl == hir::MutMutable { "mut " } else { "" }),
570 ('tcx) ty::ExistentialTraitRef<'tcx>, (self, cx) {
572 let dummy_self = cx.tcx.mk_infer(ty::FreshTy(0));
574 p!(print_display(ty::Binder::bind(*self)
575 .with_self_ty(cx.tcx, dummy_self)
579 p!(print_display(self))
585 ('tcx) ty::adjustment::Adjustment<'tcx>, (self, cx) {
587 p!(write("{:?} -> ", self.kind), print(self.target))
593 () ty::BoundRegion, (self, cx) {
595 if cx.config.is_verbose {
596 return self.print_debug(cx);
599 if let BrNamed(_, name) = *self {
600 if name != "" && name != "'_" {
601 p!(write("{}", name));
606 let highlight = RegionHighlightMode::get();
607 if let Some((region, counter)) = highlight.highlight_bound_region {
609 p!(write("'{}", counter));
615 BrAnon(n) => p!(write("BrAnon({:?})", n)),
616 BrFresh(n) => p!(write("BrFresh({:?})", n)),
617 BrNamed(did, name) => {
618 p!(write("BrNamed({:?}:{:?}, {})",
619 did.krate, did.index, name))
621 BrEnv => p!(write("BrEnv")),
627 // HACK(eddyb) (see `ty::RegionKind::display_outputs_anything`)
629 // NB: this must be kept in sync with the printing logic above.
630 impl ty::BoundRegion {
631 fn display_outputs_anything<P>(&self, cx: &mut PrintCx<'_, '_, '_, P>) -> bool {
632 if cx.config.is_verbose {
636 if let BrNamed(_, name) = *self {
637 if name != "" && name != "'_" {
642 let highlight = RegionHighlightMode::get();
643 if let Some((region, _)) = highlight.highlight_bound_region {
654 () ty::PlaceholderRegion, (self, cx) {
656 if cx.config.is_verbose {
657 return self.print_debug(cx);
660 let highlight = RegionHighlightMode::get();
661 if let Some(counter) = highlight.placeholder_highlight(*self) {
662 p!(write("'{}", counter));
664 p!(print_display(self.name));
670 // HACK(eddyb) (see `ty::RegionKind::display_outputs_anything`)
672 // NB: this must be kept in sync with the printing logic above.
673 impl ty::PlaceholderRegion {
674 fn display_outputs_anything<P>(&self, cx: &mut PrintCx<'_, '_, '_, P>) -> bool {
675 if cx.config.is_verbose {
679 let highlight = RegionHighlightMode::get();
680 if highlight.placeholder_highlight(*self).is_some() {
684 self.name.display_outputs_anything(cx)
689 () ty::RegionKind, (self, cx) {
691 if cx.config.is_verbose {
692 return self.print_debug(cx);
695 // Watch out for region highlights.
696 if let Some(n) = RegionHighlightMode::get().region_highlighted(self) {
697 p!(write("'{:?}", n));
701 // These printouts are concise. They do not contain all the information
702 // the user might want to diagnose an error, but there is basically no way
703 // to fit that into a short string. Hence the recommendation to use
704 // `explain_region()` or `note_and_explain_region()`.
706 ty::ReEarlyBound(ref data) => {
707 if data.name != "'_" {
708 p!(write("{}", data.name))
711 ty::ReLateBound(_, br) |
712 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) => {
713 p!(print_display(br))
715 ty::RePlaceholder(p) => {
718 ty::ReScope(scope) if cx.config.identify_regions => {
720 region::ScopeData::Node =>
721 p!(write("'{}s", scope.item_local_id().as_usize())),
722 region::ScopeData::CallSite =>
723 p!(write("'{}cs", scope.item_local_id().as_usize())),
724 region::ScopeData::Arguments =>
725 p!(write("'{}as", scope.item_local_id().as_usize())),
726 region::ScopeData::Destruction =>
727 p!(write("'{}ds", scope.item_local_id().as_usize())),
728 region::ScopeData::Remainder(first_statement_index) => p!(write(
730 scope.item_local_id().as_usize(),
731 first_statement_index.index()
735 ty::ReVar(region_vid) if cx.config.identify_regions => {
736 p!(print_debug(region_vid))
738 ty::ReVar(region_vid) => {
739 p!(print_display(region_vid))
743 ty::ReStatic => p!(write("'static")),
744 ty::ReEmpty => p!(write("'<empty>")),
746 // The user should never encounter these in unsubstituted form.
747 ty::ReClosureBound(vid) => p!(write("{:?}", vid)),
752 ty::ReEarlyBound(ref data) => {
753 p!(write("ReEarlyBound({}, {})",
758 ty::ReClosureBound(ref vid) => {
759 p!(write("ReClosureBound({:?})",
763 ty::ReLateBound(binder_id, ref bound_region) => {
764 p!(write("ReLateBound({:?}, {:?})",
769 ty::ReFree(ref fr) => p!(write("{:?}", fr)),
772 p!(write("ReScope({:?})", id))
775 ty::ReStatic => p!(write("ReStatic")),
777 ty::ReVar(ref vid) => {
778 p!(write("{:?}", vid))
781 ty::RePlaceholder(placeholder) => {
782 p!(write("RePlaceholder({:?})", placeholder))
785 ty::ReEmpty => p!(write("ReEmpty")),
787 ty::ReErased => p!(write("ReErased"))
793 // HACK(eddyb) Trying to print a lifetime might not print anything, which
794 // may need special handling in the caller (of `ty::RegionKind::print`).
795 // To avoid printing to a temporary string, the `display_outputs_anything`
796 // method can instead be used to determine this, ahead of time.
798 // NB: this must be kept in sync with the printing logic above.
799 impl ty::RegionKind {
800 // HACK(eddyb) `pub(crate)` only for `ty::print`.
801 pub(crate) fn display_outputs_anything<P>(&self, cx: &mut PrintCx<'_, '_, '_, P>) -> bool {
802 if cx.config.is_verbose {
806 if RegionHighlightMode::get().region_highlighted(self).is_some() {
811 ty::ReEarlyBound(ref data) => {
812 data.name != "" && data.name != "'_"
815 ty::ReLateBound(_, br) |
816 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) => {
817 br.display_outputs_anything(cx)
820 ty::RePlaceholder(p) => p.display_outputs_anything(cx),
823 ty::ReVar(_) if cx.config.identify_regions => true,
825 ty::ReVar(region_vid) => region_vid.display_outputs_anything(cx),
828 ty::ReErased => false,
832 ty::ReClosureBound(_) => true,
838 () ty::FreeRegion, (self, cx) {
840 p!(write("ReFree({:?}, {:?})", self.scope, self.bound_region))
846 () ty::Variance, (self, cx) {
848 cx.printer.write_str(match *self {
849 ty::Covariant => "+",
850 ty::Contravariant => "-",
851 ty::Invariant => "o",
852 ty::Bivariant => "*",
859 ('tcx) ty::FnSig<'tcx>, (self, cx) {
861 if self.unsafety == hir::Unsafety::Unsafe {
862 p!(write("unsafe "));
865 if self.abi != Abi::Rust {
866 p!(write("extern {} ", self.abi));
870 cx.fn_sig(self.inputs(), self.c_variadic, self.output())?
873 p!(write("({:?}; c_variadic: {})->{:?}",
874 self.inputs(), self.c_variadic, self.output()))
879 impl fmt::Debug for ty::TyVid {
880 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
881 write!(f, "_#{}t", self.index)
885 impl<'tcx> fmt::Debug for ty::ConstVid<'tcx> {
886 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
887 write!(f, "_#{}f", self.index)
891 impl fmt::Debug for ty::IntVid {
892 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
893 write!(f, "_#{}i", self.index)
897 impl fmt::Debug for ty::FloatVid {
898 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
899 write!(f, "_#{}f", self.index)
904 () ty::RegionVid, (self, cx) {
906 if cx.config.is_verbose {
907 return self.print_debug(cx);
910 let highlight = RegionHighlightMode::get();
911 if let Some(counter) = highlight.region_highlighted(&ty::ReVar(*self)) {
912 p!(write("'{:?}", counter));
916 // HACK(eddyb) this is duplicated from `display` printing,
917 // to keep NLL borrowck working even with `-Zverbose`.
918 let highlight = RegionHighlightMode::get();
919 if let Some(counter) = highlight.region_highlighted(&ty::ReVar(*self)) {
920 p!(write("'{:?}", counter));
922 p!(write("'_#{}r", self.index()));
928 // HACK(eddyb) (see `ty::RegionKind::display_outputs_anything`)
930 // NB: this must be kept in sync with the printing logic above.
932 fn display_outputs_anything<P>(&self, cx: &mut PrintCx<'_, '_, '_, P>) -> bool {
933 if cx.config.is_verbose {
937 let highlight = RegionHighlightMode::get();
938 if highlight.region_highlighted(&ty::ReVar(*self)).is_some() {
947 () ty::InferTy, (self, cx) {
949 if cx.config.is_verbose {
950 return self.print_debug(cx);
953 ty::TyVar(_) => p!(write("_")),
954 ty::IntVar(_) => p!(write("{}", "{integer}")),
955 ty::FloatVar(_) => p!(write("{}", "{float}")),
956 ty::FreshTy(v) => p!(write("FreshTy({})", v)),
957 ty::FreshIntTy(v) => p!(write("FreshIntTy({})", v)),
958 ty::FreshFloatTy(v) => p!(write("FreshFloatTy({})", v))
963 ty::TyVar(ref v) => p!(write("{:?}", v)),
964 ty::IntVar(ref v) => p!(write("{:?}", v)),
965 ty::FloatVar(ref v) => p!(write("{:?}", v)),
966 ty::FreshTy(v) => p!(write("FreshTy({:?})", v)),
967 ty::FreshIntTy(v) => p!(write("FreshIntTy({:?})", v)),
968 ty::FreshFloatTy(v) => p!(write("FreshFloatTy({:?})", v))
974 impl fmt::Debug for ty::IntVarValue {
975 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
977 ty::IntType(ref v) => v.fmt(f),
978 ty::UintType(ref v) => v.fmt(f),
983 impl fmt::Debug for ty::FloatVarValue {
984 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
989 // The generic impl doesn't work yet because projections are not
990 // normalized under HRTB.
991 /*impl<T> fmt::Display for ty::Binder<T>
992 where T: fmt::Display + for<'a> ty::Lift<'a>,
993 for<'a> <T as ty::Lift<'a>>::Lifted: fmt::Display + TypeFoldable<'a>
995 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
996 PrintCx::with_tls_tcx(|cx| cx.in_binder(cx.tcx.lift(self)
997 .expect("could not lift for printing")))
1001 define_print_multi! {
1003 ('tcx) ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
1004 ('tcx) ty::Binder<ty::TraitRef<'tcx>>,
1005 ('tcx) ty::Binder<ty::FnSig<'tcx>>,
1006 ('tcx) ty::Binder<ty::TraitPredicate<'tcx>>,
1007 ('tcx) ty::Binder<ty::SubtypePredicate<'tcx>>,
1008 ('tcx) ty::Binder<ty::ProjectionPredicate<'tcx>>,
1009 ('tcx) ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1010 ('tcx) ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>
1020 ('tcx) ty::TraitRef<'tcx>, (self, cx) {
1022 let _ = cx.print_def_path(
1030 let _ = cx.path_qualified(None, self.self_ty(), Some(*self), Namespace::TypeNS)?;
1036 ('tcx) ty::Ty<'tcx>, (self, cx) {
1039 Bool => p!(write("bool")),
1040 Char => p!(write("char")),
1041 Int(t) => p!(write("{}", t.ty_to_string())),
1042 Uint(t) => p!(write("{}", t.ty_to_string())),
1043 Float(t) => p!(write("{}", t.ty_to_string())),
1045 p!(write("*{} ", match tm.mutbl {
1046 hir::MutMutable => "mut",
1047 hir::MutImmutable => "const",
1051 Ref(r, ty, mutbl) => {
1053 if r.display_outputs_anything(cx) {
1054 p!(print_display(r), write(" "));
1056 p!(print(ty::TypeAndMut { ty, mutbl }))
1058 Never => p!(write("!")),
1061 let mut tys = tys.iter();
1062 if let Some(&ty) = tys.next() {
1063 p!(print(ty), write(","));
1064 if let Some(&ty) = tys.next() {
1065 p!(write(" "), print(ty));
1067 p!(write(", "), print(ty));
1073 FnDef(def_id, substs) => {
1074 let sig = cx.tcx.fn_sig(def_id).subst(cx.tcx, substs);
1075 p!(print(sig), write(" {{"));
1076 let _ = cx.print_def_path(
1084 FnPtr(ref bare_fn) => {
1087 Infer(infer_ty) => p!(write("{}", infer_ty)),
1088 Error => p!(write("[type error]")),
1089 Param(ref param_ty) => p!(write("{}", param_ty)),
1090 Bound(debruijn, bound_ty) => {
1091 match bound_ty.kind {
1092 ty::BoundTyKind::Anon => {
1093 if debruijn == ty::INNERMOST {
1094 p!(write("^{}", bound_ty.var.index()))
1096 p!(write("^{}_{}", debruijn.index(), bound_ty.var.index()))
1100 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
1103 Adt(def, substs) => {
1104 let _ = cx.print_def_path(
1111 Dynamic(data, r) => {
1112 let print_r = r.display_outputs_anything(cx);
1116 p!(write("dyn "), print(data));
1118 p!(write(" + "), print_display(r), write(")"));
1121 Foreign(def_id) => {
1122 let _ = cx.print_def_path(
1129 Projection(ref data) => p!(print(data)),
1130 UnnormalizedProjection(ref data) => {
1131 p!(write("Unnormalized("));
1135 Placeholder(placeholder) => {
1136 p!(write("Placeholder({:?})", placeholder))
1138 Opaque(def_id, substs) => {
1139 if cx.config.is_verbose {
1140 p!(write("Opaque({:?}, {:?})", def_id, substs));
1144 let def_key = cx.tcx.def_key(def_id);
1145 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
1146 p!(write("{}", name));
1147 let mut substs = substs.iter();
1148 // FIXME(eddyb) print this with `print_def_path`.
1149 if let Some(first) = substs.next() {
1151 p!(write("{}", first));
1152 for subst in substs {
1153 p!(write(", {}", subst));
1159 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1160 // by looking up the projections associated with the def_id.
1161 let bounds = cx.tcx.predicates_of(def_id).instantiate(cx.tcx, substs);
1163 let mut first = true;
1164 let mut is_sized = false;
1166 for predicate in bounds.predicates {
1167 if let Some(trait_ref) = predicate.to_opt_poly_trait_ref() {
1168 // Don't print +Sized, but rather +?Sized if absent.
1169 if Some(trait_ref.def_id()) == cx.tcx.lang_items().sized_trait() {
1175 write("{}", if first { " " } else { "+" }),
1181 p!(write("{}?Sized", if first { " " } else { "+" }));
1183 p!(write(" Sized"));
1186 Str => p!(write("str")),
1187 Generator(did, substs, movability) => {
1188 let upvar_tys = substs.upvar_tys(did, cx.tcx);
1189 let witness = substs.witness(did, cx.tcx);
1190 if movability == hir::GeneratorMovability::Movable {
1191 p!(write("[generator"));
1193 p!(write("[static generator"));
1196 // FIXME(eddyb) should use `def_span`.
1197 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(did) {
1198 p!(write("@{:?}", cx.tcx.hir().span_by_hir_id(hir_id)));
1200 cx.tcx.with_freevars(hir_id, |freevars| {
1201 for (freevar, upvar_ty) in freevars.iter().zip(upvar_tys) {
1205 cx.tcx.hir().name(freevar.var_id())),
1212 // cross-crate closure types should only be
1213 // visible in codegen bug reports, I imagine.
1214 p!(write("@{:?}", did));
1216 for (index, upvar_ty) in upvar_tys.enumerate() {
1218 write("{}{}:", sep, index),
1224 p!(write(" "), print(witness), write("]"))
1226 GeneratorWitness(types) => {
1227 cx.in_binder(&types)?
1229 Closure(did, substs) => {
1230 let upvar_tys = substs.upvar_tys(did, cx.tcx);
1231 p!(write("[closure"));
1233 // FIXME(eddyb) should use `def_span`.
1234 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(did) {
1235 if cx.tcx.sess.opts.debugging_opts.span_free_formats {
1236 p!(write("@{:?}", hir_id));
1238 p!(write("@{:?}", cx.tcx.hir().span_by_hir_id(hir_id)));
1241 cx.tcx.with_freevars(hir_id, |freevars| {
1242 for (freevar, upvar_ty) in freevars.iter().zip(upvar_tys) {
1246 cx.tcx.hir().name(freevar.var_id())),
1253 // cross-crate closure types should only be
1254 // visible in codegen bug reports, I imagine.
1255 p!(write("@{:?}", did));
1257 for (index, upvar_ty) in upvar_tys.enumerate() {
1259 write("{}{}:", sep, index),
1265 if cx.config.is_verbose {
1267 " closure_kind_ty={:?} closure_sig_ty={:?}",
1268 substs.closure_kind_ty(did, cx.tcx),
1269 substs.closure_sig_ty(did, cx.tcx)
1276 p!(write("["), print(ty), write("; "));
1278 ty::LazyConst::Unevaluated(_def_id, _substs) => {
1281 ty::LazyConst::Evaluated(c) => {
1283 ConstValue::Infer(..) => p!(write("_")),
1284 ConstValue::Param(ParamConst { name, .. }) =>
1285 p!(write("{}", name)),
1286 _ => p!(write("{}", c.unwrap_usize(cx.tcx))),
1293 p!(write("["), print(ty), write("]"))
1298 p!(print_display(self))
1304 ('tcx) ConstValue<'tcx>, (self, cx) {
1307 ConstValue::Infer(..) => p!(write("_")),
1308 ConstValue::Param(ParamConst { name, .. }) => p!(write("{}", name)),
1309 _ => p!(write("{:?}", self)),
1316 ('tcx) ty::Const<'tcx>, (self, cx) {
1318 p!(write("{} : {}", self.val, self.ty))
1324 ('tcx) ty::LazyConst<'tcx>, (self, cx) {
1327 // FIXME(const_generics) this should print at least the type.
1328 ty::LazyConst::Unevaluated(..) => p!(write("_ : _")),
1329 ty::LazyConst::Evaluated(c) => p!(write("{}", c)),
1336 () ty::ParamTy, (self, cx) {
1338 p!(write("{}", self.name))
1341 p!(write("{}/#{}", self.name, self.idx))
1347 () ty::ParamConst, (self, cx) {
1349 p!(write("{}", self.name))
1352 p!(write("{}/#{}", self.name, self.index))
1357 // Similar problem to `Binder<T>`, can't define a generic impl.
1358 define_print_multi! {
1360 ('tcx) ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1361 ('tcx) ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1365 p!(print(self.0), write(" : "), print(self.1))
1371 ('tcx) ty::SubtypePredicate<'tcx>, (self, cx) {
1373 p!(print(self.a), write(" <: "), print(self.b))
1379 ('tcx) ty::TraitPredicate<'tcx>, (self, cx) {
1381 p!(write("TraitPredicate({:?})",
1385 p!(print(self.trait_ref.self_ty()), write(": "), print(self.trait_ref))
1391 ('tcx) ty::ProjectionPredicate<'tcx>, (self, cx) {
1394 write("ProjectionPredicate("),
1395 print(self.projection_ty),
1401 p!(print(self.projection_ty), write(" == "), print(self.ty))
1407 ('tcx) ty::ProjectionTy<'tcx>, (self, cx) {
1409 let _ = cx.print_def_path(
1420 () ty::ClosureKind, (self, cx) {
1423 ty::ClosureKind::Fn => p!(write("Fn")),
1424 ty::ClosureKind::FnMut => p!(write("FnMut")),
1425 ty::ClosureKind::FnOnce => p!(write("FnOnce")),
1432 ('tcx) ty::Predicate<'tcx>, (self, cx) {
1435 ty::Predicate::Trait(ref data) => p!(print(data)),
1436 ty::Predicate::Subtype(ref predicate) => p!(print(predicate)),
1437 ty::Predicate::RegionOutlives(ref predicate) => p!(print(predicate)),
1438 ty::Predicate::TypeOutlives(ref predicate) => p!(print(predicate)),
1439 ty::Predicate::Projection(ref predicate) => p!(print(predicate)),
1440 ty::Predicate::WellFormed(ty) => p!(print(ty), write(" well-formed")),
1441 ty::Predicate::ObjectSafe(trait_def_id) => {
1442 p!(write("the trait `"));
1443 let _ = cx.print_def_path(
1449 p!(write("` is object-safe"))
1451 ty::Predicate::ClosureKind(closure_def_id, _closure_substs, kind) => {
1452 p!(write("the closure `"));
1453 let _ = cx.print_def_path(
1459 p!(write("` implements the trait `{}`", kind))
1461 ty::Predicate::ConstEvaluatable(def_id, substs) => {
1462 p!(write("the constant `"));
1463 let _ = cx.print_def_path(
1469 p!(write("` can be evaluated"))
1475 ty::Predicate::Trait(ref a) => p!(print(a)),
1476 ty::Predicate::Subtype(ref pair) => p!(print(pair)),
1477 ty::Predicate::RegionOutlives(ref pair) => p!(print(pair)),
1478 ty::Predicate::TypeOutlives(ref pair) => p!(print(pair)),
1479 ty::Predicate::Projection(ref pair) => p!(print(pair)),
1480 ty::Predicate::WellFormed(ty) => p!(print(ty)),
1481 ty::Predicate::ObjectSafe(trait_def_id) => {
1482 p!(write("ObjectSafe({:?})", trait_def_id))
1484 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
1485 p!(write("ClosureKind({:?}, {:?}, {:?})",
1486 closure_def_id, closure_substs, kind))
1488 ty::Predicate::ConstEvaluatable(def_id, substs) => {
1489 p!(write("ConstEvaluatable({:?}, {:?})", def_id, substs))
1497 ('tcx) Kind<'tcx>, (self, cx) {
1499 match self.unpack() {
1500 UnpackedKind::Lifetime(lt) => p!(print(lt)),
1501 UnpackedKind::Type(ty) => p!(print(ty)),
1502 UnpackedKind::Const(ct) => p!(print(ct)),
1506 match self.unpack() {
1507 UnpackedKind::Lifetime(lt) => p!(print(lt)),
1508 UnpackedKind::Type(ty) => p!(print(ty)),
1509 UnpackedKind::Const(ct) => p!(print(ct)),