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