1 use crate::hir::def_id::DefId;
2 use crate::hir::map::definitions::DefPathData;
3 use crate::middle::region;
4 use crate::ty::subst::{self, Subst, SubstsRef};
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, Ty, TypeFoldable, GenericParamCount, GenericParamDefKind, ParamConst};
12 use crate::ty::print::{PrintCx, Print};
13 use crate::mir::interpret::ConstValue;
19 use rustc_target::spec::abi::Abi;
20 use syntax::ast::CRATE_NODE_ID;
21 use syntax::symbol::{Symbol, InternedString};
24 /// The "region highlights" are used to control region printing during
25 /// specific error messages. When a "region highlight" is enabled, it
26 /// gives an alternate way to print specific regions. For now, we
27 /// always print those regions using a number, so something like "`'0`".
29 /// Regions not selected by the region highlight mode are presently
31 #[derive(Copy, Clone, Default)]
32 pub struct RegionHighlightMode {
33 /// If enabled, when we see the selected region, use "`'N`"
34 /// instead of the ordinary behavior.
35 highlight_regions: [Option<(ty::RegionKind, usize)>; 3],
37 /// If enabled, when printing a "free region" that originated from
38 /// the given `ty::BoundRegion`, print it as "`'1`". Free regions that would ordinarily
39 /// have names print as normal.
41 /// This is used when you have a signature like `fn foo(x: &u32,
42 /// y: &'a u32)` and we want to give a name to the region of the
44 highlight_bound_region: Option<(ty::BoundRegion, usize)>,
48 /// Mechanism for highlighting of specific regions for display in NLL region inference errors.
49 /// Contains region to highlight and counter for number to use when highlighting.
50 static REGION_HIGHLIGHT_MODE: Cell<RegionHighlightMode> =
51 Cell::new(RegionHighlightMode::default())
54 impl RegionHighlightMode {
55 /// Reads and returns the current region highlight settings (accesses thread-local state).
56 pub fn get() -> Self {
57 REGION_HIGHLIGHT_MODE.with(|c| c.get())
60 // Internal helper to update current settings during the execution of `op`.
64 op: impl FnOnce() -> R,
66 REGION_HIGHLIGHT_MODE.with(|c| {
74 /// If `region` and `number` are both `Some`, invokes
75 /// `highlighting_region`; otherwise, just invokes `op` directly.
76 pub fn maybe_highlighting_region<R>(
77 region: Option<ty::Region<'_>>,
78 number: Option<usize>,
79 op: impl FnOnce() -> R,
81 if let Some(k) = region {
82 if let Some(n) = number {
83 return Self::highlighting_region(k, n, op);
90 /// During the execution of `op`, highlights the region inference
91 /// variable `vid` as `'N`. We can only highlight one region `vid`
93 pub fn highlighting_region<R>(
94 region: ty::Region<'_>,
96 op: impl FnOnce() -> R,
98 let old_mode = Self::get();
99 let mut new_mode = old_mode;
100 let first_avail_slot = new_mode.highlight_regions.iter_mut()
101 .filter(|s| s.is_none())
105 "can only highlight {} placeholders at a time",
106 old_mode.highlight_regions.len(),
109 *first_avail_slot = Some((*region, number));
110 Self::set(old_mode, new_mode, op)
113 /// Convenience wrapper for `highlighting_region`.
114 pub fn highlighting_region_vid<R>(
117 op: impl FnOnce() -> R,
119 Self::highlighting_region(&ty::ReVar(vid), number, op)
122 /// Returns `true` if any placeholders are highlighted, and `false` otherwise.
123 fn any_region_vids_highlighted(&self) -> bool {
128 Some((ty::ReVar(_), _)) => true,
133 /// Returns `Some(n)` with the number to use for the given region, if any.
134 fn region_highlighted(&self, region: ty::Region<'_>) -> Option<usize> {
138 .filter_map(|h| match h {
139 Some((r, n)) if r == region => Some(*n),
145 /// During the execution of `op`, highlight the given bound
146 /// region. We can only highlight one bound region at a time. See
147 /// the field `highlight_bound_region` for more detailed notes.
148 pub fn highlighting_bound_region<R>(
151 op: impl FnOnce() -> R,
153 let old_mode = Self::get();
154 assert!(old_mode.highlight_bound_region.is_none());
158 highlight_bound_region: Some((br, number)),
165 /// Returns `true` if any placeholders are highlighted, and `false` otherwise.
166 pub fn any_placeholders_highlighted(&self) -> bool {
171 Some((ty::RePlaceholder(_), _)) => true,
176 /// Returns `Some(N)` if the placeholder `p` is highlighted to print as "`'N`".
177 pub fn placeholder_highlight(&self, p: ty::PlaceholderRegion) -> Option<usize> {
178 self.region_highlighted(&ty::RePlaceholder(p))
182 macro_rules! gen_display_debug_body {
184 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185 PrintCx::with(|mut cx| $with(self, f, &mut cx))
189 macro_rules! gen_display_debug {
190 ( ($($x:tt)+) $target:ty, display yes ) => {
191 impl<$($x)+> fmt::Display for $target {
192 gen_display_debug_body! { Print::print_display }
195 ( () $target:ty, display yes ) => {
196 impl fmt::Display for $target {
197 gen_display_debug_body! { Print::print_display }
200 ( ($($x:tt)+) $target:ty, debug yes ) => {
201 impl<$($x)+> fmt::Debug for $target {
202 gen_display_debug_body! { Print::print_debug }
205 ( () $target:ty, debug yes ) => {
206 impl fmt::Debug for $target {
207 gen_display_debug_body! { Print::print_debug }
210 ( $generic:tt $target:ty, $t:ident no ) => {};
212 macro_rules! gen_print_impl {
213 ( ($($x:tt)+) $target:ty, ($self:ident, $f:ident, $cx:ident) $disp:block $dbg:block ) => {
214 impl<$($x)+> Print<'tcx> for $target {
215 fn print<F: fmt::Write>(
218 $cx: &mut PrintCx<'_, '_, '_>,
225 ( () $target:ty, ($self:ident, $f:ident, $cx:ident) $disp:block $dbg:block ) => {
226 impl Print<'tcx> for $target {
227 fn print<F: fmt::Write>(
230 $cx: &mut PrintCx<'_, '_, '_>,
237 ( $generic:tt $target:ty,
238 $vars:tt $gendisp:ident $disp:block $gendbg:ident $dbg:block ) => {
239 gen_print_impl! { $generic $target, $vars $disp $dbg }
240 gen_display_debug! { $generic $target, display $gendisp }
241 gen_display_debug! { $generic $target, debug $gendbg }
244 macro_rules! define_print {
245 ( $generic:tt $target:ty,
246 $vars:tt { display $disp:block debug $dbg:block } ) => {
247 gen_print_impl! { $generic $target, $vars yes $disp yes $dbg }
249 ( $generic:tt $target:ty,
250 $vars:tt { debug $dbg:block display $disp:block } ) => {
251 gen_print_impl! { $generic $target, $vars yes $disp yes $dbg }
253 ( $generic:tt $target:ty,
254 $vars:tt { debug $dbg:block } ) => {
255 gen_print_impl! { $generic $target, $vars no {
256 bug!(concat!("display not implemented for ", stringify!($target)));
259 ( $generic:tt $target:ty,
260 ($self:ident, $f:ident, $cx:ident) { display $disp:block } ) => {
261 gen_print_impl! { $generic $target, ($self, $f, $cx) yes $disp no {
262 write!($f, "{:?}", $self)
266 macro_rules! define_print_multi {
267 ( [ $($generic:tt $target:ty),* ] $vars:tt $def:tt ) => {
268 $(define_print! { $generic $target, $vars $def })*
271 macro_rules! print_inner {
272 ( $f:expr, $cx:expr, write ($($data:expr),+) ) => {
273 write!($f, $($data),+)
275 ( $f:expr, $cx:expr, $kind:ident ($data:expr) ) => {
280 ( $f:expr, $cx:expr $(, $kind:ident $data:tt)+ ) => {
281 Ok(())$(.and_then(|_| print_inner!($f, $cx, $kind $data)))+
285 impl PrintCx<'a, 'gcx, 'tcx> {
286 fn fn_sig<F: fmt::Write>(&mut self,
293 let mut inputs = inputs.iter();
294 if let Some(&ty) = inputs.next() {
295 print!(f, self, print_display(ty))?;
297 print!(f, self, write(", "), print_display(ty))?;
304 if !output.is_unit() {
305 print!(f, self, write(" -> "), print_display(output))?;
311 fn parameterized<F: fmt::Write>(&mut self,
313 substs: SubstsRef<'_>,
315 projections: &[ty::ProjectionPredicate<'_>])
317 let key = self.tcx.def_key(did);
319 let verbose = self.is_verbose;
320 let mut num_supplied_defaults = 0;
322 let mut own_counts: GenericParamCount = Default::default();
323 let mut is_value_path = false;
324 let mut item_name = Some(key.disambiguated_data.data.as_interned_str());
325 let mut path_def_id = did;
327 // Unfortunately, some kinds of items (e.g., closures) don't have
328 // generics. So walk back up the find the closest parent that DOES
330 let mut item_def_id = did;
332 let key = self.tcx.def_key(item_def_id);
333 match key.disambiguated_data.data {
334 DefPathData::AssocTypeInTrait(_) |
335 DefPathData::AssocTypeInImpl(_) |
336 DefPathData::AssocExistentialInImpl(_) |
337 DefPathData::Trait(_) |
338 DefPathData::TraitAlias(_) |
340 DefPathData::TypeNs(_) => {
343 DefPathData::ValueNs(_) |
344 DefPathData::EnumVariant(_) => {
345 is_value_path = true;
348 DefPathData::CrateRoot |
350 DefPathData::Module(_) |
351 DefPathData::MacroDef(_) |
352 DefPathData::ClosureExpr |
353 DefPathData::TypeParam(_) |
354 DefPathData::LifetimeParam(_) |
355 DefPathData::ConstParam(_) |
356 DefPathData::Field(_) |
357 DefPathData::StructCtor |
358 DefPathData::AnonConst |
359 DefPathData::ImplTrait |
360 DefPathData::GlobalMetaData(_) => {
361 // if we're making a symbol for something, there ought
362 // to be a value or type-def or something in there
364 item_def_id.index = key.parent.unwrap_or_else(|| {
365 bug!("finding type for {:?}, encountered def-id {:?} with no \
366 parent", did, item_def_id);
371 let mut generics = self.tcx.generics_of(item_def_id);
372 let child_own_counts = generics.own_counts();
373 has_self = generics.has_self;
375 let mut child_types = 0;
376 if let Some(def_id) = generics.parent {
378 assert!(is_value_path);
379 child_types = child_own_counts.types;
380 generics = self.tcx.generics_of(def_id);
381 own_counts = generics.own_counts();
384 print!(f, self, write("<"), print_display(substs.type_at(0)), write(" as "))?;
387 path_def_id = def_id;
393 assert_eq!(has_self, false);
396 own_counts = child_own_counts;
401 let mut type_params =
402 generics.params.iter().rev().filter_map(|param| match param.kind {
403 GenericParamDefKind::Lifetime => None,
404 GenericParamDefKind::Type { has_default, .. } => {
405 Some((param.def_id, has_default))
407 GenericParamDefKind::Const => None, // FIXME(const_generics:defaults)
410 let has_default = type_params.peek().map(|(_, has_default)| has_default);
411 *has_default.unwrap_or(&false)
414 let substs = self.tcx.lift(&substs).expect("could not lift for printing");
415 let types = substs.types().rev().skip(child_types);
416 for ((def_id, has_default), actual) in type_params.zip(types) {
420 if self.tcx.type_of(def_id).subst(self.tcx, substs) != actual {
423 num_supplied_defaults += 1;
428 print!(f, self, write("{}", self.tcx.item_path_str(path_def_id)))?;
429 let fn_trait_kind = self.tcx.lang_items().fn_trait_kind(path_def_id);
431 if !verbose && fn_trait_kind.is_some() && projections.len() == 1 {
432 let projection_ty = projections[0].ty;
433 if let Tuple(ref args) = substs.type_at(1).sty {
434 return self.fn_sig(f, args, false, projection_ty);
438 let empty = Cell::new(true);
439 let start_or_continue = |f: &mut F, start: &str, cont: &str| {
442 write!(f, "{}", start)
444 write!(f, "{}", cont)
448 let print_regions = |f: &mut F, start: &str, skip, count| {
449 // Don't print any regions if they're all erased.
450 let regions = || substs.regions().skip(skip).take(count);
451 if regions().all(|r: ty::Region<'_>| *r == ty::ReErased) {
455 for region in regions() {
456 let region: ty::Region<'_> = region;
457 start_or_continue(f, start, ", ")?;
459 write!(f, "{:?}", region)?;
461 let s = region.to_string();
463 // This happens when the value of the region
464 // parameter is not easily serialized. This may be
465 // because the user omitted it in the first place,
466 // or because it refers to some block in the code,
467 // etc. I'm not sure how best to serialize this.
478 print_regions(f, "<", 0, own_counts.lifetimes)?;
480 let tps = substs.types()
481 .take(own_counts.types - num_supplied_defaults)
482 .skip(has_self as usize);
485 start_or_continue(f, "<", ", ")?;
486 ty.print_display(f, self)?;
489 for projection in projections {
490 start_or_continue(f, "<", ", ")?;
493 self.tcx.associated_item(projection.projection_ty.item_def_id).ident),
494 print_display(projection.ty))?;
497 // FIXME(const_generics::defaults)
498 let consts = substs.consts();
501 start_or_continue(f, "<", ", ")?;
502 ct.print_display(f, self)?;
505 start_or_continue(f, "", ">")?;
507 // For values, also print their name and type parameters.
515 if let Some(item_name) = item_name {
516 write!(f, "::{}", item_name)?;
519 print_regions(f, "::<", own_counts.lifetimes, usize::MAX)?;
521 // FIXME: consider being smart with defaults here too
522 for ty in substs.types().skip(own_counts.types) {
523 start_or_continue(f, "::<", ", ")?;
524 ty.print_display(f, self)?;
527 start_or_continue(f, "", ">")?;
533 fn in_binder<T, F>(&mut self, f: &mut F, value: ty::Binder<T>) -> fmt::Result
534 where T: Print<'tcx> + TypeFoldable<'tcx>, F: fmt::Write
536 fn name_by_region_index(index: usize) -> InternedString {
538 0 => Symbol::intern("'r"),
539 1 => Symbol::intern("'s"),
540 i => Symbol::intern(&format!("'t{}", i-2)),
544 // Replace any anonymous late-bound regions with named
545 // variants, using gensym'd identifiers, so that we can
546 // clearly differentiate between named and unnamed regions in
547 // the output. We'll probably want to tweak this over time to
548 // decide just how much information to give.
549 if self.binder_depth == 0 {
550 self.prepare_late_bound_region_info(&value);
553 let mut empty = true;
554 let mut start_or_continue = |f: &mut F, start: &str, cont: &str| {
557 write!(f, "{}", start)
559 write!(f, "{}", cont)
563 let old_region_index = self.region_index;
564 let mut region_index = old_region_index;
565 let new_value = self.tcx.replace_late_bound_regions(&value, |br| {
566 let _ = start_or_continue(f, "for<", ", ");
568 ty::BrNamed(_, name) => {
569 let _ = write!(f, "{}", name);
576 let name = name_by_region_index(region_index);
578 if !self.is_name_used(&name) {
582 let _ = write!(f, "{}", name);
583 ty::BrNamed(self.tcx.hir().local_def_id(CRATE_NODE_ID), name)
586 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
588 start_or_continue(f, "", "> ")?;
590 // Push current state to gcx, and restore after writing new_value.
591 self.binder_depth += 1;
592 self.region_index = region_index;
593 let result = new_value.print_display(f, self);
594 self.region_index = old_region_index;
595 self.binder_depth -= 1;
599 fn is_name_used(&self, name: &InternedString) -> bool {
600 match self.used_region_names {
601 Some(ref names) => names.contains(name),
607 pub fn parameterized<F: fmt::Write>(f: &mut F,
608 substs: SubstsRef<'_>,
610 projections: &[ty::ProjectionPredicate<'_>])
612 PrintCx::with(|mut cx| cx.parameterized(f, substs, did, projections))
615 impl<'a, 'tcx, T: Print<'tcx>> Print<'tcx> for &'a T {
616 fn print<F: fmt::Write>(&self, f: &mut F, cx: &mut PrintCx<'_, '_, '_>) -> fmt::Result {
622 ('tcx) &'tcx ty::List<ty::ExistentialPredicate<'tcx>>, (self, f, cx) {
624 // Generate the main trait ref, including associated types.
626 // Use a type that can't appear in defaults of type parameters.
627 let dummy_self = cx.tcx.mk_infer(ty::FreshTy(0));
628 let mut first = true;
630 if let Some(principal) = self.principal() {
631 let principal = cx.tcx
633 .expect("could not lift for printing")
634 .with_self_ty(cx.tcx, dummy_self);
635 let projections = self.projection_bounds().map(|p| {
637 .expect("could not lift for printing")
638 .with_self_ty(cx.tcx, dummy_self)
639 }).collect::<Vec<_>>();
640 cx.parameterized(f, principal.substs, principal.def_id, &projections)?;
645 let mut auto_traits: Vec<_> = self.auto_traits().map(|did| {
646 cx.tcx.item_path_str(did)
649 // The auto traits come ordered by `DefPathHash`. While
650 // `DefPathHash` is *stable* in the sense that it depends on
651 // neither the host nor the phase of the moon, it depends
652 // "pseudorandomly" on the compiler version and the target.
654 // To avoid that causing instabilities in compiletest
655 // output, sort the auto-traits alphabetically.
658 for auto_trait in auto_traits {
664 write!(f, "{}", auto_trait)?;
672 impl fmt::Debug for ty::GenericParamDef {
673 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
674 let type_name = match self.kind {
675 ty::GenericParamDefKind::Lifetime => "Lifetime",
676 ty::GenericParamDefKind::Type { .. } => "Type",
677 ty::GenericParamDefKind::Const => "Const",
679 write!(f, "{}({}, {:?}, {})",
687 impl fmt::Debug for ty::TraitDef {
688 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
690 write!(f, "{}", cx.tcx.item_path_str(self.def_id))
695 impl fmt::Debug for ty::AdtDef {
696 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
698 write!(f, "{}", cx.tcx.item_path_str(self.did))
703 impl<'tcx> fmt::Debug for ty::ClosureUpvar<'tcx> {
704 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
705 write!(f, "ClosureUpvar({:?},{:?})",
711 impl fmt::Debug for ty::UpvarId {
712 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
713 write!(f, "UpvarId({:?};`{}`;{:?})",
714 self.var_path.hir_id,
716 cx.tcx.hir().name_by_hir_id(self.var_path.hir_id)
718 self.closure_expr_id)
722 impl<'tcx> fmt::Debug for ty::UpvarBorrow<'tcx> {
723 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
724 write!(f, "UpvarBorrow({:?}, {:?})",
725 self.kind, self.region)
730 ('tcx) &'tcx ty::List<Ty<'tcx>>, (self, f, cx) {
733 let mut tys = self.iter();
734 if let Some(&ty) = tys.next() {
735 print!(f, cx, print(ty))?;
737 print!(f, cx, write(", "), print(ty))?;
746 ('tcx) ty::TypeAndMut<'tcx>, (self, f, cx) {
749 write("{}", if self.mutbl == hir::MutMutable { "mut " } else { "" }),
756 ('tcx) ty::ExistentialTraitRef<'tcx>, (self, f, cx) {
758 cx.parameterized(f, self.substs, self.def_id, &[])
761 let dummy_self = cx.tcx.mk_infer(ty::FreshTy(0));
763 let trait_ref = *cx.tcx.lift(&ty::Binder::bind(*self))
764 .expect("could not lift for printing")
765 .with_self_ty(cx.tcx, dummy_self).skip_binder();
766 cx.parameterized(f, trait_ref.substs, trait_ref.def_id, &[])
772 ('tcx) ty::adjustment::Adjustment<'tcx>, (self, f, cx) {
774 print!(f, cx, write("{:?} -> ", self.kind), print(self.target))
780 () ty::BoundRegion, (self, f, cx) {
783 return self.print_debug(f, cx);
786 if let Some((region, counter)) = RegionHighlightMode::get().highlight_bound_region {
789 BrNamed(_, name) => write!(f, "{}", name),
790 BrAnon(_) | BrFresh(_) | BrEnv => write!(f, "'{}", counter)
796 BrNamed(_, name) => write!(f, "{}", name),
797 BrAnon(_) | BrFresh(_) | BrEnv => Ok(())
802 BrAnon(n) => write!(f, "BrAnon({:?})", n),
803 BrFresh(n) => write!(f, "BrFresh({:?})", n),
804 BrNamed(did, name) => {
805 write!(f, "BrNamed({:?}:{:?}, {})",
806 did.krate, did.index, name)
808 BrEnv => write!(f, "BrEnv"),
815 () ty::PlaceholderRegion, (self, f, cx) {
818 return self.print_debug(f, cx);
821 let highlight = RegionHighlightMode::get();
822 if let Some(counter) = highlight.placeholder_highlight(*self) {
823 write!(f, "'{}", counter)
824 } else if highlight.any_placeholders_highlighted() {
827 write!(f, "{}", self.name)
834 () ty::RegionKind, (self, f, cx) {
837 return self.print_debug(f, cx);
840 // Watch out for region highlights.
841 if let Some(n) = RegionHighlightMode::get().region_highlighted(self) {
842 return write!(f, "'{:?}", n);
845 // These printouts are concise. They do not contain all the information
846 // the user might want to diagnose an error, but there is basically no way
847 // to fit that into a short string. Hence the recommendation to use
848 // `explain_region()` or `note_and_explain_region()`.
850 ty::ReEarlyBound(ref data) => {
851 write!(f, "{}", data.name)
853 ty::ReLateBound(_, br) |
854 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) => {
857 ty::RePlaceholder(p) => {
860 ty::ReScope(scope) if cx.identify_regions => {
862 region::ScopeData::Node =>
863 write!(f, "'{}s", scope.item_local_id().as_usize()),
864 region::ScopeData::CallSite =>
865 write!(f, "'{}cs", scope.item_local_id().as_usize()),
866 region::ScopeData::Arguments =>
867 write!(f, "'{}as", scope.item_local_id().as_usize()),
868 region::ScopeData::Destruction =>
869 write!(f, "'{}ds", scope.item_local_id().as_usize()),
870 region::ScopeData::Remainder(first_statement_index) => write!(
873 scope.item_local_id().as_usize(),
874 first_statement_index.index()
878 ty::ReVar(region_vid) => {
879 if RegionHighlightMode::get().any_region_vids_highlighted() {
880 write!(f, "{:?}", region_vid)
881 } else if cx.identify_regions {
882 write!(f, "'{}rv", region_vid.index())
888 ty::ReErased => Ok(()),
889 ty::ReStatic => write!(f, "'static"),
890 ty::ReEmpty => write!(f, "'<empty>"),
892 // The user should never encounter these in unsubstituted form.
893 ty::ReClosureBound(vid) => write!(f, "{:?}", vid),
898 ty::ReEarlyBound(ref data) => {
899 write!(f, "ReEarlyBound({}, {})",
904 ty::ReClosureBound(ref vid) => {
905 write!(f, "ReClosureBound({:?})",
909 ty::ReLateBound(binder_id, ref bound_region) => {
910 write!(f, "ReLateBound({:?}, {:?})",
915 ty::ReFree(ref fr) => write!(f, "{:?}", fr),
918 write!(f, "ReScope({:?})", id)
921 ty::ReStatic => write!(f, "ReStatic"),
923 ty::ReVar(ref vid) => {
924 write!(f, "{:?}", vid)
927 ty::RePlaceholder(placeholder) => {
928 write!(f, "RePlaceholder({:?})", placeholder)
931 ty::ReEmpty => write!(f, "ReEmpty"),
933 ty::ReErased => write!(f, "ReErased")
940 () ty::FreeRegion, (self, f, cx) {
942 write!(f, "ReFree({:?}, {:?})", self.scope, self.bound_region)
948 () ty::Variance, (self, f, cx) {
950 f.write_str(match *self {
951 ty::Covariant => "+",
952 ty::Contravariant => "-",
953 ty::Invariant => "o",
954 ty::Bivariant => "*",
961 ('tcx) ty::GenericPredicates<'tcx>, (self, f, cx) {
963 write!(f, "GenericPredicates({:?})", self.predicates)
969 ('tcx) ty::InstantiatedPredicates<'tcx>, (self, f, cx) {
971 write!(f, "InstantiatedPredicates({:?})", self.predicates)
977 ('tcx) ty::FnSig<'tcx>, (self, f, cx) {
979 if self.unsafety == hir::Unsafety::Unsafe {
980 write!(f, "unsafe ")?;
983 if self.abi != Abi::Rust {
984 write!(f, "extern {} ", self.abi)?;
988 cx.fn_sig(f, self.inputs(), self.c_variadic, self.output())
991 write!(f, "({:?}; c_variadic: {})->{:?}", self.inputs(), self.c_variadic, self.output())
996 impl fmt::Debug for ty::TyVid {
997 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
998 write!(f, "_#{}t", self.index)
1002 impl<'tcx> fmt::Debug for ty::ConstVid<'tcx> {
1003 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1004 write!(f, "_#{}f", self.index)
1008 impl fmt::Debug for ty::IntVid {
1009 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1010 write!(f, "_#{}i", self.index)
1014 impl fmt::Debug for ty::FloatVid {
1015 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1016 write!(f, "_#{}f", self.index)
1020 impl fmt::Debug for ty::RegionVid {
1021 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1022 if let Some(counter) = RegionHighlightMode::get().region_highlighted(&ty::ReVar(*self)) {
1023 return write!(f, "'{:?}", counter);
1024 } else if RegionHighlightMode::get().any_region_vids_highlighted() {
1025 return write!(f, "'_");
1028 write!(f, "'_#{}r", self.index())
1033 () ty::InferTy, (self, f, cx) {
1036 print!(f, cx, print_debug(self))
1039 ty::TyVar(_) => write!(f, "_"),
1040 ty::IntVar(_) => write!(f, "{}", "{integer}"),
1041 ty::FloatVar(_) => write!(f, "{}", "{float}"),
1042 ty::FreshTy(v) => write!(f, "FreshTy({})", v),
1043 ty::FreshIntTy(v) => write!(f, "FreshIntTy({})", v),
1044 ty::FreshFloatTy(v) => write!(f, "FreshFloatTy({})", v)
1050 ty::TyVar(ref v) => write!(f, "{:?}", v),
1051 ty::IntVar(ref v) => write!(f, "{:?}", v),
1052 ty::FloatVar(ref v) => write!(f, "{:?}", v),
1053 ty::FreshTy(v) => write!(f, "FreshTy({:?})", v),
1054 ty::FreshIntTy(v) => write!(f, "FreshIntTy({:?})", v),
1055 ty::FreshFloatTy(v) => write!(f, "FreshFloatTy({:?})", v)
1061 impl fmt::Debug for ty::IntVarValue {
1062 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1064 ty::IntType(ref v) => v.fmt(f),
1065 ty::UintType(ref v) => v.fmt(f),
1070 impl fmt::Debug for ty::FloatVarValue {
1071 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1076 // The generic impl doesn't work yet because projections are not
1077 // normalized under HRTB.
1078 /*impl<T> fmt::Display for ty::Binder<T>
1079 where T: fmt::Display + for<'a> ty::Lift<'a>,
1080 for<'a> <T as ty::Lift<'a>>::Lifted: fmt::Display + TypeFoldable<'a>
1082 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1083 PrintCx::with(|cx| cx.in_binder(f, cx.tcx.lift(self)
1084 .expect("could not lift for printing")))
1088 define_print_multi! {
1090 ('tcx) ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
1091 ('tcx) ty::Binder<ty::TraitRef<'tcx>>,
1092 ('tcx) ty::Binder<ty::FnSig<'tcx>>,
1093 ('tcx) ty::Binder<ty::TraitPredicate<'tcx>>,
1094 ('tcx) ty::Binder<ty::SubtypePredicate<'tcx>>,
1095 ('tcx) ty::Binder<ty::ProjectionPredicate<'tcx>>,
1096 ('tcx) ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1097 ('tcx) ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>
1101 cx.in_binder(f, cx.tcx.lift(self)
1102 .expect("could not lift for printing"))
1108 ('tcx) ty::TraitRef<'tcx>, (self, f, cx) {
1110 cx.parameterized(f, self.substs, self.def_id, &[])
1113 // when printing out the debug representation, we don't need
1114 // to enumerate the `for<...>` etc because the debruijn index
1115 // tells you everything you need to know.
1118 print(self.self_ty()),
1120 cx.parameterized(f, self.substs, self.def_id, &[])?;
1127 ('tcx) ty::TyKind<'tcx>, (self, f, cx) {
1130 Bool => write!(f, "bool"),
1131 Char => write!(f, "char"),
1132 Int(t) => write!(f, "{}", t.ty_to_string()),
1133 Uint(t) => write!(f, "{}", t.ty_to_string()),
1134 Float(t) => write!(f, "{}", t.ty_to_string()),
1136 write!(f, "*{} ", match tm.mutbl {
1137 hir::MutMutable => "mut",
1138 hir::MutImmutable => "const",
1142 Ref(r, ty, mutbl) => {
1144 let s = r.print_to_string(cx);
1146 write!(f, "{}", s)?;
1151 ty::TypeAndMut { ty, mutbl }.print(f, cx)
1153 Never => write!(f, "!"),
1156 let mut tys = tys.iter();
1157 if let Some(&ty) = tys.next() {
1158 print!(f, cx, print(ty), write(","))?;
1159 if let Some(&ty) = tys.next() {
1160 print!(f, cx, write(" "), print(ty))?;
1162 print!(f, cx, write(", "), print(ty))?;
1168 FnDef(def_id, substs) => {
1169 let substs = cx.tcx.lift(&substs)
1170 .expect("could not lift for printing");
1171 let sig = cx.tcx.fn_sig(def_id).subst(cx.tcx, substs);
1172 print!(f, cx, print(sig), write(" {{"))?;
1173 cx.parameterized(f, substs, def_id, &[])?;
1176 FnPtr(ref bare_fn) => {
1177 bare_fn.print(f, cx)
1179 Infer(infer_ty) => write!(f, "{}", infer_ty),
1180 Error => write!(f, "[type error]"),
1181 Param(ref param_ty) => write!(f, "{}", param_ty),
1182 Bound(debruijn, bound_ty) => {
1183 match bound_ty.kind {
1184 ty::BoundTyKind::Anon => {
1185 if debruijn == ty::INNERMOST {
1186 write!(f, "^{}", bound_ty.var.index())
1188 write!(f, "^{}_{}", debruijn.index(), bound_ty.var.index())
1192 ty::BoundTyKind::Param(p) => write!(f, "{}", p),
1195 Adt(def, substs) => cx.parameterized(f, substs, def.did, &[]),
1196 Dynamic(data, r) => {
1197 let r = r.print_to_string(cx);
1204 write!(f, " + {})", r)
1209 Foreign(def_id) => parameterized(f, subst::InternalSubsts::empty(), def_id, &[]),
1210 Projection(ref data) => data.print(f, cx),
1211 UnnormalizedProjection(ref data) => {
1212 write!(f, "Unnormalized(")?;
1216 Placeholder(placeholder) => {
1217 write!(f, "Placeholder({:?})", placeholder)
1219 Opaque(def_id, substs) => {
1221 return write!(f, "Opaque({:?}, {:?})", def_id, substs);
1224 let def_key = cx.tcx.def_key(def_id);
1225 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
1226 write!(f, "{}", name)?;
1227 let mut substs = substs.iter();
1228 if let Some(first) = substs.next() {
1230 write!(f, "{}", first)?;
1231 for subst in substs {
1232 write!(f, ", {}", subst)?;
1238 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1239 // by looking up the projections associated with the def_id.
1240 let substs = cx.tcx.lift(&substs)
1241 .expect("could not lift for printing");
1242 let bounds = cx.tcx.predicates_of(def_id).instantiate(cx.tcx, substs);
1244 let mut first = true;
1245 let mut is_sized = false;
1247 for predicate in bounds.predicates {
1248 if let Some(trait_ref) = predicate.to_opt_poly_trait_ref() {
1249 // Don't print +Sized, but rather +?Sized if absent.
1250 if Some(trait_ref.def_id()) == cx.tcx.lang_items().sized_trait() {
1256 write("{}", if first { " " } else { "+" }),
1262 write!(f, "{}?Sized", if first { " " } else { "+" })?;
1264 write!(f, " Sized")?;
1268 Str => write!(f, "str"),
1269 Generator(did, substs, movability) => {
1270 let upvar_tys = substs.upvar_tys(did, cx.tcx);
1271 let witness = substs.witness(did, cx.tcx);
1272 if movability == hir::GeneratorMovability::Movable {
1273 write!(f, "[generator")?;
1275 write!(f, "[static generator")?;
1278 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(did) {
1279 write!(f, "@{:?}", cx.tcx.hir().span_by_hir_id(hir_id))?;
1281 cx.tcx.with_freevars(hir_id, |freevars| {
1282 for (freevar, upvar_ty) in freevars.iter().zip(upvar_tys) {
1286 cx.tcx.hir().name(freevar.var_id())),
1293 // cross-crate closure types should only be
1294 // visible in codegen bug reports, I imagine.
1295 write!(f, "@{:?}", did)?;
1297 for (index, upvar_ty) in upvar_tys.enumerate() {
1299 write("{}{}:", sep, index),
1305 print!(f, cx, write(" "), print(witness), write("]"))
1307 GeneratorWitness(types) => {
1308 cx.in_binder(f, cx.tcx.lift(&types)
1309 .expect("could not lift for printing"))
1311 Closure(did, substs) => {
1312 let upvar_tys = substs.upvar_tys(did, cx.tcx);
1313 write!(f, "[closure")?;
1315 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(did) {
1316 if cx.tcx.sess.opts.debugging_opts.span_free_formats {
1317 write!(f, "@{:?}", hir_id)?;
1319 write!(f, "@{:?}", cx.tcx.hir().span_by_hir_id(hir_id))?;
1322 cx.tcx.with_freevars(hir_id, |freevars| {
1323 for (freevar, upvar_ty) in freevars.iter().zip(upvar_tys) {
1327 cx.tcx.hir().name(freevar.var_id())),
1334 // cross-crate closure types should only be
1335 // visible in codegen bug reports, I imagine.
1336 write!(f, "@{:?}", did)?;
1338 for (index, upvar_ty) in upvar_tys.enumerate() {
1340 write("{}{}:", sep, index),
1349 " closure_kind_ty={:?} closure_sig_ty={:?}",
1350 substs.closure_kind_ty(did, tcx),
1351 substs.closure_sig_ty(did, tcx),
1358 print!(f, cx, write("["), print(ty), write("; "))?;
1360 ty::LazyConst::Unevaluated(_def_id, _substs) => {
1363 ty::LazyConst::Evaluated(c) => {
1365 ConstValue::Infer(..) => write!(f, "_")?,
1366 ConstValue::Param(ParamConst { name, .. }) =>
1367 write!(f, "{}", name)?,
1368 _ => write!(f, "{}", c.unwrap_usize(cx.tcx))?,
1375 print!(f, cx, write("["), print(ty), write("]"))
1383 ('tcx) ty::TyS<'tcx>, (self, f, cx) {
1385 self.sty.print(f, cx)
1388 self.sty.print_display(f, cx)
1394 ('tcx) ConstValue<'tcx>, (self, f, cx) {
1397 ConstValue::Infer(..) => write!(f, "_"),
1398 ConstValue::Param(ParamConst { name, .. }) => write!(f, "{}", name),
1399 _ => write!(f, "{:?}", self),
1406 ('tcx) ty::Const<'tcx>, (self, f, cx) {
1408 write!(f, "{} : {}", self.val, self.ty)
1414 ('tcx) ty::LazyConst<'tcx>, (self, f, cx) {
1417 ty::LazyConst::Unevaluated(..) => write!(f, "_ : _"),
1418 ty::LazyConst::Evaluated(c) => write!(f, "{}", c),
1425 () ty::ParamTy, (self, f, cx) {
1427 write!(f, "{}", self.name)
1430 write!(f, "{}/#{}", self.name, self.idx)
1436 () ty::ParamConst, (self, f, cx) {
1438 write!(f, "{}", self.name)
1441 write!(f, "{}/#{}", self.name, self.index)
1447 ('tcx, T: Print<'tcx> + fmt::Debug, U: Print<'tcx> + fmt::Debug) ty::OutlivesPredicate<T, U>,
1450 print!(f, cx, print(self.0), write(" : "), print(self.1))
1456 ('tcx) ty::SubtypePredicate<'tcx>, (self, f, cx) {
1458 print!(f, cx, print(self.a), write(" <: "), print(self.b))
1464 ('tcx) ty::TraitPredicate<'tcx>, (self, f, cx) {
1466 write!(f, "TraitPredicate({:?})",
1470 print!(f, cx, print(self.trait_ref.self_ty()), write(": "), print(self.trait_ref))
1476 ('tcx) ty::ProjectionPredicate<'tcx>, (self, f, cx) {
1479 write("ProjectionPredicate("),
1480 print(self.projection_ty),
1486 print!(f, cx, print(self.projection_ty), write(" == "), print(self.ty))
1492 ('tcx) ty::ProjectionTy<'tcx>, (self, f, cx) {
1494 // FIXME(tschottdorf): use something like
1495 // parameterized(f, self.substs, self.item_def_id, &[])
1496 // (which currently ICEs).
1497 let trait_ref = self.trait_ref(cx.tcx);
1498 let item_name = cx.tcx.associated_item(self.item_def_id).ident;
1499 print!(f, cx, print_debug(trait_ref), write("::{}", item_name))
1505 () ty::ClosureKind, (self, f, cx) {
1508 ty::ClosureKind::Fn => write!(f, "Fn"),
1509 ty::ClosureKind::FnMut => write!(f, "FnMut"),
1510 ty::ClosureKind::FnOnce => write!(f, "FnOnce"),
1517 ('tcx) ty::Predicate<'tcx>, (self, f, cx) {
1520 ty::Predicate::Trait(ref data) => data.print(f, cx),
1521 ty::Predicate::Subtype(ref predicate) => predicate.print(f, cx),
1522 ty::Predicate::RegionOutlives(ref predicate) => predicate.print(f, cx),
1523 ty::Predicate::TypeOutlives(ref predicate) => predicate.print(f, cx),
1524 ty::Predicate::Projection(ref predicate) => predicate.print(f, cx),
1525 ty::Predicate::WellFormed(ty) => print!(f, cx, print(ty), write(" well-formed")),
1526 ty::Predicate::ObjectSafe(trait_def_id) => {
1527 write!(f, "the trait `{}` is object-safe", cx.tcx.item_path_str(trait_def_id))
1529 ty::Predicate::ClosureKind(closure_def_id, _closure_substs, kind) => {
1530 write!(f, "the closure `{}` implements the trait `{}`",
1531 cx.tcx.item_path_str(closure_def_id), kind)
1533 ty::Predicate::ConstEvaluatable(def_id, substs) => {
1534 write!(f, "the constant `")?;
1535 cx.parameterized(f, substs, def_id, &[])?;
1536 write!(f, "` can be evaluated")
1542 ty::Predicate::Trait(ref a) => a.print(f, cx),
1543 ty::Predicate::Subtype(ref pair) => pair.print(f, cx),
1544 ty::Predicate::RegionOutlives(ref pair) => pair.print(f, cx),
1545 ty::Predicate::TypeOutlives(ref pair) => pair.print(f, cx),
1546 ty::Predicate::Projection(ref pair) => pair.print(f, cx),
1547 ty::Predicate::WellFormed(ty) => ty.print(f, cx),
1548 ty::Predicate::ObjectSafe(trait_def_id) => {
1549 write!(f, "ObjectSafe({:?})", trait_def_id)
1551 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
1552 write!(f, "ClosureKind({:?}, {:?}, {:?})", closure_def_id, closure_substs, kind)
1554 ty::Predicate::ConstEvaluatable(def_id, substs) => {
1555 write!(f, "ConstEvaluatable({:?}, {:?})", def_id, substs)