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, 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::{PrintCx, Print};
13 use crate::mir::interpret::ConstValue;
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(|mut cx| {
165 $with(&cx.tcx.lift(self).expect("could not lift for printing"), f, &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, $f:ident, $cx:ident) $disp:block $dbg:block ) => {
195 impl<$($x)+> Print<'tcx> for $target {
196 fn print<F: fmt::Write>(
199 $cx: &mut PrintCx<'_, '_, 'tcx>,
206 ( () $target:ty, ($self:ident, $f:ident, $cx:ident) $disp:block $dbg:block ) => {
207 impl Print<'tcx> for $target {
208 fn print<F: fmt::Write>(
211 $cx: &mut PrintCx<'_, '_, 'tcx>,
218 ( $generic:tt $target:ty,
219 $vars:tt $gendisp:ident $disp:block $gendbg:ident $dbg:block ) => {
220 gen_print_impl! { $generic $target, $vars $disp $dbg }
221 gen_display_debug! { $generic $target, display $gendisp }
222 gen_display_debug! { $generic $target, debug $gendbg }
225 macro_rules! define_print {
226 ( $generic:tt $target:ty,
227 $vars:tt { display $disp:block debug $dbg:block } ) => {
228 gen_print_impl! { $generic $target, $vars yes $disp yes $dbg }
230 ( $generic:tt $target:ty,
231 $vars:tt { debug $dbg:block display $disp:block } ) => {
232 gen_print_impl! { $generic $target, $vars yes $disp yes $dbg }
234 ( $generic:tt $target:ty,
235 $vars:tt { debug $dbg:block } ) => {
236 gen_print_impl! { $generic $target, $vars no {
237 bug!(concat!("display not implemented for ", stringify!($target)));
240 ( $generic:tt $target:ty,
241 ($self:ident, $f:ident, $cx:ident) { display $disp:block } ) => {
242 gen_print_impl! { $generic $target, ($self, $f, $cx) yes $disp no {
243 write!($f, "{:?}", $self)
247 macro_rules! define_print_multi {
248 ( [ $($generic:tt $target:ty),* ] $vars:tt $def:tt ) => {
249 $(define_print! { $generic $target, $vars $def })*
252 macro_rules! print_inner {
253 ( $f:expr, $cx:expr, write ($($data:expr),+) ) => {
254 write!($f, $($data),+)
256 ( $f:expr, $cx:expr, $kind:ident ($data:expr) ) => {
261 ( $f:expr, $cx:expr $(, $kind:ident $data:tt)+ ) => {
262 Ok(())$(.and_then(|_| print_inner!($f, $cx, $kind $data)))+
266 impl PrintCx<'a, 'gcx, 'tcx> {
267 fn fn_sig<F: fmt::Write>(&mut self,
274 let mut inputs = inputs.iter();
275 if let Some(&ty) = inputs.next() {
276 print!(f, self, print_display(ty))?;
278 print!(f, self, write(", "), print_display(ty))?;
285 if !output.is_unit() {
286 print!(f, self, write(" -> "), print_display(output))?;
292 fn parameterized<F: fmt::Write>(
296 substs: SubstsRef<'tcx>,
297 projections: impl Iterator<Item = ty::ExistentialProjection<'tcx>>,
299 let mut key = self.tcx.def_key(def_id);
300 let is_value_ns = match key.disambiguated_data.data {
301 DefPathData::ValueNs(_) |
302 DefPathData::EnumVariant(_) => true,
304 // Skip `StructCtor` so that `Struct::<T>` will be printed,
305 // instead of the less pretty `Struct<T>::{{constructor}}`.
306 DefPathData::StructCtor => {
307 def_id.index = key.parent.unwrap();
308 key = self.tcx.def_key(def_id);
315 let generics = self.tcx.generics_of(def_id);
317 if let Some(parent_def_id) = generics.parent {
318 assert_eq!(parent_def_id, DefId { index: key.parent.unwrap(), ..def_id });
320 let parent_generics = self.tcx.generics_of(parent_def_id);
321 let parent_has_own_self =
322 parent_generics.has_self && parent_generics.parent_count == 0;
323 if parent_has_own_self {
324 print!(f, self, write("<"), print_display(substs.type_at(0)), write(" as "))?;
326 self.parameterized(f, parent_def_id, substs, iter::empty())?;
327 if parent_has_own_self {
331 write!(f, "::{}", key.disambiguated_data.data.as_interned_str())?;
333 // Try to print `impl`s more like how you'd refer to their associated items.
334 if let DefPathData::Impl = key.disambiguated_data.data {
335 if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
336 // HACK(eddyb) this is in lieu of more specific disambiguation.
337 print!(f, self, write("{}", self.tcx.item_path_str(def_id)))?;
339 let trait_ref = trait_ref.subst(self.tcx, substs);
340 print!(f, self, print_debug(trait_ref))?;
342 let self_ty = self.tcx.type_of(def_id).subst(self.tcx, substs);
343 // FIXME(eddyb) omit the <> where possible.
344 print!(f, self, write("<"), print(self_ty), write(">"))?;
349 print!(f, self, write("{}", self.tcx.item_path_str(def_id)))?;
352 let mut empty = true;
353 let mut start_or_continue = |f: &mut F, start: &str, cont: &str| {
356 write!(f, "{}", start)
358 write!(f, "{}", cont)
362 let start = if is_value_ns { "::<" } else { "<" };
364 let has_own_self = generics.has_self && generics.parent_count == 0;
365 let params = &generics.params[has_own_self as usize..];
367 // Don't print any regions if they're all erased.
368 let print_regions = params.iter().any(|param| {
369 match substs[param.index as usize].unpack() {
370 UnpackedKind::Lifetime(r) => *r != ty::ReErased,
375 // Don't print args that are the defaults of their respective parameters.
376 let num_supplied_defaults = if self.is_verbose {
379 params.iter().rev().take_while(|param| {
381 ty::GenericParamDefKind::Lifetime => false,
382 ty::GenericParamDefKind::Type { has_default, .. } => {
383 has_default && substs[param.index as usize] == Kind::from(
384 self.tcx.type_of(param.def_id).subst(self.tcx, substs)
387 ty::GenericParamDefKind::Const => false, // FIXME(const_generics:defaults)
392 for param in ¶ms[..params.len() - num_supplied_defaults] {
393 match substs[param.index as usize].unpack() {
394 UnpackedKind::Lifetime(region) => {
398 start_or_continue(f, start, ", ")?;
400 write!(f, "{:?}", region)?;
402 let s = region.print_display_to_string(self);
404 // This happens when the value of the region
405 // parameter is not easily serialized. This may be
406 // because the user omitted it in the first place,
407 // or because it refers to some block in the code,
408 // etc. I'm not sure how best to serialize this.
415 UnpackedKind::Type(ty) => {
416 start_or_continue(f, start, ", ")?;
417 ty.print_display(f, self)?;
419 UnpackedKind::Const(ct) => {
420 start_or_continue(f, start, ", ")?;
421 ct.print_display(f, self)?;
426 for projection in projections {
427 start_or_continue(f, start, ", ")?;
430 self.tcx.associated_item(projection.item_def_id).ident),
431 print_display(projection.ty))?;
434 start_or_continue(f, "", ">")
437 fn in_binder<T, F>(&mut self, f: &mut F, value: &ty::Binder<T>) -> fmt::Result
438 where T: Print<'tcx> + TypeFoldable<'tcx>, F: fmt::Write
440 fn name_by_region_index(index: usize) -> InternedString {
442 0 => Symbol::intern("'r"),
443 1 => Symbol::intern("'s"),
444 i => Symbol::intern(&format!("'t{}", i-2)),
448 // Replace any anonymous late-bound regions with named
449 // variants, using gensym'd identifiers, so that we can
450 // clearly differentiate between named and unnamed regions in
451 // the output. We'll probably want to tweak this over time to
452 // decide just how much information to give.
453 if self.binder_depth == 0 {
454 self.prepare_late_bound_region_info(value);
457 let mut empty = true;
458 let mut start_or_continue = |f: &mut F, start: &str, cont: &str| {
461 write!(f, "{}", start)
463 write!(f, "{}", cont)
467 let old_region_index = self.region_index;
468 let mut region_index = old_region_index;
469 let new_value = self.tcx.replace_late_bound_regions(value, |br| {
470 let _ = start_or_continue(f, "for<", ", ");
472 ty::BrNamed(_, name) => {
473 let _ = write!(f, "{}", name);
480 let name = name_by_region_index(region_index);
482 if !self.is_name_used(&name) {
486 let _ = write!(f, "{}", name);
487 ty::BrNamed(self.tcx.hir().local_def_id(CRATE_NODE_ID), name)
490 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
492 start_or_continue(f, "", "> ")?;
494 // Push current state to gcx, and restore after writing new_value.
495 self.binder_depth += 1;
496 self.region_index = region_index;
497 let result = new_value.print_display(f, self);
498 self.region_index = old_region_index;
499 self.binder_depth -= 1;
503 fn is_name_used(&self, name: &InternedString) -> bool {
504 match self.used_region_names {
505 Some(ref names) => names.contains(name),
511 pub fn parameterized<F: fmt::Write>(f: &mut F, did: DefId, substs: SubstsRef<'_>) -> fmt::Result {
512 PrintCx::with(|mut cx| {
513 let substs = cx.tcx.lift(&substs).expect("could not lift for printing");
514 cx.parameterized(f, did, substs, iter::empty())
518 impl<'a, 'tcx, T: Print<'tcx>> Print<'tcx> for &'a T {
519 fn print<F: fmt::Write>(&self, f: &mut F, cx: &mut PrintCx<'_, '_, 'tcx>) -> fmt::Result {
525 ('tcx) &'tcx ty::List<ty::ExistentialPredicate<'tcx>>, (self, f, cx) {
527 // Generate the main trait ref, including associated types.
528 let mut first = true;
530 if let Some(principal) = self.principal() {
531 let mut resugared_principal = false;
533 // Special-case `Fn(...) -> ...` and resugar it.
534 if !cx.is_verbose && cx.tcx.lang_items().fn_trait_kind(principal.def_id).is_some() {
535 if let Tuple(ref args) = principal.substs.type_at(0).sty {
536 let mut projections = self.projection_bounds();
537 if let (Some(proj), None) = (projections.next(), projections.next()) {
538 print!(f, cx, write("{}", cx.tcx.item_path_str(principal.def_id)))?;
539 cx.fn_sig(f, args, false, proj.ty)?;
540 resugared_principal = true;
545 if !resugared_principal {
546 // Use a type that can't appear in defaults of type parameters.
547 let dummy_self = cx.tcx.mk_infer(ty::FreshTy(0));
548 let principal = principal.with_self_ty(cx.tcx, dummy_self);
553 self.projection_bounds(),
560 let mut auto_traits: Vec<_> = self.auto_traits().map(|did| {
561 cx.tcx.item_path_str(did)
564 // The auto traits come ordered by `DefPathHash`. While
565 // `DefPathHash` is *stable* in the sense that it depends on
566 // neither the host nor the phase of the moon, it depends
567 // "pseudorandomly" on the compiler version and the target.
569 // To avoid that causing instabilities in compiletest
570 // output, sort the auto-traits alphabetically.
573 for auto_trait in auto_traits {
579 write!(f, "{}", auto_trait)?;
587 impl fmt::Debug for ty::GenericParamDef {
588 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
589 let type_name = match self.kind {
590 ty::GenericParamDefKind::Lifetime => "Lifetime",
591 ty::GenericParamDefKind::Type { .. } => "Type",
592 ty::GenericParamDefKind::Const => "Const",
594 write!(f, "{}({}, {:?}, {})",
602 impl fmt::Debug for ty::TraitDef {
603 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
605 write!(f, "{}", cx.tcx.item_path_str(self.def_id))
610 impl fmt::Debug for ty::AdtDef {
611 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
613 write!(f, "{}", cx.tcx.item_path_str(self.did))
618 impl<'tcx> fmt::Debug for ty::ClosureUpvar<'tcx> {
619 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
620 write!(f, "ClosureUpvar({:?},{:?})",
626 impl fmt::Debug for ty::UpvarId {
627 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
628 write!(f, "UpvarId({:?};`{}`;{:?})",
629 self.var_path.hir_id,
631 cx.tcx.hir().name_by_hir_id(self.var_path.hir_id)
633 self.closure_expr_id)
637 impl<'tcx> fmt::Debug for ty::UpvarBorrow<'tcx> {
638 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
639 write!(f, "UpvarBorrow({:?}, {:?})",
640 self.kind, self.region)
645 ('tcx) &'tcx ty::List<Ty<'tcx>>, (self, f, cx) {
648 let mut tys = self.iter();
649 if let Some(&ty) = tys.next() {
650 print!(f, cx, print(ty))?;
652 print!(f, cx, write(", "), print(ty))?;
661 ('tcx) ty::TypeAndMut<'tcx>, (self, f, cx) {
664 write("{}", if self.mutbl == hir::MutMutable { "mut " } else { "" }),
671 ('tcx) ty::ExistentialTraitRef<'tcx>, (self, f, cx) {
673 let dummy_self = cx.tcx.mk_infer(ty::FreshTy(0));
675 let trait_ref = *ty::Binder::bind(*self)
676 .with_self_ty(cx.tcx, dummy_self)
678 cx.parameterized(f, trait_ref.def_id, trait_ref.substs, iter::empty())
681 self.print_display(f, cx)
687 ('tcx) ty::adjustment::Adjustment<'tcx>, (self, f, cx) {
689 print!(f, cx, write("{:?} -> ", self.kind), print(self.target))
695 () ty::BoundRegion, (self, f, cx) {
698 return self.print_debug(f, cx);
701 if let BrNamed(_, name) = *self {
702 if name != "" && name != "'_" {
703 return write!(f, "{}", name);
707 let highlight = RegionHighlightMode::get();
708 if let Some((region, counter)) = highlight.highlight_bound_region {
710 return write!(f, "'{}", counter);
718 BrAnon(n) => write!(f, "BrAnon({:?})", n),
719 BrFresh(n) => write!(f, "BrFresh({:?})", n),
720 BrNamed(did, name) => {
721 write!(f, "BrNamed({:?}:{:?}, {})",
722 did.krate, did.index, name)
724 BrEnv => write!(f, "BrEnv"),
731 () ty::PlaceholderRegion, (self, f, cx) {
734 return self.print_debug(f, cx);
737 let highlight = RegionHighlightMode::get();
738 if let Some(counter) = highlight.placeholder_highlight(*self) {
739 return write!(f, "'{}", counter);
742 write!(f, "{}", self.name)
748 () ty::RegionKind, (self, f, cx) {
751 return self.print_debug(f, cx);
754 // Watch out for region highlights.
755 if let Some(n) = RegionHighlightMode::get().region_highlighted(self) {
756 return write!(f, "'{:?}", n);
759 // These printouts are concise. They do not contain all the information
760 // the user might want to diagnose an error, but there is basically no way
761 // to fit that into a short string. Hence the recommendation to use
762 // `explain_region()` or `note_and_explain_region()`.
764 ty::ReEarlyBound(ref data) => {
765 if data.name != "'_" {
766 write!(f, "{}", data.name)
771 ty::ReLateBound(_, br) |
772 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) => {
775 ty::RePlaceholder(p) => {
778 ty::ReScope(scope) if cx.identify_regions => {
780 region::ScopeData::Node =>
781 write!(f, "'{}s", scope.item_local_id().as_usize()),
782 region::ScopeData::CallSite =>
783 write!(f, "'{}cs", scope.item_local_id().as_usize()),
784 region::ScopeData::Arguments =>
785 write!(f, "'{}as", scope.item_local_id().as_usize()),
786 region::ScopeData::Destruction =>
787 write!(f, "'{}ds", scope.item_local_id().as_usize()),
788 region::ScopeData::Remainder(first_statement_index) => write!(
791 scope.item_local_id().as_usize(),
792 first_statement_index.index()
796 ty::ReVar(region_vid) if cx.identify_regions => {
797 write!(f, "{:?}", region_vid)
799 ty::ReVar(region_vid) => {
800 write!(f, "{}", region_vid)
803 ty::ReErased => Ok(()),
804 ty::ReStatic => write!(f, "'static"),
805 ty::ReEmpty => write!(f, "'<empty>"),
807 // The user should never encounter these in unsubstituted form.
808 ty::ReClosureBound(vid) => write!(f, "{:?}", vid),
813 ty::ReEarlyBound(ref data) => {
814 write!(f, "ReEarlyBound({}, {})",
819 ty::ReClosureBound(ref vid) => {
820 write!(f, "ReClosureBound({:?})",
824 ty::ReLateBound(binder_id, ref bound_region) => {
825 write!(f, "ReLateBound({:?}, {:?})",
830 ty::ReFree(ref fr) => write!(f, "{:?}", fr),
833 write!(f, "ReScope({:?})", id)
836 ty::ReStatic => write!(f, "ReStatic"),
838 ty::ReVar(ref vid) => {
839 write!(f, "{:?}", vid)
842 ty::RePlaceholder(placeholder) => {
843 write!(f, "RePlaceholder({:?})", placeholder)
846 ty::ReEmpty => write!(f, "ReEmpty"),
848 ty::ReErased => write!(f, "ReErased")
855 () ty::FreeRegion, (self, f, cx) {
857 write!(f, "ReFree({:?}, {:?})", self.scope, self.bound_region)
863 () ty::Variance, (self, f, cx) {
865 f.write_str(match *self {
866 ty::Covariant => "+",
867 ty::Contravariant => "-",
868 ty::Invariant => "o",
869 ty::Bivariant => "*",
876 ('tcx) ty::FnSig<'tcx>, (self, f, cx) {
878 if self.unsafety == hir::Unsafety::Unsafe {
879 write!(f, "unsafe ")?;
882 if self.abi != Abi::Rust {
883 write!(f, "extern {} ", self.abi)?;
887 cx.fn_sig(f, self.inputs(), self.c_variadic, self.output())
890 write!(f, "({:?}; c_variadic: {})->{:?}", self.inputs(), self.c_variadic, self.output())
895 impl fmt::Debug for ty::TyVid {
896 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
897 write!(f, "_#{}t", self.index)
901 impl<'tcx> fmt::Debug for ty::ConstVid<'tcx> {
902 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
903 write!(f, "_#{}f", self.index)
907 impl fmt::Debug for ty::IntVid {
908 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
909 write!(f, "_#{}i", self.index)
913 impl fmt::Debug for ty::FloatVid {
914 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
915 write!(f, "_#{}f", self.index)
920 () ty::RegionVid, (self, f, cx) {
923 return self.print_debug(f, cx);
926 let highlight = RegionHighlightMode::get();
927 if let Some(counter) = highlight.region_highlighted(&ty::ReVar(*self)) {
928 return write!(f, "'{:?}", counter);
934 // HACK(eddyb) this is duplicated from `display` printing,
935 // to keep NLL borrowck working even with `-Zverbose`.
936 let highlight = RegionHighlightMode::get();
937 if let Some(counter) = highlight.region_highlighted(&ty::ReVar(*self)) {
938 return write!(f, "'{:?}", counter);
941 write!(f, "'_#{}r", self.index())
947 () ty::InferTy, (self, f, cx) {
950 return self.print_debug(f, cx);
953 ty::TyVar(_) => write!(f, "_"),
954 ty::IntVar(_) => write!(f, "{}", "{integer}"),
955 ty::FloatVar(_) => write!(f, "{}", "{float}"),
956 ty::FreshTy(v) => write!(f, "FreshTy({})", v),
957 ty::FreshIntTy(v) => write!(f, "FreshIntTy({})", v),
958 ty::FreshFloatTy(v) => write!(f, "FreshFloatTy({})", v)
963 ty::TyVar(ref v) => write!(f, "{:?}", v),
964 ty::IntVar(ref v) => write!(f, "{:?}", v),
965 ty::FloatVar(ref v) => write!(f, "{:?}", v),
966 ty::FreshTy(v) => write!(f, "FreshTy({:?})", v),
967 ty::FreshIntTy(v) => write!(f, "FreshIntTy({:?})", v),
968 ty::FreshFloatTy(v) => write!(f, "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(|cx| cx.in_binder(f, 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>>>
1014 cx.in_binder(f, self)
1020 ('tcx) ty::TraitRef<'tcx>, (self, f, cx) {
1022 cx.parameterized(f, self.def_id, self.substs, iter::empty())
1025 // when printing out the debug representation, we don't need
1026 // to enumerate the `for<...>` etc because the debruijn index
1027 // tells you everything you need to know.
1030 print(self.self_ty()),
1032 cx.parameterized(f, self.def_id, self.substs, iter::empty())?;
1039 ('tcx) ty::Ty<'tcx>, (self, f, cx) {
1042 Bool => write!(f, "bool"),
1043 Char => write!(f, "char"),
1044 Int(t) => write!(f, "{}", t.ty_to_string()),
1045 Uint(t) => write!(f, "{}", t.ty_to_string()),
1046 Float(t) => write!(f, "{}", t.ty_to_string()),
1048 write!(f, "*{} ", match tm.mutbl {
1049 hir::MutMutable => "mut",
1050 hir::MutImmutable => "const",
1054 Ref(r, ty, mutbl) => {
1056 let s = r.print_display_to_string(cx);
1058 write!(f, "{} ", s)?;
1060 ty::TypeAndMut { ty, mutbl }.print(f, cx)
1062 Never => write!(f, "!"),
1065 let mut tys = tys.iter();
1066 if let Some(&ty) = tys.next() {
1067 print!(f, cx, print(ty), write(","))?;
1068 if let Some(&ty) = tys.next() {
1069 print!(f, cx, write(" "), print(ty))?;
1071 print!(f, cx, write(", "), print(ty))?;
1077 FnDef(def_id, substs) => {
1078 let sig = cx.tcx.fn_sig(def_id).subst(cx.tcx, substs);
1079 print!(f, cx, print(sig), write(" {{"))?;
1080 cx.parameterized(f, def_id, substs, iter::empty())?;
1083 FnPtr(ref bare_fn) => {
1084 bare_fn.print(f, cx)
1086 Infer(infer_ty) => write!(f, "{}", infer_ty),
1087 Error => write!(f, "[type error]"),
1088 Param(ref param_ty) => write!(f, "{}", param_ty),
1089 Bound(debruijn, bound_ty) => {
1090 match bound_ty.kind {
1091 ty::BoundTyKind::Anon => {
1092 if debruijn == ty::INNERMOST {
1093 write!(f, "^{}", bound_ty.var.index())
1095 write!(f, "^{}_{}", debruijn.index(), bound_ty.var.index())
1099 ty::BoundTyKind::Param(p) => write!(f, "{}", p),
1102 Adt(def, substs) => cx.parameterized(f, def.did, substs, iter::empty()),
1103 Dynamic(data, r) => {
1104 let r = r.print_display_to_string(cx);
1111 write!(f, " + {})", r)
1116 Foreign(def_id) => {
1117 cx.parameterized(f, def_id, subst::InternalSubsts::empty(), iter::empty())
1119 Projection(ref data) => data.print(f, cx),
1120 UnnormalizedProjection(ref data) => {
1121 write!(f, "Unnormalized(")?;
1125 Placeholder(placeholder) => {
1126 write!(f, "Placeholder({:?})", placeholder)
1128 Opaque(def_id, substs) => {
1130 return write!(f, "Opaque({:?}, {:?})", def_id, substs);
1133 let def_key = cx.tcx.def_key(def_id);
1134 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
1135 write!(f, "{}", name)?;
1136 let mut substs = substs.iter();
1137 if let Some(first) = substs.next() {
1139 write!(f, "{}", first)?;
1140 for subst in substs {
1141 write!(f, ", {}", subst)?;
1147 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1148 // by looking up the projections associated with the def_id.
1149 let bounds = cx.tcx.predicates_of(def_id).instantiate(cx.tcx, substs);
1151 let mut first = true;
1152 let mut is_sized = false;
1154 for predicate in bounds.predicates {
1155 if let Some(trait_ref) = predicate.to_opt_poly_trait_ref() {
1156 // Don't print +Sized, but rather +?Sized if absent.
1157 if Some(trait_ref.def_id()) == cx.tcx.lang_items().sized_trait() {
1163 write("{}", if first { " " } else { "+" }),
1169 write!(f, "{}?Sized", if first { " " } else { "+" })?;
1171 write!(f, " Sized")?;
1175 Str => write!(f, "str"),
1176 Generator(did, substs, movability) => {
1177 let upvar_tys = substs.upvar_tys(did, cx.tcx);
1178 let witness = substs.witness(did, cx.tcx);
1179 if movability == hir::GeneratorMovability::Movable {
1180 write!(f, "[generator")?;
1182 write!(f, "[static generator")?;
1185 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(did) {
1186 write!(f, "@{:?}", cx.tcx.hir().span_by_hir_id(hir_id))?;
1188 cx.tcx.with_freevars(hir_id, |freevars| {
1189 for (freevar, upvar_ty) in freevars.iter().zip(upvar_tys) {
1193 cx.tcx.hir().name(freevar.var_id())),
1200 // cross-crate closure types should only be
1201 // visible in codegen bug reports, I imagine.
1202 write!(f, "@{:?}", did)?;
1204 for (index, upvar_ty) in upvar_tys.enumerate() {
1206 write("{}{}:", sep, index),
1212 print!(f, cx, write(" "), print(witness), write("]"))
1214 GeneratorWitness(types) => {
1215 cx.in_binder(f, &types)
1217 Closure(did, substs) => {
1218 let upvar_tys = substs.upvar_tys(did, cx.tcx);
1219 write!(f, "[closure")?;
1221 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(did) {
1222 if cx.tcx.sess.opts.debugging_opts.span_free_formats {
1223 write!(f, "@{:?}", hir_id)?;
1225 write!(f, "@{:?}", cx.tcx.hir().span_by_hir_id(hir_id))?;
1228 cx.tcx.with_freevars(hir_id, |freevars| {
1229 for (freevar, upvar_ty) in freevars.iter().zip(upvar_tys) {
1233 cx.tcx.hir().name(freevar.var_id())),
1240 // cross-crate closure types should only be
1241 // visible in codegen bug reports, I imagine.
1242 write!(f, "@{:?}", did)?;
1244 for (index, upvar_ty) in upvar_tys.enumerate() {
1246 write("{}{}:", sep, index),
1255 " closure_kind_ty={:?} closure_sig_ty={:?}",
1256 substs.closure_kind_ty(did, cx.tcx),
1257 substs.closure_sig_ty(did, cx.tcx),
1264 print!(f, cx, write("["), print(ty), write("; "))?;
1266 ty::LazyConst::Unevaluated(_def_id, _substs) => {
1269 ty::LazyConst::Evaluated(c) => {
1271 ConstValue::Infer(..) => write!(f, "_")?,
1272 ConstValue::Param(ParamConst { name, .. }) =>
1273 write!(f, "{}", name)?,
1274 _ => write!(f, "{}", c.unwrap_usize(cx.tcx))?,
1281 print!(f, cx, write("["), print(ty), write("]"))
1286 self.print_display(f, cx)
1292 ('tcx) ConstValue<'tcx>, (self, f, cx) {
1295 ConstValue::Infer(..) => write!(f, "_"),
1296 ConstValue::Param(ParamConst { name, .. }) => write!(f, "{}", name),
1297 _ => write!(f, "{:?}", self),
1304 ('tcx) ty::Const<'tcx>, (self, f, cx) {
1306 write!(f, "{} : {}", self.val, self.ty)
1312 ('tcx) ty::LazyConst<'tcx>, (self, f, cx) {
1315 ty::LazyConst::Unevaluated(..) => write!(f, "_ : _"),
1316 ty::LazyConst::Evaluated(c) => write!(f, "{}", c),
1323 () ty::ParamTy, (self, f, cx) {
1325 write!(f, "{}", self.name)
1328 write!(f, "{}/#{}", self.name, self.idx)
1334 () ty::ParamConst, (self, f, cx) {
1336 write!(f, "{}", self.name)
1339 write!(f, "{}/#{}", self.name, self.index)
1344 // Similar problem to `Binder<T>`, can't define a generic impl.
1345 define_print_multi! {
1347 ('tcx) ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1348 ('tcx) ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1352 print!(f, cx, print(self.0), write(" : "), print(self.1))
1358 ('tcx) ty::SubtypePredicate<'tcx>, (self, f, cx) {
1360 print!(f, cx, print(self.a), write(" <: "), print(self.b))
1366 ('tcx) ty::TraitPredicate<'tcx>, (self, f, cx) {
1368 write!(f, "TraitPredicate({:?})",
1372 print!(f, cx, print(self.trait_ref.self_ty()), write(": "), print(self.trait_ref))
1378 ('tcx) ty::ProjectionPredicate<'tcx>, (self, f, cx) {
1381 write("ProjectionPredicate("),
1382 print(self.projection_ty),
1388 print!(f, cx, print(self.projection_ty), write(" == "), print(self.ty))
1394 ('tcx) ty::ProjectionTy<'tcx>, (self, f, cx) {
1396 cx.parameterized(f, self.item_def_id, self.substs, iter::empty())
1402 () ty::ClosureKind, (self, f, cx) {
1405 ty::ClosureKind::Fn => write!(f, "Fn"),
1406 ty::ClosureKind::FnMut => write!(f, "FnMut"),
1407 ty::ClosureKind::FnOnce => write!(f, "FnOnce"),
1414 ('tcx) ty::Predicate<'tcx>, (self, f, cx) {
1417 ty::Predicate::Trait(ref data) => data.print(f, cx),
1418 ty::Predicate::Subtype(ref predicate) => predicate.print(f, cx),
1419 ty::Predicate::RegionOutlives(ref predicate) => predicate.print(f, cx),
1420 ty::Predicate::TypeOutlives(ref predicate) => predicate.print(f, cx),
1421 ty::Predicate::Projection(ref predicate) => predicate.print(f, cx),
1422 ty::Predicate::WellFormed(ty) => print!(f, cx, print(ty), write(" well-formed")),
1423 ty::Predicate::ObjectSafe(trait_def_id) => {
1424 write!(f, "the trait `{}` is object-safe", cx.tcx.item_path_str(trait_def_id))
1426 ty::Predicate::ClosureKind(closure_def_id, _closure_substs, kind) => {
1427 write!(f, "the closure `{}` implements the trait `{}`",
1428 cx.tcx.item_path_str(closure_def_id), kind)
1430 ty::Predicate::ConstEvaluatable(def_id, substs) => {
1431 write!(f, "the constant `")?;
1432 cx.parameterized(f, def_id, substs, iter::empty())?;
1433 write!(f, "` can be evaluated")
1439 ty::Predicate::Trait(ref a) => a.print(f, cx),
1440 ty::Predicate::Subtype(ref pair) => pair.print(f, cx),
1441 ty::Predicate::RegionOutlives(ref pair) => pair.print(f, cx),
1442 ty::Predicate::TypeOutlives(ref pair) => pair.print(f, cx),
1443 ty::Predicate::Projection(ref pair) => pair.print(f, cx),
1444 ty::Predicate::WellFormed(ty) => ty.print(f, cx),
1445 ty::Predicate::ObjectSafe(trait_def_id) => {
1446 write!(f, "ObjectSafe({:?})", trait_def_id)
1448 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
1449 write!(f, "ClosureKind({:?}, {:?}, {:?})", closure_def_id, closure_substs, kind)
1451 ty::Predicate::ConstEvaluatable(def_id, substs) => {
1452 write!(f, "ConstEvaluatable({:?}, {:?})", def_id, substs)
1460 ('tcx) Kind<'tcx>, (self, f, cx) {
1462 match self.unpack() {
1463 UnpackedKind::Lifetime(lt) => print!(f, cx, print(lt)),
1464 UnpackedKind::Type(ty) => print!(f, cx, print(ty)),
1465 UnpackedKind::Const(ct) => print!(f, cx, print(ct)),
1469 match self.unpack() {
1470 UnpackedKind::Lifetime(lt) => print!(f, cx, print(lt)),
1471 UnpackedKind::Type(ty) => print!(f, cx, print(ty)),
1472 UnpackedKind::Const(ct) => print!(f, cx, print(ct)),