1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use hir::def_id::DefId;
12 use hir::map::definitions::DefPathData;
13 use mir::interpret::ConstValue;
15 use ty::subst::{self, Subst};
16 use ty::{BrAnon, BrEnv, BrFresh, BrNamed};
17 use ty::{Bool, Char, Adt};
18 use ty::{Error, Str, Array, Slice, Float, FnDef, FnPtr};
19 use ty::{Param, Bound, RawPtr, Ref, Never, Tuple};
20 use ty::{Closure, Generator, GeneratorWitness, Foreign, Projection, Opaque};
21 use ty::{UnnormalizedProjection, Dynamic, Int, Uint, Infer};
22 use ty::{self, RegionVid, Ty, TyCtxt, TypeFoldable, GenericParamCount, GenericParamDefKind};
23 use util::nodemap::FxHashSet;
29 use rustc_target::spec::abi::Abi;
30 use syntax::ast::CRATE_NODE_ID;
31 use syntax::symbol::{Symbol, InternedString};
35 /// Mechanism for highlighting of specific regions for display in NLL region inference errors.
36 /// Contains region to highlight and counter for number to use when highlighting.
37 static HIGHLIGHT_REGION_FOR_REGIONVID: Cell<Option<(RegionVid, usize)>> = Cell::new(None)
41 /// Mechanism for highlighting of specific regions for display in NLL's 'borrow does not live
42 /// long enough' errors. Contains a region to highlight and a counter to use.
43 static HIGHLIGHT_REGION_FOR_BOUND_REGION: Cell<Option<(ty::BoundRegion, usize)>> =
47 macro_rules! gen_display_debug_body {
49 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50 let mut cx = PrintContext::new();
51 $with(self, f, &mut cx)
55 macro_rules! gen_display_debug {
56 ( ($($x:tt)+) $target:ty, display yes ) => {
57 impl<$($x)+> fmt::Display for $target {
58 gen_display_debug_body! { Print::print_display }
61 ( () $target:ty, display yes ) => {
62 impl fmt::Display for $target {
63 gen_display_debug_body! { Print::print_display }
66 ( ($($x:tt)+) $target:ty, debug yes ) => {
67 impl<$($x)+> fmt::Debug for $target {
68 gen_display_debug_body! { Print::print_debug }
71 ( () $target:ty, debug yes ) => {
72 impl fmt::Debug for $target {
73 gen_display_debug_body! { Print::print_debug }
76 ( $generic:tt $target:ty, $t:ident no ) => {};
78 macro_rules! gen_print_impl {
79 ( ($($x:tt)+) $target:ty, ($self:ident, $f:ident, $cx:ident) $disp:block $dbg:block ) => {
80 impl<$($x)+> Print for $target {
81 fn print<F: fmt::Write>(&$self, $f: &mut F, $cx: &mut PrintContext) -> fmt::Result {
87 ( () $target:ty, ($self:ident, $f:ident, $cx:ident) $disp:block $dbg:block ) => {
88 impl Print for $target {
89 fn print<F: fmt::Write>(&$self, $f: &mut F, $cx: &mut PrintContext) -> fmt::Result {
95 ( $generic:tt $target:ty,
96 $vars:tt $gendisp:ident $disp:block $gendbg:ident $dbg:block ) => {
97 gen_print_impl! { $generic $target, $vars $disp $dbg }
98 gen_display_debug! { $generic $target, display $gendisp }
99 gen_display_debug! { $generic $target, debug $gendbg }
102 macro_rules! define_print {
103 ( $generic:tt $target:ty,
104 $vars:tt { display $disp:block debug $dbg:block } ) => {
105 gen_print_impl! { $generic $target, $vars yes $disp yes $dbg }
107 ( $generic:tt $target:ty,
108 $vars:tt { debug $dbg:block display $disp:block } ) => {
109 gen_print_impl! { $generic $target, $vars yes $disp yes $dbg }
111 ( $generic:tt $target:ty,
112 $vars:tt { debug $dbg:block } ) => {
113 gen_print_impl! { $generic $target, $vars no {
114 bug!(concat!("display not implemented for ", stringify!($target)));
117 ( $generic:tt $target:ty,
118 ($self:ident, $f:ident, $cx:ident) { display $disp:block } ) => {
119 gen_print_impl! { $generic $target, ($self, $f, $cx) yes $disp no {
120 write!($f, "{:?}", $self)
124 macro_rules! define_print_multi {
125 ( [ $($generic:tt $target:ty),* ] $vars:tt $def:tt ) => {
126 $(define_print! { $generic $target, $vars $def })*
129 macro_rules! print_inner {
130 ( $f:expr, $cx:expr, write ($($data:expr),+) ) => {
131 write!($f, $($data),+)
133 ( $f:expr, $cx:expr, $kind:ident ($data:expr) ) => {
138 ( $f:expr, $cx:expr $(, $kind:ident $data:tt)+ ) => {
139 Ok(())$(.and_then(|_| print_inner!($f, $cx, $kind $data)))+
144 struct LateBoundRegionNameCollector(FxHashSet<InternedString>);
145 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector {
146 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
148 ty::ReLateBound(_, ty::BrNamed(_, name)) => {
153 r.super_visit_with(self)
158 pub struct PrintContext {
161 identify_regions: bool,
162 used_region_names: Option<FxHashSet<InternedString>>,
168 ty::tls::with_opt(|tcx| {
169 let (is_verbose, identify_regions) = tcx.map(
170 |tcx| (tcx.sess.verbose(), tcx.sess.opts.debugging_opts.identify_regions)
171 ).unwrap_or((false, false));
174 is_verbose: is_verbose,
175 identify_regions: identify_regions,
176 used_region_names: None,
182 fn prepare_late_bound_region_info<'tcx, T>(&mut self, value: &ty::Binder<T>)
183 where T: TypeFoldable<'tcx>
185 let mut collector = LateBoundRegionNameCollector(Default::default());
186 value.visit_with(&mut collector);
187 self.used_region_names = Some(collector.0);
188 self.region_index = 0;
193 fn print<F: fmt::Write>(&self, f: &mut F, cx: &mut PrintContext) -> fmt::Result;
194 fn print_to_string(&self, cx: &mut PrintContext) -> String {
195 let mut result = String::new();
196 let _ = self.print(&mut result, cx);
199 fn print_display<F: fmt::Write>(&self, f: &mut F, cx: &mut PrintContext) -> fmt::Result {
200 let old_debug = cx.is_debug;
202 let result = self.print(f, cx);
203 cx.is_debug = old_debug;
206 fn print_display_to_string(&self, cx: &mut PrintContext) -> String {
207 let mut result = String::new();
208 let _ = self.print_display(&mut result, cx);
211 fn print_debug<F: fmt::Write>(&self, f: &mut F, cx: &mut PrintContext) -> fmt::Result {
212 let old_debug = cx.is_debug;
214 let result = self.print(f, cx);
215 cx.is_debug = old_debug;
218 fn print_debug_to_string(&self, cx: &mut PrintContext) -> String {
219 let mut result = String::new();
220 let _ = self.print_debug(&mut result, cx);
226 fn fn_sig<F: fmt::Write>(&mut self,
233 let mut inputs = inputs.iter();
234 if let Some(&ty) = inputs.next() {
235 print!(f, self, print_display(ty))?;
237 print!(f, self, write(", "), print_display(ty))?;
244 if !output.is_unit() {
245 print!(f, self, write(" -> "), print_display(output))?;
251 fn parameterized<F: fmt::Write>(&mut self,
253 substs: &subst::Substs<'_>,
255 projections: &[ty::ProjectionPredicate<'_>])
257 let key = ty::tls::with(|tcx| tcx.def_key(did));
259 let verbose = self.is_verbose;
260 let mut num_supplied_defaults = 0;
261 let mut has_self = false;
262 let mut own_counts: GenericParamCount = Default::default();
263 let mut is_value_path = false;
264 let mut item_name = Some(key.disambiguated_data.data.as_interned_str());
265 let fn_trait_kind = ty::tls::with(|tcx| {
266 // Unfortunately, some kinds of items (e.g., closures) don't have
267 // generics. So walk back up the find the closest parent that DOES
269 let mut item_def_id = did;
271 let key = tcx.def_key(item_def_id);
272 match key.disambiguated_data.data {
273 DefPathData::AssocTypeInTrait(_) |
274 DefPathData::AssocTypeInImpl(_) |
275 DefPathData::AssocExistentialInImpl(_) |
276 DefPathData::Trait(_) |
278 DefPathData::TypeNs(_) => {
281 DefPathData::ValueNs(_) |
282 DefPathData::EnumVariant(_) => {
283 is_value_path = true;
286 DefPathData::CrateRoot |
288 DefPathData::Module(_) |
289 DefPathData::MacroDef(_) |
290 DefPathData::ClosureExpr |
291 DefPathData::TypeParam(_) |
292 DefPathData::LifetimeParam(_) |
293 DefPathData::Field(_) |
294 DefPathData::StructCtor |
295 DefPathData::AnonConst |
296 DefPathData::ImplTrait |
297 DefPathData::GlobalMetaData(_) => {
298 // if we're making a symbol for something, there ought
299 // to be a value or type-def or something in there
301 item_def_id.index = key.parent.unwrap_or_else(|| {
302 bug!("finding type for {:?}, encountered def-id {:?} with no \
303 parent", did, item_def_id);
308 let mut generics = tcx.generics_of(item_def_id);
309 let child_own_counts = generics.own_counts();
310 let mut path_def_id = did;
311 has_self = generics.has_self;
313 let mut child_types = 0;
314 if let Some(def_id) = generics.parent {
316 assert!(is_value_path);
317 child_types = child_own_counts.types;
318 generics = tcx.generics_of(def_id);
319 own_counts = generics.own_counts();
322 print!(f, self, write("<"), print_display(substs.type_at(0)), write(" as "))?;
325 path_def_id = def_id;
331 assert_eq!(has_self, false);
334 own_counts = child_own_counts;
339 let mut type_params =
340 generics.params.iter().rev().filter_map(|param| match param.kind {
341 GenericParamDefKind::Lifetime => None,
342 GenericParamDefKind::Type { has_default, .. } => {
343 Some((param.def_id, has_default))
347 let has_default = type_params.peek().map(|(_, has_default)| has_default);
348 *has_default.unwrap_or(&false)
351 if let Some(substs) = tcx.lift(&substs) {
352 let types = substs.types().rev().skip(child_types);
353 for ((def_id, has_default), actual) in type_params.zip(types) {
357 if tcx.type_of(def_id).subst(tcx, substs) != actual {
360 num_supplied_defaults += 1;
366 print!(f, self, write("{}", tcx.item_path_str(path_def_id)))?;
367 Ok(tcx.lang_items().fn_trait_kind(path_def_id))
370 if !verbose && fn_trait_kind.is_some() && projections.len() == 1 {
371 let projection_ty = projections[0].ty;
372 if let Tuple(ref args) = substs.type_at(1).sty {
373 return self.fn_sig(f, args, false, projection_ty);
377 let empty = Cell::new(true);
378 let start_or_continue = |f: &mut F, start: &str, cont: &str| {
381 write!(f, "{}", start)
383 write!(f, "{}", cont)
387 let print_regions = |f: &mut F, start: &str, skip, count| {
388 // Don't print any regions if they're all erased.
389 let regions = || substs.regions().skip(skip).take(count);
390 if regions().all(|r: ty::Region<'_>| *r == ty::ReErased) {
394 for region in regions() {
395 let region: ty::Region<'_> = region;
396 start_or_continue(f, start, ", ")?;
398 write!(f, "{:?}", region)?;
400 let s = region.to_string();
402 // This happens when the value of the region
403 // parameter is not easily serialized. This may be
404 // because the user omitted it in the first place,
405 // or because it refers to some block in the code,
406 // etc. I'm not sure how best to serialize this.
417 print_regions(f, "<", 0, own_counts.lifetimes)?;
419 let tps = substs.types()
420 .take(own_counts.types - num_supplied_defaults)
421 .skip(has_self as usize);
424 start_or_continue(f, "<", ", ")?;
425 ty.print_display(f, self)?;
428 for projection in projections {
429 start_or_continue(f, "<", ", ")?;
433 tcx.associated_item(projection.projection_ty.item_def_id).ident),
434 print_display(projection.ty))
438 start_or_continue(f, "", ">")?;
440 // For values, also print their name and type parameters.
448 if let Some(item_name) = item_name {
449 write!(f, "::{}", item_name)?;
452 print_regions(f, "::<", own_counts.lifetimes, usize::MAX)?;
454 // FIXME: consider being smart with defaults here too
455 for ty in substs.types().skip(own_counts.types) {
456 start_or_continue(f, "::<", ", ")?;
457 ty.print_display(f, self)?;
460 start_or_continue(f, "", ">")?;
466 fn in_binder<'a, 'gcx, 'tcx, T, U, F>(&mut self,
468 tcx: TyCtxt<'a, 'gcx, 'tcx>,
469 original: &ty::Binder<T>,
470 lifted: Option<ty::Binder<U>>) -> fmt::Result
471 where T: Print, U: Print + TypeFoldable<'tcx>, F: fmt::Write
473 fn name_by_region_index(index: usize) -> InternedString {
475 0 => Symbol::intern("'r"),
476 1 => Symbol::intern("'s"),
477 i => Symbol::intern(&format!("'t{}", i-2)),
481 // Replace any anonymous late-bound regions with named
482 // variants, using gensym'd identifiers, so that we can
483 // clearly differentiate between named and unnamed regions in
484 // the output. We'll probably want to tweak this over time to
485 // decide just how much information to give.
486 let value = if let Some(v) = lifted {
489 return original.skip_binder().print_display(f, self);
492 if self.binder_depth == 0 {
493 self.prepare_late_bound_region_info(&value);
496 let mut empty = true;
497 let mut start_or_continue = |f: &mut F, start: &str, cont: &str| {
500 write!(f, "{}", start)
502 write!(f, "{}", cont)
506 let old_region_index = self.region_index;
507 let mut region_index = old_region_index;
508 let new_value = tcx.replace_late_bound_regions(&value, |br| {
509 let _ = start_or_continue(f, "for<", ", ");
511 ty::BrNamed(_, name) => {
512 let _ = write!(f, "{}", name);
519 let name = name_by_region_index(region_index);
521 if !self.is_name_used(&name) {
525 let _ = write!(f, "{}", name);
526 ty::BrNamed(tcx.hir.local_def_id(CRATE_NODE_ID), name)
529 tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
531 start_or_continue(f, "", "> ")?;
533 // Push current state to gcx, and restore after writing new_value.
534 self.binder_depth += 1;
535 self.region_index = region_index;
536 let result = new_value.print_display(f, self);
537 self.region_index = old_region_index;
538 self.binder_depth -= 1;
542 fn is_name_used(&self, name: &InternedString) -> bool {
543 match self.used_region_names {
544 Some(ref names) => names.contains(name),
550 pub fn verbose() -> bool {
551 ty::tls::with(|tcx| tcx.sess.verbose())
554 pub fn identify_regions() -> bool {
555 ty::tls::with(|tcx| tcx.sess.opts.debugging_opts.identify_regions)
558 pub fn parameterized<F: fmt::Write>(f: &mut F,
559 substs: &subst::Substs<'_>,
561 projections: &[ty::ProjectionPredicate<'_>])
563 PrintContext::new().parameterized(f, substs, did, projections)
566 fn get_highlight_region_for_regionvid() -> Option<(RegionVid, usize)> {
567 HIGHLIGHT_REGION_FOR_REGIONVID.with(|hr| hr.get())
570 pub fn with_highlight_region_for_regionvid<R>(
573 op: impl FnOnce() -> R
575 HIGHLIGHT_REGION_FOR_REGIONVID.with(|hr| {
576 assert_eq!(hr.get(), None);
577 hr.set(Some((r, counter)));
584 fn get_highlight_region_for_bound_region() -> Option<(ty::BoundRegion, usize)> {
585 HIGHLIGHT_REGION_FOR_BOUND_REGION.with(|hr| hr.get())
588 pub fn with_highlight_region_for_bound_region<R>(
593 HIGHLIGHT_REGION_FOR_BOUND_REGION.with(|hr| {
594 assert_eq!(hr.get(), None);
595 hr.set(Some((r, counter)));
602 impl<'a, T: Print> Print for &'a T {
603 fn print<F: fmt::Write>(&self, f: &mut F, cx: &mut PrintContext) -> fmt::Result {
609 ('tcx) &'tcx ty::List<ty::ExistentialPredicate<'tcx>>, (self, f, cx) {
611 // Generate the main trait ref, including associated types.
612 ty::tls::with(|tcx| {
613 // Use a type that can't appear in defaults of type parameters.
614 let dummy_self = tcx.mk_infer(ty::FreshTy(0));
617 .lift(&self.principal())
618 .expect("could not lift TraitRef for printing")
619 .with_self_ty(tcx, dummy_self);
620 let projections = self.projection_bounds().map(|p| {
622 .expect("could not lift projection for printing")
623 .with_self_ty(tcx, dummy_self)
624 }).collect::<Vec<_>>();
625 cx.parameterized(f, principal.substs, principal.def_id, &projections)?;
628 for did in self.auto_traits() {
629 write!(f, " + {}", tcx.item_path_str(did))?;
640 impl fmt::Debug for ty::GenericParamDef {
641 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
642 let type_name = match self.kind {
643 ty::GenericParamDefKind::Lifetime => "Lifetime",
644 ty::GenericParamDefKind::Type {..} => "Type",
646 write!(f, "{}({}, {:?}, {})",
654 impl fmt::Debug for ty::TraitDef {
655 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
656 ty::tls::with(|tcx| {
657 write!(f, "{}", tcx.item_path_str(self.def_id))
662 impl fmt::Debug for ty::AdtDef {
663 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
664 ty::tls::with(|tcx| {
665 write!(f, "{}", tcx.item_path_str(self.did))
670 impl<'tcx> fmt::Debug for ty::ClosureUpvar<'tcx> {
671 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
672 write!(f, "ClosureUpvar({:?},{:?})",
678 impl fmt::Debug for ty::UpvarId {
679 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
680 write!(f, "UpvarId({:?};`{}`;{:?})",
682 ty::tls::with(|tcx| tcx.hir.name(tcx.hir.hir_to_node_id(self.var_id))),
683 self.closure_expr_id)
687 impl<'tcx> fmt::Debug for ty::UpvarBorrow<'tcx> {
688 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
689 write!(f, "UpvarBorrow({:?}, {:?})",
690 self.kind, self.region)
695 ('tcx) &'tcx ty::List<Ty<'tcx>>, (self, f, cx) {
698 let mut tys = self.iter();
699 if let Some(&ty) = tys.next() {
700 print!(f, cx, print(ty))?;
702 print!(f, cx, write(", "), print(ty))?;
711 ('tcx) ty::TypeAndMut<'tcx>, (self, f, cx) {
714 write("{}", if self.mutbl == hir::MutMutable { "mut " } else { "" }),
721 ('tcx) ty::ExistentialTraitRef<'tcx>, (self, f, cx) {
723 ty::tls::with(|tcx| {
724 let dummy_self = tcx.mk_infer(ty::FreshTy(0));
726 let trait_ref = *tcx.lift(&ty::Binder::bind(*self))
727 .expect("could not lift TraitRef for printing")
728 .with_self_ty(tcx, dummy_self).skip_binder();
729 cx.parameterized(f, trait_ref.substs, trait_ref.def_id, &[])
736 ('tcx) ty::adjustment::Adjustment<'tcx>, (self, f, cx) {
738 print!(f, cx, write("{:?} -> ", self.kind), print(self.target))
744 () ty::BoundRegion, (self, f, cx) {
747 return self.print_debug(f, cx);
750 if let Some((region, counter)) = get_highlight_region_for_bound_region() {
753 BrNamed(_, name) => write!(f, "{}", name),
754 BrAnon(_) | BrFresh(_) | BrEnv => write!(f, "'{}", counter)
760 BrNamed(_, name) => write!(f, "{}", name),
761 BrAnon(_) | BrFresh(_) | BrEnv => Ok(())
766 BrAnon(n) => write!(f, "BrAnon({:?})", n),
767 BrFresh(n) => write!(f, "BrFresh({:?})", n),
768 BrNamed(did, name) => {
769 write!(f, "BrNamed({:?}:{:?}, {})",
770 did.krate, did.index, name)
772 BrEnv => write!(f, "BrEnv"),
779 () ty::RegionKind, (self, f, cx) {
781 if cx.is_verbose || get_highlight_region_for_regionvid().is_some() {
782 return self.print_debug(f, cx);
785 // These printouts are concise. They do not contain all the information
786 // the user might want to diagnose an error, but there is basically no way
787 // to fit that into a short string. Hence the recommendation to use
788 // `explain_region()` or `note_and_explain_region()`.
790 ty::ReEarlyBound(ref data) => {
791 write!(f, "{}", data.name)
793 ty::ReLateBound(_, br) |
794 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
795 ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
798 ty::ReScope(scope) if cx.identify_regions => {
800 region::ScopeData::Node =>
801 write!(f, "'{}s", scope.item_local_id().as_usize()),
802 region::ScopeData::CallSite =>
803 write!(f, "'{}cs", scope.item_local_id().as_usize()),
804 region::ScopeData::Arguments =>
805 write!(f, "'{}as", scope.item_local_id().as_usize()),
806 region::ScopeData::Destruction =>
807 write!(f, "'{}ds", scope.item_local_id().as_usize()),
808 region::ScopeData::Remainder(first_statement_index) => write!(
811 scope.item_local_id().as_usize(),
812 first_statement_index.index()
816 ty::ReVar(region_vid) if cx.identify_regions => {
817 write!(f, "'{}rv", region_vid.index())
821 ty::ReErased => Ok(()),
822 ty::ReStatic => write!(f, "'static"),
823 ty::ReEmpty => write!(f, "'<empty>"),
825 // The user should never encounter these in unsubstituted form.
826 ty::ReClosureBound(vid) => write!(f, "{:?}", vid),
831 ty::ReEarlyBound(ref data) => {
832 write!(f, "ReEarlyBound({}, {})",
837 ty::ReClosureBound(ref vid) => {
838 write!(f, "ReClosureBound({:?})",
842 ty::ReLateBound(binder_id, ref bound_region) => {
843 write!(f, "ReLateBound({:?}, {:?})",
848 ty::ReFree(ref fr) => write!(f, "{:?}", fr),
851 write!(f, "ReScope({:?})", id)
854 ty::ReStatic => write!(f, "ReStatic"),
856 ty::ReVar(ref vid) => {
857 write!(f, "{:?}", vid)
860 ty::RePlaceholder(placeholder) => {
861 write!(f, "RePlaceholder({:?})", placeholder)
864 ty::ReEmpty => write!(f, "ReEmpty"),
866 ty::ReErased => write!(f, "ReErased")
873 () ty::FreeRegion, (self, f, cx) {
875 write!(f, "ReFree({:?}, {:?})", self.scope, self.bound_region)
881 () ty::Variance, (self, f, cx) {
883 f.write_str(match *self {
884 ty::Covariant => "+",
885 ty::Contravariant => "-",
886 ty::Invariant => "o",
887 ty::Bivariant => "*",
894 ('tcx) ty::GenericPredicates<'tcx>, (self, f, cx) {
896 write!(f, "GenericPredicates({:?})", self.predicates)
902 ('tcx) ty::InstantiatedPredicates<'tcx>, (self, f, cx) {
904 write!(f, "InstantiatedPredicates({:?})", self.predicates)
910 ('tcx) ty::FnSig<'tcx>, (self, f, cx) {
912 if self.unsafety == hir::Unsafety::Unsafe {
913 write!(f, "unsafe ")?;
916 if self.abi != Abi::Rust {
917 write!(f, "extern {} ", self.abi)?;
921 cx.fn_sig(f, self.inputs(), self.variadic, self.output())
924 write!(f, "({:?}; variadic: {})->{:?}", self.inputs(), self.variadic, self.output())
929 impl fmt::Debug for ty::TyVid {
930 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
931 write!(f, "_#{}t", self.index)
935 impl fmt::Debug for ty::IntVid {
936 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
937 write!(f, "_#{}i", self.index)
941 impl fmt::Debug for ty::FloatVid {
942 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
943 write!(f, "_#{}f", self.index)
947 impl fmt::Debug for ty::RegionVid {
948 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
949 if let Some((region, counter)) = get_highlight_region_for_regionvid() {
950 debug!("RegionVid.fmt: region={:?} self={:?} counter={:?}", region, self, counter);
951 return if *self == region {
952 write!(f, "'{:?}", counter)
958 write!(f, "'_#{}r", self.index())
963 () ty::InferTy, (self, f, cx) {
966 print!(f, cx, print_debug(self))
969 ty::TyVar(_) => write!(f, "_"),
970 ty::IntVar(_) => write!(f, "{}", "{integer}"),
971 ty::FloatVar(_) => write!(f, "{}", "{float}"),
972 ty::FreshTy(v) => write!(f, "FreshTy({})", v),
973 ty::FreshIntTy(v) => write!(f, "FreshIntTy({})", v),
974 ty::FreshFloatTy(v) => write!(f, "FreshFloatTy({})", v)
980 ty::TyVar(ref v) => write!(f, "{:?}", v),
981 ty::IntVar(ref v) => write!(f, "{:?}", v),
982 ty::FloatVar(ref v) => write!(f, "{:?}", v),
983 ty::FreshTy(v) => write!(f, "FreshTy({:?})", v),
984 ty::FreshIntTy(v) => write!(f, "FreshIntTy({:?})", v),
985 ty::FreshFloatTy(v) => write!(f, "FreshFloatTy({:?})", v)
991 impl fmt::Debug for ty::IntVarValue {
992 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
994 ty::IntType(ref v) => v.fmt(f),
995 ty::UintType(ref v) => v.fmt(f),
1000 impl fmt::Debug for ty::FloatVarValue {
1001 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1006 // The generic impl doesn't work yet because projections are not
1007 // normalized under HRTB.
1008 /*impl<T> fmt::Display for ty::Binder<T>
1009 where T: fmt::Display + for<'a> ty::Lift<'a>,
1010 for<'a> <T as ty::Lift<'a>>::Lifted: fmt::Display + TypeFoldable<'a>
1012 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1013 ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self)))
1017 define_print_multi! {
1019 ('tcx) ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
1020 ('tcx) ty::Binder<ty::TraitRef<'tcx>>,
1021 ('tcx) ty::Binder<ty::FnSig<'tcx>>,
1022 ('tcx) ty::Binder<ty::TraitPredicate<'tcx>>,
1023 ('tcx) ty::Binder<ty::SubtypePredicate<'tcx>>,
1024 ('tcx) ty::Binder<ty::ProjectionPredicate<'tcx>>,
1025 ('tcx) ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1026 ('tcx) ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>
1030 ty::tls::with(|tcx| cx.in_binder(f, tcx, self, tcx.lift(self)))
1036 ('tcx) ty::TraitRef<'tcx>, (self, f, cx) {
1038 cx.parameterized(f, self.substs, self.def_id, &[])
1041 // when printing out the debug representation, we don't need
1042 // to enumerate the `for<...>` etc because the debruijn index
1043 // tells you everything you need to know.
1046 print(self.self_ty()),
1048 cx.parameterized(f, self.substs, self.def_id, &[])?;
1055 ('tcx) ty::TyKind<'tcx>, (self, f, cx) {
1058 Bool => write!(f, "bool"),
1059 Char => write!(f, "char"),
1060 Int(t) => write!(f, "{}", t.ty_to_string()),
1061 Uint(t) => write!(f, "{}", t.ty_to_string()),
1062 Float(t) => write!(f, "{}", t.ty_to_string()),
1064 write!(f, "*{} ", match tm.mutbl {
1065 hir::MutMutable => "mut",
1066 hir::MutImmutable => "const",
1070 Ref(r, ty, mutbl) => {
1072 let s = r.print_to_string(cx);
1074 write!(f, "{}", s)?;
1079 ty::TypeAndMut { ty, mutbl }.print(f, cx)
1081 Never => write!(f, "!"),
1084 let mut tys = tys.iter();
1085 if let Some(&ty) = tys.next() {
1086 print!(f, cx, print(ty), write(","))?;
1087 if let Some(&ty) = tys.next() {
1088 print!(f, cx, write(" "), print(ty))?;
1090 print!(f, cx, write(", "), print(ty))?;
1096 FnDef(def_id, substs) => {
1097 ty::tls::with(|tcx| {
1098 let mut sig = tcx.fn_sig(def_id);
1099 if let Some(substs) = tcx.lift(&substs) {
1100 sig = sig.subst(tcx, substs);
1102 print!(f, cx, print(sig), write(" {{"))
1104 cx.parameterized(f, substs, def_id, &[])?;
1107 FnPtr(ref bare_fn) => {
1108 bare_fn.print(f, cx)
1110 Infer(infer_ty) => write!(f, "{}", infer_ty),
1111 Error => write!(f, "[type error]"),
1112 Param(ref param_ty) => write!(f, "{}", param_ty),
1113 Bound(bound_ty) => {
1114 match bound_ty.kind {
1115 ty::BoundTyKind::Anon => {
1116 if bound_ty.index == ty::INNERMOST {
1117 write!(f, "?{}", bound_ty.var.index())
1119 write!(f, "?{}_{}", bound_ty.index.index(), bound_ty.var.index())
1123 ty::BoundTyKind::Param(p) => write!(f, "{}", p),
1126 Adt(def, substs) => cx.parameterized(f, substs, def.did, &[]),
1127 Dynamic(data, r) => {
1128 let r = r.print_to_string(cx);
1135 write!(f, " + {})", r)
1140 Foreign(def_id) => parameterized(f, subst::Substs::empty(), def_id, &[]),
1141 Projection(ref data) => data.print(f, cx),
1142 UnnormalizedProjection(ref data) => {
1143 write!(f, "Unnormalized(")?;
1147 Opaque(def_id, substs) => {
1149 return write!(f, "Opaque({:?}, {:?})", def_id, substs);
1152 ty::tls::with(|tcx| {
1153 let def_key = tcx.def_key(def_id);
1154 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
1155 write!(f, "{}", name)?;
1156 let mut substs = substs.iter();
1157 if let Some(first) = substs.next() {
1159 write!(f, "{}", first)?;
1160 for subst in substs {
1161 write!(f, ", {}", subst)?;
1167 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1168 // by looking up the projections associated with the def_id.
1169 let predicates_of = tcx.predicates_of(def_id);
1170 let substs = tcx.lift(&substs).unwrap_or_else(|| {
1171 tcx.intern_substs(&[])
1173 let bounds = predicates_of.instantiate(tcx, substs);
1175 let mut first = true;
1176 let mut is_sized = false;
1178 for predicate in bounds.predicates {
1179 if let Some(trait_ref) = predicate.to_opt_poly_trait_ref() {
1180 // Don't print +Sized, but rather +?Sized if absent.
1181 if Some(trait_ref.def_id()) == tcx.lang_items().sized_trait() {
1187 write("{}", if first { " " } else { "+" }),
1193 write!(f, "{}?Sized", if first { " " } else { "+" })?;
1198 Str => write!(f, "str"),
1199 Generator(did, substs, movability) => ty::tls::with(|tcx| {
1200 let upvar_tys = substs.upvar_tys(did, tcx);
1201 let witness = substs.witness(did, tcx);
1202 if movability == hir::GeneratorMovability::Movable {
1203 write!(f, "[generator")?;
1205 write!(f, "[static generator")?;
1208 if let Some(node_id) = tcx.hir.as_local_node_id(did) {
1209 write!(f, "@{:?}", tcx.hir.span(node_id))?;
1211 tcx.with_freevars(node_id, |freevars| {
1212 for (freevar, upvar_ty) in freevars.iter().zip(upvar_tys) {
1216 tcx.hir.name(freevar.var_id())),
1223 // cross-crate closure types should only be
1224 // visible in codegen bug reports, I imagine.
1225 write!(f, "@{:?}", did)?;
1227 for (index, upvar_ty) in upvar_tys.enumerate() {
1229 write("{}{}:", sep, index),
1235 print!(f, cx, write(" "), print(witness), write("]"))
1237 GeneratorWitness(types) => {
1238 ty::tls::with(|tcx| cx.in_binder(f, tcx, &types, tcx.lift(&types)))
1240 Closure(did, substs) => ty::tls::with(|tcx| {
1241 let upvar_tys = substs.upvar_tys(did, tcx);
1242 write!(f, "[closure")?;
1244 if let Some(node_id) = tcx.hir.as_local_node_id(did) {
1245 if tcx.sess.opts.debugging_opts.span_free_formats {
1246 write!(f, "@{:?}", node_id)?;
1248 write!(f, "@{:?}", tcx.hir.span(node_id))?;
1251 tcx.with_freevars(node_id, |freevars| {
1252 for (freevar, upvar_ty) in freevars.iter().zip(upvar_tys) {
1256 tcx.hir.name(freevar.var_id())),
1263 // cross-crate closure types should only be
1264 // visible in codegen bug reports, I imagine.
1265 write!(f, "@{:?}", did)?;
1267 for (index, upvar_ty) in upvar_tys.enumerate() {
1269 write("{}{}:", sep, index),
1278 print!(f, cx, write("["), print(ty), write("; "))?;
1280 ConstValue::Unevaluated(_def_id, _substs) => {
1283 _ => ty::tls::with(|tcx| {
1284 write!(f, "{}", sz.unwrap_usize(tcx))
1290 print!(f, cx, write("["), print(ty), write("]"))
1298 ('tcx) ty::TyS<'tcx>, (self, f, cx) {
1300 self.sty.print(f, cx)
1303 self.sty.print_display(f, cx)
1309 () ty::ParamTy, (self, f, cx) {
1311 write!(f, "{}", self.name)
1314 write!(f, "{}/#{}", self.name, self.idx)
1320 ('tcx, T: Print + fmt::Debug, U: Print + fmt::Debug) ty::OutlivesPredicate<T, U>,
1323 print!(f, cx, print(self.0), write(" : "), print(self.1))
1329 ('tcx) ty::SubtypePredicate<'tcx>, (self, f, cx) {
1331 print!(f, cx, print(self.a), write(" <: "), print(self.b))
1337 ('tcx) ty::TraitPredicate<'tcx>, (self, f, cx) {
1339 write!(f, "TraitPredicate({:?})",
1343 print!(f, cx, print(self.trait_ref.self_ty()), write(": "), print(self.trait_ref))
1349 ('tcx) ty::ProjectionPredicate<'tcx>, (self, f, cx) {
1352 write("ProjectionPredicate("),
1353 print(self.projection_ty),
1359 print!(f, cx, print(self.projection_ty), write(" == "), print(self.ty))
1365 ('tcx) ty::ProjectionTy<'tcx>, (self, f, cx) {
1367 // FIXME(tschottdorf): use something like
1368 // parameterized(f, self.substs, self.item_def_id, &[])
1369 // (which currently ICEs).
1370 let (trait_ref, item_name) = ty::tls::with(|tcx|
1371 (self.trait_ref(tcx), tcx.associated_item(self.item_def_id).ident)
1373 print!(f, cx, print_debug(trait_ref), write("::{}", item_name))
1379 () ty::ClosureKind, (self, f, cx) {
1382 ty::ClosureKind::Fn => write!(f, "Fn"),
1383 ty::ClosureKind::FnMut => write!(f, "FnMut"),
1384 ty::ClosureKind::FnOnce => write!(f, "FnOnce"),
1391 ('tcx) ty::Predicate<'tcx>, (self, f, cx) {
1394 ty::Predicate::Trait(ref data) => data.print(f, cx),
1395 ty::Predicate::Subtype(ref predicate) => predicate.print(f, cx),
1396 ty::Predicate::RegionOutlives(ref predicate) => predicate.print(f, cx),
1397 ty::Predicate::TypeOutlives(ref predicate) => predicate.print(f, cx),
1398 ty::Predicate::Projection(ref predicate) => predicate.print(f, cx),
1399 ty::Predicate::WellFormed(ty) => print!(f, cx, print(ty), write(" well-formed")),
1400 ty::Predicate::ObjectSafe(trait_def_id) =>
1401 ty::tls::with(|tcx| {
1402 write!(f, "the trait `{}` is object-safe", tcx.item_path_str(trait_def_id))
1404 ty::Predicate::ClosureKind(closure_def_id, _closure_substs, kind) =>
1405 ty::tls::with(|tcx| {
1406 write!(f, "the closure `{}` implements the trait `{}`",
1407 tcx.item_path_str(closure_def_id), kind)
1409 ty::Predicate::ConstEvaluatable(def_id, substs) => {
1410 write!(f, "the constant `")?;
1411 cx.parameterized(f, substs, def_id, &[])?;
1412 write!(f, "` can be evaluated")
1418 ty::Predicate::Trait(ref a) => a.print(f, cx),
1419 ty::Predicate::Subtype(ref pair) => pair.print(f, cx),
1420 ty::Predicate::RegionOutlives(ref pair) => pair.print(f, cx),
1421 ty::Predicate::TypeOutlives(ref pair) => pair.print(f, cx),
1422 ty::Predicate::Projection(ref pair) => pair.print(f, cx),
1423 ty::Predicate::WellFormed(ty) => ty.print(f, cx),
1424 ty::Predicate::ObjectSafe(trait_def_id) => {
1425 write!(f, "ObjectSafe({:?})", trait_def_id)
1427 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
1428 write!(f, "ClosureKind({:?}, {:?}, {:?})", closure_def_id, closure_substs, kind)
1430 ty::Predicate::ConstEvaluatable(def_id, substs) => {
1431 write!(f, "ConstEvaluatable({:?}, {:?})", def_id, substs)