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