]> git.lizzy.rs Git - rust.git/blob - src/librustc/util/ppaux.rs
rustc: add a 'tcx parameter to Print.
[rust.git] / src / librustc / util / ppaux.rs
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, TyCtxt, TypeFoldable, GenericParamCount, GenericParamDefKind, ParamConst};
12 use crate::ty::print::{PrintContext, Print};
13 use crate::mir::interpret::ConstValue;
14
15 use std::cell::Cell;
16 use std::fmt;
17 use std::usize;
18
19 use rustc_target::spec::abi::Abi;
20 use syntax::ast::CRATE_NODE_ID;
21 use syntax::symbol::{Symbol, InternedString};
22 use crate::hir;
23
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`".
28 ///
29 /// Regions not selected by the region highlight mode are presently
30 /// unaffected.
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],
36
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.
40     ///
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
43     /// reference `x`.
44     highlight_bound_region: Option<(ty::BoundRegion, usize)>,
45 }
46
47 thread_local! {
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())
52 }
53
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())
58     }
59
60     // Internal helper to update current settings during the execution of `op`.
61     fn set<R>(
62         old_mode: Self,
63         new_mode: Self,
64         op: impl FnOnce() -> R,
65     ) -> R {
66         REGION_HIGHLIGHT_MODE.with(|c| {
67             c.set(new_mode);
68             let result = op();
69             c.set(old_mode);
70             result
71         })
72     }
73
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,
80     ) -> R {
81         if let Some(k) = region {
82             if let Some(n) = number {
83                 return Self::highlighting_region(k, n, op);
84             }
85         }
86
87         op()
88     }
89
90     /// During the execution of `op`, highlights the region inference
91     /// variable `vid` as `'N`. We can only highlight one region `vid`
92     /// at a time.
93     pub fn highlighting_region<R>(
94         region: ty::Region<'_>,
95         number: usize,
96         op: impl FnOnce() -> R,
97     ) -> 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())
102             .next()
103             .unwrap_or_else(|| {
104                 panic!(
105                     "can only highlight {} placeholders at a time",
106                     old_mode.highlight_regions.len(),
107                 )
108             });
109         *first_avail_slot = Some((*region, number));
110         Self::set(old_mode, new_mode, op)
111     }
112
113     /// Convenience wrapper for `highlighting_region`.
114     pub fn highlighting_region_vid<R>(
115         vid: ty::RegionVid,
116         number: usize,
117         op: impl FnOnce() -> R,
118     ) -> R {
119         Self::highlighting_region(&ty::ReVar(vid), number, op)
120     }
121
122     /// Returns `true` if any placeholders are highlighted, and `false` otherwise.
123     fn any_region_vids_highlighted(&self) -> bool {
124         Self::get()
125             .highlight_regions
126             .iter()
127             .any(|h| match h {
128                 Some((ty::ReVar(_), _)) => true,
129                 _ => false,
130             })
131     }
132
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> {
135         Self::get()
136             .highlight_regions
137             .iter()
138             .filter_map(|h| match h {
139                 Some((r, n)) if r == region => Some(*n),
140                 _ => None,
141             })
142             .next()
143     }
144
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>(
149         br: ty::BoundRegion,
150         number: usize,
151         op: impl FnOnce() -> R,
152     ) -> R {
153         let old_mode = Self::get();
154         assert!(old_mode.highlight_bound_region.is_none());
155         Self::set(
156             old_mode,
157             Self {
158                 highlight_bound_region: Some((br, number)),
159                 ..old_mode
160             },
161             op,
162         )
163     }
164
165     /// Returns `true` if any placeholders are highlighted, and `false` otherwise.
166     pub fn any_placeholders_highlighted(&self) -> bool {
167         Self::get()
168             .highlight_regions
169             .iter()
170             .any(|h| match h {
171                 Some((ty::RePlaceholder(_), _)) => true,
172                 _ => false,
173             })
174     }
175
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))
179     }
180 }
181
182 macro_rules! gen_display_debug_body {
183     ( $with:path ) => {
184         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185             let mut cx = PrintContext::new();
186             $with(self, f, &mut cx)
187         }
188     };
189 }
190 macro_rules! gen_display_debug {
191     ( ($($x:tt)+) $target:ty, display yes ) => {
192         impl<$($x)+> fmt::Display for $target {
193             gen_display_debug_body! { Print::print_display }
194         }
195     };
196     ( () $target:ty, display yes ) => {
197         impl fmt::Display for $target {
198             gen_display_debug_body! { Print::print_display }
199         }
200     };
201     ( ($($x:tt)+) $target:ty, debug yes ) => {
202         impl<$($x)+> fmt::Debug for $target {
203             gen_display_debug_body! { Print::print_debug }
204         }
205     };
206     ( () $target:ty, debug yes ) => {
207         impl fmt::Debug for $target {
208             gen_display_debug_body! { Print::print_debug }
209         }
210     };
211     ( $generic:tt $target:ty, $t:ident no ) => {};
212 }
213 macro_rules! gen_print_impl {
214     ( ($($x:tt)+) $target:ty, ($self:ident, $f:ident, $cx:ident) $disp:block $dbg:block ) => {
215         impl<$($x)+> Print<'tcx> for $target {
216             fn print<F: fmt::Write>(&$self, $f: &mut F, $cx: &mut PrintContext) -> fmt::Result {
217                 if $cx.is_debug $dbg
218                 else $disp
219             }
220         }
221     };
222     ( () $target:ty, ($self:ident, $f:ident, $cx:ident) $disp:block $dbg:block ) => {
223         impl Print<'tcx> for $target {
224             fn print<F: fmt::Write>(&$self, $f: &mut F, $cx: &mut PrintContext) -> fmt::Result {
225                 if $cx.is_debug $dbg
226                 else $disp
227             }
228         }
229     };
230     ( $generic:tt $target:ty,
231       $vars:tt $gendisp:ident $disp:block $gendbg:ident $dbg:block ) => {
232         gen_print_impl! { $generic $target, $vars $disp $dbg }
233         gen_display_debug! { $generic $target, display $gendisp }
234         gen_display_debug! { $generic $target, debug $gendbg }
235     }
236 }
237 macro_rules! define_print {
238     ( $generic:tt $target:ty,
239       $vars:tt { display $disp:block debug $dbg:block } ) => {
240         gen_print_impl! { $generic $target, $vars yes $disp yes $dbg }
241     };
242     ( $generic:tt $target:ty,
243       $vars:tt { debug $dbg:block display $disp:block } ) => {
244         gen_print_impl! { $generic $target, $vars yes $disp yes $dbg }
245     };
246     ( $generic:tt $target:ty,
247       $vars:tt { debug $dbg:block } ) => {
248         gen_print_impl! { $generic $target, $vars no {
249             bug!(concat!("display not implemented for ", stringify!($target)));
250         } yes $dbg }
251     };
252     ( $generic:tt $target:ty,
253       ($self:ident, $f:ident, $cx:ident) { display $disp:block } ) => {
254         gen_print_impl! { $generic $target, ($self, $f, $cx) yes $disp no {
255             write!($f, "{:?}", $self)
256         } }
257     };
258 }
259 macro_rules! define_print_multi {
260     ( [ $($generic:tt $target:ty),* ] $vars:tt $def:tt ) => {
261         $(define_print! { $generic $target, $vars $def })*
262     };
263 }
264 macro_rules! print_inner {
265     ( $f:expr, $cx:expr, write ($($data:expr),+) ) => {
266         write!($f, $($data),+)
267     };
268     ( $f:expr, $cx:expr, $kind:ident ($data:expr) ) => {
269         $data.$kind($f, $cx)
270     };
271 }
272 macro_rules! print {
273     ( $f:expr, $cx:expr $(, $kind:ident $data:tt)+ ) => {
274         Ok(())$(.and_then(|_| print_inner!($f, $cx, $kind $data)))+
275     };
276 }
277
278 impl PrintContext {
279     fn fn_sig<F: fmt::Write>(&mut self,
280                              f: &mut F,
281                              inputs: &[Ty<'_>],
282                              c_variadic: bool,
283                              output: Ty<'_>)
284                              -> fmt::Result {
285         write!(f, "(")?;
286         let mut inputs = inputs.iter();
287         if let Some(&ty) = inputs.next() {
288             print!(f, self, print_display(ty))?;
289             for &ty in inputs {
290                 print!(f, self, write(", "), print_display(ty))?;
291             }
292             if c_variadic {
293                 write!(f, ", ...")?;
294             }
295         }
296         write!(f, ")")?;
297         if !output.is_unit() {
298             print!(f, self, write(" -> "), print_display(output))?;
299         }
300
301         Ok(())
302     }
303
304     fn parameterized<F: fmt::Write>(&mut self,
305                                     f: &mut F,
306                                     substs: SubstsRef<'_>,
307                                     did: DefId,
308                                     projections: &[ty::ProjectionPredicate<'_>])
309                                     -> fmt::Result {
310         let key = ty::tls::with(|tcx| tcx.def_key(did));
311
312         let verbose = self.is_verbose;
313         let mut num_supplied_defaults = 0;
314         let mut has_self = false;
315         let mut own_counts: GenericParamCount = Default::default();
316         let mut is_value_path = false;
317         let mut item_name = Some(key.disambiguated_data.data.as_interned_str());
318         let fn_trait_kind = ty::tls::with(|tcx| {
319             // Unfortunately, some kinds of items (e.g., closures) don't have
320             // generics. So walk back up the find the closest parent that DOES
321             // have them.
322             let mut item_def_id = did;
323             loop {
324                 let key = tcx.def_key(item_def_id);
325                 match key.disambiguated_data.data {
326                     DefPathData::AssocTypeInTrait(_) |
327                     DefPathData::AssocTypeInImpl(_) |
328                     DefPathData::AssocExistentialInImpl(_) |
329                     DefPathData::Trait(_) |
330                     DefPathData::TraitAlias(_) |
331                     DefPathData::Impl |
332                     DefPathData::TypeNs(_) => {
333                         break;
334                     }
335                     DefPathData::ValueNs(_) |
336                     DefPathData::EnumVariant(_) => {
337                         is_value_path = true;
338                         break;
339                     }
340                     DefPathData::CrateRoot |
341                     DefPathData::Misc |
342                     DefPathData::Module(_) |
343                     DefPathData::MacroDef(_) |
344                     DefPathData::ClosureExpr |
345                     DefPathData::TypeParam(_) |
346                     DefPathData::LifetimeParam(_) |
347                     DefPathData::ConstParam(_) |
348                     DefPathData::Field(_) |
349                     DefPathData::StructCtor |
350                     DefPathData::AnonConst |
351                     DefPathData::ImplTrait |
352                     DefPathData::GlobalMetaData(_) => {
353                         // if we're making a symbol for something, there ought
354                         // to be a value or type-def or something in there
355                         // *somewhere*
356                         item_def_id.index = key.parent.unwrap_or_else(|| {
357                             bug!("finding type for {:?}, encountered def-id {:?} with no \
358                                  parent", did, item_def_id);
359                         });
360                     }
361                 }
362             }
363             let mut generics = tcx.generics_of(item_def_id);
364             let child_own_counts = generics.own_counts();
365             let mut path_def_id = did;
366             has_self = generics.has_self;
367
368             let mut child_types = 0;
369             if let Some(def_id) = generics.parent {
370                 // Methods.
371                 assert!(is_value_path);
372                 child_types = child_own_counts.types;
373                 generics = tcx.generics_of(def_id);
374                 own_counts = generics.own_counts();
375
376                 if has_self {
377                     print!(f, self, write("<"), print_display(substs.type_at(0)), write(" as "))?;
378                 }
379
380                 path_def_id = def_id;
381             } else {
382                 item_name = None;
383
384                 if is_value_path {
385                     // Functions.
386                     assert_eq!(has_self, false);
387                 } else {
388                     // Types and traits.
389                     own_counts = child_own_counts;
390                 }
391             }
392
393             if !verbose {
394                 let mut type_params =
395                     generics.params.iter().rev().filter_map(|param| match param.kind {
396                         GenericParamDefKind::Lifetime => None,
397                         GenericParamDefKind::Type { has_default, .. } => {
398                             Some((param.def_id, has_default))
399                         }
400                         GenericParamDefKind::Const => None, // FIXME(const_generics:defaults)
401                     }).peekable();
402                 let has_default = {
403                     let has_default = type_params.peek().map(|(_, has_default)| has_default);
404                     *has_default.unwrap_or(&false)
405                 };
406                 if has_default {
407                     if let Some(substs) = tcx.lift(&substs) {
408                         let types = substs.types().rev().skip(child_types);
409                         for ((def_id, has_default), actual) in type_params.zip(types) {
410                             if !has_default {
411                                 break;
412                             }
413                             if tcx.type_of(def_id).subst(tcx, substs) != actual {
414                                 break;
415                             }
416                             num_supplied_defaults += 1;
417                         }
418                     }
419                 }
420             }
421
422             print!(f, self, write("{}", tcx.item_path_str(path_def_id)))?;
423             Ok(tcx.lang_items().fn_trait_kind(path_def_id))
424         })?;
425
426         if !verbose && fn_trait_kind.is_some() && projections.len() == 1 {
427             let projection_ty = projections[0].ty;
428             if let Tuple(ref args) = substs.type_at(1).sty {
429                 return self.fn_sig(f, args, false, projection_ty);
430             }
431         }
432
433         let empty = Cell::new(true);
434         let start_or_continue = |f: &mut F, start: &str, cont: &str| {
435             if empty.get() {
436                 empty.set(false);
437                 write!(f, "{}", start)
438             } else {
439                 write!(f, "{}", cont)
440             }
441         };
442
443         let print_regions = |f: &mut F, start: &str, skip, count| {
444             // Don't print any regions if they're all erased.
445             let regions = || substs.regions().skip(skip).take(count);
446             if regions().all(|r: ty::Region<'_>| *r == ty::ReErased) {
447                 return Ok(());
448             }
449
450             for region in regions() {
451                 let region: ty::Region<'_> = region;
452                 start_or_continue(f, start, ", ")?;
453                 if verbose {
454                     write!(f, "{:?}", region)?;
455                 } else {
456                     let s = region.to_string();
457                     if s.is_empty() {
458                         // This happens when the value of the region
459                         // parameter is not easily serialized. This may be
460                         // because the user omitted it in the first place,
461                         // or because it refers to some block in the code,
462                         // etc. I'm not sure how best to serialize this.
463                         write!(f, "'_")?;
464                     } else {
465                         write!(f, "{}", s)?;
466                     }
467                 }
468             }
469
470             Ok(())
471         };
472
473         print_regions(f, "<", 0, own_counts.lifetimes)?;
474
475         let tps = substs.types()
476                         .take(own_counts.types - num_supplied_defaults)
477                         .skip(has_self as usize);
478
479         for ty in tps {
480             start_or_continue(f, "<", ", ")?;
481             ty.print_display(f, self)?;
482         }
483
484         for projection in projections {
485             start_or_continue(f, "<", ", ")?;
486             ty::tls::with(|tcx|
487                 print!(f, self,
488                        write("{}=",
489                              tcx.associated_item(projection.projection_ty.item_def_id).ident),
490                        print_display(projection.ty))
491             )?;
492         }
493
494         // FIXME(const_generics::defaults)
495         let consts = substs.consts();
496
497         for ct in consts {
498             start_or_continue(f, "<", ", ")?;
499             ct.print_display(f, self)?;
500         }
501
502         start_or_continue(f, "", ">")?;
503
504         // For values, also print their name and type parameters.
505         if is_value_path {
506             empty.set(true);
507
508             if has_self {
509                 write!(f, ">")?;
510             }
511
512             if let Some(item_name) = item_name {
513                 write!(f, "::{}", item_name)?;
514             }
515
516             print_regions(f, "::<", own_counts.lifetimes, usize::MAX)?;
517
518             // FIXME: consider being smart with defaults here too
519             for ty in substs.types().skip(own_counts.types) {
520                 start_or_continue(f, "::<", ", ")?;
521                 ty.print_display(f, self)?;
522             }
523
524             start_or_continue(f, "", ">")?;
525         }
526
527         Ok(())
528     }
529
530     // FIXME(eddyb) replace `'almost_tcx` with `'tcx` when possible/needed.
531     fn in_binder<'a, 'gcx, 'tcx, 'almost_tcx, T, U, F>(
532         &mut self,
533         f: &mut F,
534         tcx: TyCtxt<'a, 'gcx, 'tcx>,
535         original: &ty::Binder<T>,
536         lifted: Option<ty::Binder<U>>,
537     ) -> fmt::Result
538         where T: Print<'almost_tcx>, U: Print<'tcx> + TypeFoldable<'tcx>, F: fmt::Write
539     {
540         fn name_by_region_index(index: usize) -> InternedString {
541             match index {
542                 0 => Symbol::intern("'r"),
543                 1 => Symbol::intern("'s"),
544                 i => Symbol::intern(&format!("'t{}", i-2)),
545             }.as_interned_str()
546         }
547
548         // Replace any anonymous late-bound regions with named
549         // variants, using gensym'd identifiers, so that we can
550         // clearly differentiate between named and unnamed regions in
551         // the output. We'll probably want to tweak this over time to
552         // decide just how much information to give.
553         let value = if let Some(v) = lifted {
554             v
555         } else {
556             return original.skip_binder().print_display(f, self);
557         };
558
559         if self.binder_depth == 0 {
560             self.prepare_late_bound_region_info(&value);
561         }
562
563         let mut empty = true;
564         let mut start_or_continue = |f: &mut F, start: &str, cont: &str| {
565             if empty {
566                 empty = false;
567                 write!(f, "{}", start)
568             } else {
569                 write!(f, "{}", cont)
570             }
571         };
572
573         let old_region_index = self.region_index;
574         let mut region_index = old_region_index;
575         let new_value = tcx.replace_late_bound_regions(&value, |br| {
576             let _ = start_or_continue(f, "for<", ", ");
577             let br = match br {
578                 ty::BrNamed(_, name) => {
579                     let _ = write!(f, "{}", name);
580                     br
581                 }
582                 ty::BrAnon(_) |
583                 ty::BrFresh(_) |
584                 ty::BrEnv => {
585                     let name = loop {
586                         let name = name_by_region_index(region_index);
587                         region_index += 1;
588                         if !self.is_name_used(&name) {
589                             break name;
590                         }
591                     };
592                     let _ = write!(f, "{}", name);
593                     ty::BrNamed(tcx.hir().local_def_id(CRATE_NODE_ID), name)
594                 }
595             };
596             tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
597         }).0;
598         start_or_continue(f, "", "> ")?;
599
600         // Push current state to gcx, and restore after writing new_value.
601         self.binder_depth += 1;
602         self.region_index = region_index;
603         let result = new_value.print_display(f, self);
604         self.region_index = old_region_index;
605         self.binder_depth -= 1;
606         result
607     }
608
609     fn is_name_used(&self, name: &InternedString) -> bool {
610         match self.used_region_names {
611             Some(ref names) => names.contains(name),
612             None => false,
613         }
614     }
615 }
616
617 pub fn verbose() -> bool {
618     ty::tls::with(|tcx| tcx.sess.verbose())
619 }
620
621 pub fn identify_regions() -> bool {
622     ty::tls::with(|tcx| tcx.sess.opts.debugging_opts.identify_regions)
623 }
624
625 pub fn parameterized<F: fmt::Write>(f: &mut F,
626                                     substs: SubstsRef<'_>,
627                                     did: DefId,
628                                     projections: &[ty::ProjectionPredicate<'_>])
629                                     -> fmt::Result {
630     PrintContext::new().parameterized(f, substs, did, projections)
631 }
632
633 impl<'a, 'tcx, T: Print<'tcx>> Print<'tcx> for &'a T {
634     fn print<F: fmt::Write>(&self, f: &mut F, cx: &mut PrintContext) -> fmt::Result {
635         (*self).print(f, cx)
636     }
637 }
638
639 define_print! {
640     ('tcx) &'tcx ty::List<ty::ExistentialPredicate<'tcx>>, (self, f, cx) {
641         display {
642             // Generate the main trait ref, including associated types.
643             ty::tls::with(|tcx| {
644                 // Use a type that can't appear in defaults of type parameters.
645                 let dummy_self = tcx.mk_infer(ty::FreshTy(0));
646                 let mut first = true;
647
648                 if let Some(principal) = self.principal() {
649                     let principal = tcx
650                         .lift(&principal)
651                         .expect("could not lift TraitRef for printing")
652                         .with_self_ty(tcx, dummy_self);
653                     let projections = self.projection_bounds().map(|p| {
654                         tcx.lift(&p)
655                             .expect("could not lift projection for printing")
656                             .with_self_ty(tcx, dummy_self)
657                     }).collect::<Vec<_>>();
658                     cx.parameterized(f, principal.substs, principal.def_id, &projections)?;
659                     first = false;
660                 }
661
662                 // Builtin bounds.
663                 let mut auto_traits: Vec<_> = self.auto_traits().map(|did| {
664                     tcx.item_path_str(did)
665                 }).collect();
666
667                 // The auto traits come ordered by `DefPathHash`. While
668                 // `DefPathHash` is *stable* in the sense that it depends on
669                 // neither the host nor the phase of the moon, it depends
670                 // "pseudorandomly" on the compiler version and the target.
671                 //
672                 // To avoid that causing instabilities in compiletest
673                 // output, sort the auto-traits alphabetically.
674                 auto_traits.sort();
675
676                 for auto_trait in auto_traits {
677                     if !first {
678                         write!(f, " + ")?;
679                     }
680                     first = false;
681
682                     write!(f, "{}", auto_trait)?;
683                 }
684
685                 Ok(())
686             })?;
687
688             Ok(())
689         }
690     }
691 }
692
693 impl fmt::Debug for ty::GenericParamDef {
694     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
695         let type_name = match self.kind {
696             ty::GenericParamDefKind::Lifetime => "Lifetime",
697             ty::GenericParamDefKind::Type { .. } => "Type",
698             ty::GenericParamDefKind::Const => "Const",
699         };
700         write!(f, "{}({}, {:?}, {})",
701                type_name,
702                self.name,
703                self.def_id,
704                self.index)
705     }
706 }
707
708 impl fmt::Debug for ty::TraitDef {
709     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
710         ty::tls::with(|tcx| {
711             write!(f, "{}", tcx.item_path_str(self.def_id))
712         })
713     }
714 }
715
716 impl fmt::Debug for ty::AdtDef {
717     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
718         ty::tls::with(|tcx| {
719             write!(f, "{}", tcx.item_path_str(self.did))
720         })
721     }
722 }
723
724 impl<'tcx> fmt::Debug for ty::ClosureUpvar<'tcx> {
725     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
726         write!(f, "ClosureUpvar({:?},{:?})",
727                self.def,
728                self.ty)
729     }
730 }
731
732 impl fmt::Debug for ty::UpvarId {
733     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
734         write!(f, "UpvarId({:?};`{}`;{:?})",
735                self.var_path.hir_id,
736                ty::tls::with(|tcx| tcx.hir().name_by_hir_id(self.var_path.hir_id)),
737                self.closure_expr_id)
738     }
739 }
740
741 impl<'tcx> fmt::Debug for ty::UpvarBorrow<'tcx> {
742     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
743         write!(f, "UpvarBorrow({:?}, {:?})",
744                self.kind, self.region)
745     }
746 }
747
748 define_print! {
749     ('tcx) &'tcx ty::List<Ty<'tcx>>, (self, f, cx) {
750         display {
751             write!(f, "{{")?;
752             let mut tys = self.iter();
753             if let Some(&ty) = tys.next() {
754                 print!(f, cx, print(ty))?;
755                 for &ty in tys {
756                     print!(f, cx, write(", "), print(ty))?;
757                 }
758             }
759             write!(f, "}}")
760         }
761     }
762 }
763
764 define_print! {
765     ('tcx) ty::TypeAndMut<'tcx>, (self, f, cx) {
766         display {
767             print!(f, cx,
768                    write("{}", if self.mutbl == hir::MutMutable { "mut " } else { "" }),
769                    print(self.ty))
770         }
771     }
772 }
773
774 define_print! {
775     ('tcx) ty::ExistentialTraitRef<'tcx>, (self, f, cx) {
776         display {
777             cx.parameterized(f, self.substs, self.def_id, &[])
778         }
779         debug {
780             ty::tls::with(|tcx| {
781                 let dummy_self = tcx.mk_infer(ty::FreshTy(0));
782
783                 let trait_ref = *tcx.lift(&ty::Binder::bind(*self))
784                                    .expect("could not lift TraitRef for printing")
785                                    .with_self_ty(tcx, dummy_self).skip_binder();
786                 cx.parameterized(f, trait_ref.substs, trait_ref.def_id, &[])
787             })
788         }
789     }
790 }
791
792 define_print! {
793     ('tcx) ty::adjustment::Adjustment<'tcx>, (self, f, cx) {
794         debug {
795             print!(f, cx, write("{:?} -> ", self.kind), print(self.target))
796         }
797     }
798 }
799
800 define_print! {
801     () ty::BoundRegion, (self, f, cx) {
802         display {
803             if cx.is_verbose {
804                 return self.print_debug(f, cx);
805             }
806
807             if let Some((region, counter)) = RegionHighlightMode::get().highlight_bound_region {
808                 if *self == region {
809                     return match *self {
810                         BrNamed(_, name) => write!(f, "{}", name),
811                         BrAnon(_) | BrFresh(_) | BrEnv => write!(f, "'{}", counter)
812                     };
813                 }
814             }
815
816             match *self {
817                 BrNamed(_, name) => write!(f, "{}", name),
818                 BrAnon(_) | BrFresh(_) | BrEnv => Ok(())
819             }
820         }
821         debug {
822             return match *self {
823                 BrAnon(n) => write!(f, "BrAnon({:?})", n),
824                 BrFresh(n) => write!(f, "BrFresh({:?})", n),
825                 BrNamed(did, name) => {
826                     write!(f, "BrNamed({:?}:{:?}, {})",
827                            did.krate, did.index, name)
828                 }
829                 BrEnv => write!(f, "BrEnv"),
830             };
831         }
832     }
833 }
834
835 define_print! {
836     () ty::PlaceholderRegion, (self, f, cx) {
837         display {
838             if cx.is_verbose {
839                 return self.print_debug(f, cx);
840             }
841
842             let highlight = RegionHighlightMode::get();
843             if let Some(counter) = highlight.placeholder_highlight(*self) {
844                 write!(f, "'{}", counter)
845             } else if highlight.any_placeholders_highlighted() {
846                 write!(f, "'_")
847             } else {
848                 write!(f, "{}", self.name)
849             }
850         }
851     }
852 }
853
854 define_print! {
855     () ty::RegionKind, (self, f, cx) {
856         display {
857             if cx.is_verbose {
858                 return self.print_debug(f, cx);
859             }
860
861             // Watch out for region highlights.
862             if let Some(n) = RegionHighlightMode::get().region_highlighted(self) {
863                 return write!(f, "'{:?}", n);
864             }
865
866             // These printouts are concise.  They do not contain all the information
867             // the user might want to diagnose an error, but there is basically no way
868             // to fit that into a short string.  Hence the recommendation to use
869             // `explain_region()` or `note_and_explain_region()`.
870             match *self {
871                 ty::ReEarlyBound(ref data) => {
872                     write!(f, "{}", data.name)
873                 }
874                 ty::ReLateBound(_, br) |
875                 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) => {
876                     write!(f, "{}", br)
877                 }
878                 ty::RePlaceholder(p) => {
879                     write!(f, "{}", p)
880                 }
881                 ty::ReScope(scope) if cx.identify_regions => {
882                     match scope.data {
883                         region::ScopeData::Node =>
884                             write!(f, "'{}s", scope.item_local_id().as_usize()),
885                         region::ScopeData::CallSite =>
886                             write!(f, "'{}cs", scope.item_local_id().as_usize()),
887                         region::ScopeData::Arguments =>
888                             write!(f, "'{}as", scope.item_local_id().as_usize()),
889                         region::ScopeData::Destruction =>
890                             write!(f, "'{}ds", scope.item_local_id().as_usize()),
891                         region::ScopeData::Remainder(first_statement_index) => write!(
892                             f,
893                             "'{}_{}rs",
894                             scope.item_local_id().as_usize(),
895                             first_statement_index.index()
896                         ),
897                     }
898                 }
899                 ty::ReVar(region_vid) => {
900                     if RegionHighlightMode::get().any_region_vids_highlighted() {
901                         write!(f, "{:?}", region_vid)
902                     } else if cx.identify_regions {
903                         write!(f, "'{}rv", region_vid.index())
904                     } else {
905                         Ok(())
906                     }
907                 }
908                 ty::ReScope(_) |
909                 ty::ReErased => Ok(()),
910                 ty::ReStatic => write!(f, "'static"),
911                 ty::ReEmpty => write!(f, "'<empty>"),
912
913                 // The user should never encounter these in unsubstituted form.
914                 ty::ReClosureBound(vid) => write!(f, "{:?}", vid),
915             }
916         }
917         debug {
918             match *self {
919                 ty::ReEarlyBound(ref data) => {
920                     write!(f, "ReEarlyBound({}, {})",
921                            data.index,
922                            data.name)
923                 }
924
925                 ty::ReClosureBound(ref vid) => {
926                     write!(f, "ReClosureBound({:?})",
927                            vid)
928                 }
929
930                 ty::ReLateBound(binder_id, ref bound_region) => {
931                     write!(f, "ReLateBound({:?}, {:?})",
932                            binder_id,
933                            bound_region)
934                 }
935
936                 ty::ReFree(ref fr) => write!(f, "{:?}", fr),
937
938                 ty::ReScope(id) => {
939                     write!(f, "ReScope({:?})", id)
940                 }
941
942                 ty::ReStatic => write!(f, "ReStatic"),
943
944                 ty::ReVar(ref vid) => {
945                     write!(f, "{:?}", vid)
946                 }
947
948                 ty::RePlaceholder(placeholder) => {
949                     write!(f, "RePlaceholder({:?})", placeholder)
950                 }
951
952                 ty::ReEmpty => write!(f, "ReEmpty"),
953
954                 ty::ReErased => write!(f, "ReErased")
955             }
956         }
957     }
958 }
959
960 define_print! {
961     () ty::FreeRegion, (self, f, cx) {
962         debug {
963             write!(f, "ReFree({:?}, {:?})", self.scope, self.bound_region)
964         }
965     }
966 }
967
968 define_print! {
969     () ty::Variance, (self, f, cx) {
970         debug {
971             f.write_str(match *self {
972                 ty::Covariant => "+",
973                 ty::Contravariant => "-",
974                 ty::Invariant => "o",
975                 ty::Bivariant => "*",
976             })
977         }
978     }
979 }
980
981 define_print! {
982     ('tcx) ty::GenericPredicates<'tcx>, (self, f, cx) {
983         debug {
984             write!(f, "GenericPredicates({:?})", self.predicates)
985         }
986     }
987 }
988
989 define_print! {
990     ('tcx) ty::InstantiatedPredicates<'tcx>, (self, f, cx) {
991         debug {
992             write!(f, "InstantiatedPredicates({:?})", self.predicates)
993         }
994     }
995 }
996
997 define_print! {
998     ('tcx) ty::FnSig<'tcx>, (self, f, cx) {
999         display {
1000             if self.unsafety == hir::Unsafety::Unsafe {
1001                 write!(f, "unsafe ")?;
1002             }
1003
1004             if self.abi != Abi::Rust {
1005                 write!(f, "extern {} ", self.abi)?;
1006             }
1007
1008             write!(f, "fn")?;
1009             cx.fn_sig(f, self.inputs(), self.c_variadic, self.output())
1010         }
1011         debug {
1012             write!(f, "({:?}; c_variadic: {})->{:?}", self.inputs(), self.c_variadic, self.output())
1013         }
1014     }
1015 }
1016
1017 impl fmt::Debug for ty::TyVid {
1018     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1019         write!(f, "_#{}t", self.index)
1020     }
1021 }
1022
1023 impl<'tcx> fmt::Debug for ty::ConstVid<'tcx> {
1024     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1025         write!(f, "_#{}f", self.index)
1026     }
1027 }
1028
1029 impl fmt::Debug for ty::IntVid {
1030     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1031         write!(f, "_#{}i", self.index)
1032     }
1033 }
1034
1035 impl fmt::Debug for ty::FloatVid {
1036     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1037         write!(f, "_#{}f", self.index)
1038     }
1039 }
1040
1041 impl fmt::Debug for ty::RegionVid {
1042     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1043         if let Some(counter) = RegionHighlightMode::get().region_highlighted(&ty::ReVar(*self)) {
1044             return write!(f, "'{:?}", counter);
1045         } else if RegionHighlightMode::get().any_region_vids_highlighted() {
1046             return write!(f, "'_");
1047         }
1048
1049         write!(f, "'_#{}r", self.index())
1050     }
1051 }
1052
1053 define_print! {
1054     () ty::InferTy, (self, f, cx) {
1055         display {
1056             if cx.is_verbose {
1057                 print!(f, cx, print_debug(self))
1058             } else {
1059                 match *self {
1060                     ty::TyVar(_) => write!(f, "_"),
1061                     ty::IntVar(_) => write!(f, "{}", "{integer}"),
1062                     ty::FloatVar(_) => write!(f, "{}", "{float}"),
1063                     ty::FreshTy(v) => write!(f, "FreshTy({})", v),
1064                     ty::FreshIntTy(v) => write!(f, "FreshIntTy({})", v),
1065                     ty::FreshFloatTy(v) => write!(f, "FreshFloatTy({})", v)
1066                 }
1067             }
1068         }
1069         debug {
1070             match *self {
1071                 ty::TyVar(ref v) => write!(f, "{:?}", v),
1072                 ty::IntVar(ref v) => write!(f, "{:?}", v),
1073                 ty::FloatVar(ref v) => write!(f, "{:?}", v),
1074                 ty::FreshTy(v) => write!(f, "FreshTy({:?})", v),
1075                 ty::FreshIntTy(v) => write!(f, "FreshIntTy({:?})", v),
1076                 ty::FreshFloatTy(v) => write!(f, "FreshFloatTy({:?})", v)
1077             }
1078         }
1079     }
1080 }
1081
1082 impl fmt::Debug for ty::IntVarValue {
1083     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1084         match *self {
1085             ty::IntType(ref v) => v.fmt(f),
1086             ty::UintType(ref v) => v.fmt(f),
1087         }
1088     }
1089 }
1090
1091 impl fmt::Debug for ty::FloatVarValue {
1092     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1093         self.0.fmt(f)
1094     }
1095 }
1096
1097 // The generic impl doesn't work yet because projections are not
1098 // normalized under HRTB.
1099 /*impl<T> fmt::Display for ty::Binder<T>
1100     where T: fmt::Display + for<'a> ty::Lift<'a>,
1101           for<'a> <T as ty::Lift<'a>>::Lifted: fmt::Display + TypeFoldable<'a>
1102 {
1103     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1104         ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self)))
1105     }
1106 }*/
1107
1108 define_print_multi! {
1109     [
1110     ('tcx) ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
1111     ('tcx) ty::Binder<ty::TraitRef<'tcx>>,
1112     ('tcx) ty::Binder<ty::FnSig<'tcx>>,
1113     ('tcx) ty::Binder<ty::TraitPredicate<'tcx>>,
1114     ('tcx) ty::Binder<ty::SubtypePredicate<'tcx>>,
1115     ('tcx) ty::Binder<ty::ProjectionPredicate<'tcx>>,
1116     ('tcx) ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1117     ('tcx) ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>
1118     ]
1119     (self, f, cx) {
1120         display {
1121             ty::tls::with(|tcx| cx.in_binder(f, tcx, self, tcx.lift(self)))
1122         }
1123     }
1124 }
1125
1126 define_print! {
1127     ('tcx) ty::TraitRef<'tcx>, (self, f, cx) {
1128         display {
1129             cx.parameterized(f, self.substs, self.def_id, &[])
1130         }
1131         debug {
1132             // when printing out the debug representation, we don't need
1133             // to enumerate the `for<...>` etc because the debruijn index
1134             // tells you everything you need to know.
1135             print!(f, cx,
1136                    write("<"),
1137                    print(self.self_ty()),
1138                    write(" as "))?;
1139             cx.parameterized(f, self.substs, self.def_id, &[])?;
1140             write!(f, ">")
1141         }
1142     }
1143 }
1144
1145 define_print! {
1146     ('tcx) ty::TyKind<'tcx>, (self, f, cx) {
1147         display {
1148             match *self {
1149                 Bool => write!(f, "bool"),
1150                 Char => write!(f, "char"),
1151                 Int(t) => write!(f, "{}", t.ty_to_string()),
1152                 Uint(t) => write!(f, "{}", t.ty_to_string()),
1153                 Float(t) => write!(f, "{}", t.ty_to_string()),
1154                 RawPtr(ref tm) => {
1155                     write!(f, "*{} ", match tm.mutbl {
1156                         hir::MutMutable => "mut",
1157                         hir::MutImmutable => "const",
1158                     })?;
1159                     tm.ty.print(f, cx)
1160                 }
1161                 Ref(r, ty, mutbl) => {
1162                     write!(f, "&")?;
1163                     let s = r.print_to_string(cx);
1164                     if s != "'_" {
1165                         write!(f, "{}", s)?;
1166                         if !s.is_empty() {
1167                             write!(f, " ")?;
1168                         }
1169                     }
1170                     ty::TypeAndMut { ty, mutbl }.print(f, cx)
1171                 }
1172                 Never => write!(f, "!"),
1173                 Tuple(ref tys) => {
1174                     write!(f, "(")?;
1175                     let mut tys = tys.iter();
1176                     if let Some(&ty) = tys.next() {
1177                         print!(f, cx, print(ty), write(","))?;
1178                         if let Some(&ty) = tys.next() {
1179                             print!(f, cx, write(" "), print(ty))?;
1180                             for &ty in tys {
1181                                 print!(f, cx, write(", "), print(ty))?;
1182                             }
1183                         }
1184                     }
1185                     write!(f, ")")
1186                 }
1187                 FnDef(def_id, substs) => {
1188                     ty::tls::with(|tcx| {
1189                         let mut sig = tcx.fn_sig(def_id);
1190                         if let Some(substs) = tcx.lift(&substs) {
1191                             sig = sig.subst(tcx, substs);
1192                         }
1193                         print!(f, cx, print(sig), write(" {{"))
1194                     })?;
1195                     cx.parameterized(f, substs, def_id, &[])?;
1196                     write!(f, "}}")
1197                 }
1198                 FnPtr(ref bare_fn) => {
1199                     bare_fn.print(f, cx)
1200                 }
1201                 Infer(infer_ty) => write!(f, "{}", infer_ty),
1202                 Error => write!(f, "[type error]"),
1203                 Param(ref param_ty) => write!(f, "{}", param_ty),
1204                 Bound(debruijn, bound_ty) => {
1205                     match bound_ty.kind {
1206                         ty::BoundTyKind::Anon => {
1207                             if debruijn == ty::INNERMOST {
1208                                 write!(f, "^{}", bound_ty.var.index())
1209                             } else {
1210                                 write!(f, "^{}_{}", debruijn.index(), bound_ty.var.index())
1211                             }
1212                         }
1213
1214                         ty::BoundTyKind::Param(p) => write!(f, "{}", p),
1215                     }
1216                 }
1217                 Adt(def, substs) => cx.parameterized(f, substs, def.did, &[]),
1218                 Dynamic(data, r) => {
1219                     let r = r.print_to_string(cx);
1220                     if !r.is_empty() {
1221                         write!(f, "(")?;
1222                     }
1223                     write!(f, "dyn ")?;
1224                     data.print(f, cx)?;
1225                     if !r.is_empty() {
1226                         write!(f, " + {})", r)
1227                     } else {
1228                         Ok(())
1229                     }
1230                 }
1231                 Foreign(def_id) => parameterized(f, subst::InternalSubsts::empty(), def_id, &[]),
1232                 Projection(ref data) => data.print(f, cx),
1233                 UnnormalizedProjection(ref data) => {
1234                     write!(f, "Unnormalized(")?;
1235                     data.print(f, cx)?;
1236                     write!(f, ")")
1237                 }
1238                 Placeholder(placeholder) => {
1239                     write!(f, "Placeholder({:?})", placeholder)
1240                 }
1241                 Opaque(def_id, substs) => {
1242                     if cx.is_verbose {
1243                         return write!(f, "Opaque({:?}, {:?})", def_id, substs);
1244                     }
1245
1246                     ty::tls::with(|tcx| {
1247                         let def_key = tcx.def_key(def_id);
1248                         if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
1249                             write!(f, "{}", name)?;
1250                             let mut substs = substs.iter();
1251                             if let Some(first) = substs.next() {
1252                                 write!(f, "::<")?;
1253                                 write!(f, "{}", first)?;
1254                                 for subst in substs {
1255                                     write!(f, ", {}", subst)?;
1256                                 }
1257                                 write!(f, ">")?;
1258                             }
1259                             return Ok(());
1260                         }
1261                         // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1262                         // by looking up the projections associated with the def_id.
1263                         let predicates_of = tcx.predicates_of(def_id);
1264                         let substs = tcx.lift(&substs).unwrap_or_else(|| {
1265                             tcx.intern_substs(&[])
1266                         });
1267                         let bounds = predicates_of.instantiate(tcx, substs);
1268
1269                         let mut first = true;
1270                         let mut is_sized = false;
1271                         write!(f, "impl")?;
1272                         for predicate in bounds.predicates {
1273                             if let Some(trait_ref) = predicate.to_opt_poly_trait_ref() {
1274                                 // Don't print +Sized, but rather +?Sized if absent.
1275                                 if Some(trait_ref.def_id()) == tcx.lang_items().sized_trait() {
1276                                     is_sized = true;
1277                                     continue;
1278                                 }
1279
1280                                 print!(f, cx,
1281                                        write("{}", if first { " " } else { "+" }),
1282                                        print(trait_ref))?;
1283                                 first = false;
1284                             }
1285                         }
1286                         if !is_sized {
1287                             write!(f, "{}?Sized", if first { " " } else { "+" })?;
1288                         } else if first {
1289                             write!(f, " Sized")?;
1290                         }
1291                         Ok(())
1292                     })
1293                 }
1294                 Str => write!(f, "str"),
1295                 Generator(did, substs, movability) => ty::tls::with(|tcx| {
1296                     let upvar_tys = substs.upvar_tys(did, tcx);
1297                     let witness = substs.witness(did, tcx);
1298                     if movability == hir::GeneratorMovability::Movable {
1299                         write!(f, "[generator")?;
1300                     } else {
1301                         write!(f, "[static generator")?;
1302                     }
1303
1304                     if let Some(hir_id) = tcx.hir().as_local_hir_id(did) {
1305                         write!(f, "@{:?}", tcx.hir().span_by_hir_id(hir_id))?;
1306                         let mut sep = " ";
1307                         tcx.with_freevars(hir_id, |freevars| {
1308                             for (freevar, upvar_ty) in freevars.iter().zip(upvar_tys) {
1309                                 print!(f, cx,
1310                                        write("{}{}:",
1311                                              sep,
1312                                              tcx.hir().name(freevar.var_id())),
1313                                        print(upvar_ty))?;
1314                                 sep = ", ";
1315                             }
1316                             Ok(())
1317                         })?
1318                     } else {
1319                         // cross-crate closure types should only be
1320                         // visible in codegen bug reports, I imagine.
1321                         write!(f, "@{:?}", did)?;
1322                         let mut sep = " ";
1323                         for (index, upvar_ty) in upvar_tys.enumerate() {
1324                             print!(f, cx,
1325                                    write("{}{}:", sep, index),
1326                                    print(upvar_ty))?;
1327                             sep = ", ";
1328                         }
1329                     }
1330
1331                     print!(f, cx, write(" "), print(witness), write("]"))
1332                 }),
1333                 GeneratorWitness(types) => {
1334                     ty::tls::with(|tcx| cx.in_binder(f, tcx, &types, tcx.lift(&types)))
1335                 }
1336                 Closure(did, substs) => ty::tls::with(|tcx| {
1337                     let upvar_tys = substs.upvar_tys(did, tcx);
1338                     write!(f, "[closure")?;
1339
1340                     if let Some(hir_id) = tcx.hir().as_local_hir_id(did) {
1341                         if tcx.sess.opts.debugging_opts.span_free_formats {
1342                             write!(f, "@{:?}", hir_id)?;
1343                         } else {
1344                             write!(f, "@{:?}", tcx.hir().span_by_hir_id(hir_id))?;
1345                         }
1346                         let mut sep = " ";
1347                         tcx.with_freevars(hir_id, |freevars| {
1348                             for (freevar, upvar_ty) in freevars.iter().zip(upvar_tys) {
1349                                 print!(f, cx,
1350                                        write("{}{}:",
1351                                              sep,
1352                                              tcx.hir().name(freevar.var_id())),
1353                                        print(upvar_ty))?;
1354                                 sep = ", ";
1355                             }
1356                             Ok(())
1357                         })?
1358                     } else {
1359                         // cross-crate closure types should only be
1360                         // visible in codegen bug reports, I imagine.
1361                         write!(f, "@{:?}", did)?;
1362                         let mut sep = " ";
1363                         for (index, upvar_ty) in upvar_tys.enumerate() {
1364                             print!(f, cx,
1365                                    write("{}{}:", sep, index),
1366                                    print(upvar_ty))?;
1367                             sep = ", ";
1368                         }
1369                     }
1370
1371                     if cx.is_verbose {
1372                         write!(
1373                             f,
1374                             " closure_kind_ty={:?} closure_sig_ty={:?}",
1375                             substs.closure_kind_ty(did, tcx),
1376                             substs.closure_sig_ty(did, tcx),
1377                         )?;
1378                     }
1379
1380                     write!(f, "]")
1381                 }),
1382                 Array(ty, sz) => {
1383                     print!(f, cx, write("["), print(ty), write("; "))?;
1384                     match sz {
1385                         ty::LazyConst::Unevaluated(_def_id, _substs) => {
1386                             write!(f, "_")?;
1387                         }
1388                         ty::LazyConst::Evaluated(c) => ty::tls::with(|tcx| {
1389                             match c.val {
1390                                 ConstValue::Infer(..) => write!(f, "_"),
1391                                 ConstValue::Param(ParamConst { name, .. }) =>
1392                                     write!(f, "{}", name),
1393                                 _ => write!(f, "{}", c.unwrap_usize(tcx)),
1394                             }
1395                         })?,
1396                     }
1397                     write!(f, "]")
1398                 }
1399                 Slice(ty) => {
1400                     print!(f, cx, write("["), print(ty), write("]"))
1401                 }
1402             }
1403         }
1404     }
1405 }
1406
1407 define_print! {
1408     ('tcx) ty::TyS<'tcx>, (self, f, cx) {
1409         display {
1410             self.sty.print(f, cx)
1411         }
1412         debug {
1413             self.sty.print_display(f, cx)
1414         }
1415     }
1416 }
1417
1418 define_print! {
1419     ('tcx) ConstValue<'tcx>, (self, f, cx) {
1420         display {
1421             match self {
1422                 ConstValue::Infer(..) => write!(f, "_"),
1423                 ConstValue::Param(ParamConst { name, .. }) => write!(f, "{}", name),
1424                 _ => write!(f, "{:?}", self),
1425             }
1426         }
1427     }
1428 }
1429
1430 define_print! {
1431     ('tcx) ty::Const<'tcx>, (self, f, cx) {
1432         display {
1433             write!(f, "{} : {}", self.val, self.ty)
1434         }
1435     }
1436 }
1437
1438 define_print! {
1439     ('tcx) ty::LazyConst<'tcx>, (self, f, cx) {
1440         display {
1441             match self {
1442                 ty::LazyConst::Unevaluated(..) => write!(f, "_ : _"),
1443                 ty::LazyConst::Evaluated(c) => write!(f, "{}", c),
1444             }
1445         }
1446     }
1447 }
1448
1449 define_print! {
1450     () ty::ParamTy, (self, f, cx) {
1451         display {
1452             write!(f, "{}", self.name)
1453         }
1454         debug {
1455             write!(f, "{}/#{}", self.name, self.idx)
1456         }
1457     }
1458 }
1459
1460 define_print! {
1461     () ty::ParamConst, (self, f, cx) {
1462         display {
1463             write!(f, "{}", self.name)
1464         }
1465         debug {
1466             write!(f, "{}/#{}", self.name, self.index)
1467         }
1468     }
1469 }
1470
1471 define_print! {
1472     ('tcx, T: Print<'tcx> + fmt::Debug, U: Print<'tcx> + fmt::Debug) ty::OutlivesPredicate<T, U>,
1473     (self, f, cx) {
1474         display {
1475             print!(f, cx, print(self.0), write(" : "), print(self.1))
1476         }
1477     }
1478 }
1479
1480 define_print! {
1481     ('tcx) ty::SubtypePredicate<'tcx>, (self, f, cx) {
1482         display {
1483             print!(f, cx, print(self.a), write(" <: "), print(self.b))
1484         }
1485     }
1486 }
1487
1488 define_print! {
1489     ('tcx) ty::TraitPredicate<'tcx>, (self, f, cx) {
1490         debug {
1491             write!(f, "TraitPredicate({:?})",
1492                    self.trait_ref)
1493         }
1494         display {
1495             print!(f, cx, print(self.trait_ref.self_ty()), write(": "), print(self.trait_ref))
1496         }
1497     }
1498 }
1499
1500 define_print! {
1501     ('tcx) ty::ProjectionPredicate<'tcx>, (self, f, cx) {
1502         debug {
1503             print!(f, cx,
1504                    write("ProjectionPredicate("),
1505                    print(self.projection_ty),
1506                    write(", "),
1507                    print(self.ty),
1508                    write(")"))
1509         }
1510         display {
1511             print!(f, cx, print(self.projection_ty), write(" == "), print(self.ty))
1512         }
1513     }
1514 }
1515
1516 define_print! {
1517     ('tcx) ty::ProjectionTy<'tcx>, (self, f, cx) {
1518         display {
1519             // FIXME(tschottdorf): use something like
1520             //   parameterized(f, self.substs, self.item_def_id, &[])
1521             // (which currently ICEs).
1522             let (trait_ref, item_name) = ty::tls::with(|tcx|
1523                 (self.trait_ref(tcx), tcx.associated_item(self.item_def_id).ident)
1524             );
1525             print!(f, cx, print_debug(trait_ref), write("::{}", item_name))
1526         }
1527     }
1528 }
1529
1530 define_print! {
1531     () ty::ClosureKind, (self, f, cx) {
1532         display {
1533             match *self {
1534                 ty::ClosureKind::Fn => write!(f, "Fn"),
1535                 ty::ClosureKind::FnMut => write!(f, "FnMut"),
1536                 ty::ClosureKind::FnOnce => write!(f, "FnOnce"),
1537             }
1538         }
1539     }
1540 }
1541
1542 define_print! {
1543     ('tcx) ty::Predicate<'tcx>, (self, f, cx) {
1544         display {
1545             match *self {
1546                 ty::Predicate::Trait(ref data) => data.print(f, cx),
1547                 ty::Predicate::Subtype(ref predicate) => predicate.print(f, cx),
1548                 ty::Predicate::RegionOutlives(ref predicate) => predicate.print(f, cx),
1549                 ty::Predicate::TypeOutlives(ref predicate) => predicate.print(f, cx),
1550                 ty::Predicate::Projection(ref predicate) => predicate.print(f, cx),
1551                 ty::Predicate::WellFormed(ty) => print!(f, cx, print(ty), write(" well-formed")),
1552                 ty::Predicate::ObjectSafe(trait_def_id) =>
1553                     ty::tls::with(|tcx| {
1554                         write!(f, "the trait `{}` is object-safe", tcx.item_path_str(trait_def_id))
1555                     }),
1556                 ty::Predicate::ClosureKind(closure_def_id, _closure_substs, kind) =>
1557                     ty::tls::with(|tcx| {
1558                         write!(f, "the closure `{}` implements the trait `{}`",
1559                                tcx.item_path_str(closure_def_id), kind)
1560                     }),
1561                 ty::Predicate::ConstEvaluatable(def_id, substs) => {
1562                     write!(f, "the constant `")?;
1563                     cx.parameterized(f, substs, def_id, &[])?;
1564                     write!(f, "` can be evaluated")
1565                 }
1566             }
1567         }
1568         debug {
1569             match *self {
1570                 ty::Predicate::Trait(ref a) => a.print(f, cx),
1571                 ty::Predicate::Subtype(ref pair) => pair.print(f, cx),
1572                 ty::Predicate::RegionOutlives(ref pair) => pair.print(f, cx),
1573                 ty::Predicate::TypeOutlives(ref pair) => pair.print(f, cx),
1574                 ty::Predicate::Projection(ref pair) => pair.print(f, cx),
1575                 ty::Predicate::WellFormed(ty) => ty.print(f, cx),
1576                 ty::Predicate::ObjectSafe(trait_def_id) => {
1577                     write!(f, "ObjectSafe({:?})", trait_def_id)
1578                 }
1579                 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
1580                     write!(f, "ClosureKind({:?}, {:?}, {:?})", closure_def_id, closure_substs, kind)
1581                 }
1582                 ty::Predicate::ConstEvaluatable(def_id, substs) => {
1583                     write!(f, "ConstEvaluatable({:?}, {:?})", def_id, substs)
1584                 }
1585             }
1586         }
1587     }
1588 }