]> git.lizzy.rs Git - rust.git/blob - src/librustc/util/ppaux.rs
Unignore u128 test for stage 0,1
[rust.git] / src / librustc / util / ppaux.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use hir::def_id::DefId;
12 use hir::map::definitions::DefPathData;
13 use ty::subst::{self, Subst};
14 use ty::{BrAnon, BrEnv, BrFresh, BrNamed};
15 use ty::{TyBool, TyChar, TyAdt};
16 use ty::{TyError, TyStr, TyArray, TySlice, TyFloat, TyFnDef, TyFnPtr};
17 use ty::{TyParam, TyRawPtr, TyRef, TyNever, TyTuple};
18 use ty::{TyClosure, TyProjection, TyAnon};
19 use ty::{TyDynamic, TyInt, TyUint, TyInfer};
20 use ty::{self, Ty, TyCtxt, TypeFoldable};
21
22 use std::cell::Cell;
23 use std::fmt;
24 use std::usize;
25
26 use syntax::abi::Abi;
27 use syntax::ast::CRATE_NODE_ID;
28 use syntax::symbol::Symbol;
29 use hir;
30
31 pub fn verbose() -> bool {
32     ty::tls::with(|tcx| tcx.sess.verbose())
33 }
34
35 fn fn_sig(f: &mut fmt::Formatter,
36           inputs: &[Ty],
37           variadic: bool,
38           output: Ty)
39           -> fmt::Result {
40     write!(f, "(")?;
41     let mut inputs = inputs.iter();
42     if let Some(&ty) = inputs.next() {
43         write!(f, "{}", ty)?;
44         for &ty in inputs {
45             write!(f, ", {}", ty)?;
46         }
47         if variadic {
48             write!(f, ", ...")?;
49         }
50     }
51     write!(f, ")")?;
52     if !output.is_nil() {
53         write!(f, " -> {}", output)?;
54     }
55
56     Ok(())
57 }
58
59 pub fn parameterized(f: &mut fmt::Formatter,
60                      substs: &subst::Substs,
61                      mut did: DefId,
62                      projections: &[ty::ProjectionPredicate])
63                      -> fmt::Result {
64     let key = ty::tls::with(|tcx| tcx.def_key(did));
65     let mut item_name = if let Some(name) = key.disambiguated_data.data.get_opt_name() {
66         Some(name)
67     } else {
68         did.index = key.parent.unwrap_or_else(
69             || bug!("finding type for {:?}, encountered def-id {:?} with no parent",
70                     did, did));
71         parameterized(f, substs, did, projections)?;
72         return write!(f, "::{}", key.disambiguated_data.data.as_interned_str());
73     };
74
75     let mut verbose = false;
76     let mut num_supplied_defaults = 0;
77     let mut has_self = false;
78     let mut num_regions = 0;
79     let mut num_types = 0;
80     let mut is_value_path = false;
81     let fn_trait_kind = ty::tls::with(|tcx| {
82         // Unfortunately, some kinds of items (e.g., closures) don't have
83         // generics. So walk back up the find the closest parent that DOES
84         // have them.
85         let mut item_def_id = did;
86         loop {
87             let key = tcx.def_key(item_def_id);
88             match key.disambiguated_data.data {
89                 DefPathData::TypeNs(_) => {
90                     break;
91                 }
92                 DefPathData::ValueNs(_) | DefPathData::EnumVariant(_) => {
93                     is_value_path = true;
94                     break;
95                 }
96                 _ => {
97                     // if we're making a symbol for something, there ought
98                     // to be a value or type-def or something in there
99                     // *somewhere*
100                     item_def_id.index = key.parent.unwrap_or_else(|| {
101                         bug!("finding type for {:?}, encountered def-id {:?} with no \
102                              parent", did, item_def_id);
103                     });
104                 }
105             }
106         }
107         let mut generics = tcx.item_generics(item_def_id);
108         let mut path_def_id = did;
109         verbose = tcx.sess.verbose();
110         has_self = generics.has_self;
111
112         let mut child_types = 0;
113         if let Some(def_id) = generics.parent {
114             // Methods.
115             assert!(is_value_path);
116             child_types = generics.types.len();
117             generics = tcx.item_generics(def_id);
118             num_regions = generics.regions.len();
119             num_types = generics.types.len();
120
121             if has_self {
122                 write!(f, "<{} as ", substs.type_at(0))?;
123             }
124
125             path_def_id = def_id;
126         } else {
127             item_name = None;
128
129             if is_value_path {
130                 // Functions.
131                 assert_eq!(has_self, false);
132             } else {
133                 // Types and traits.
134                 num_regions = generics.regions.len();
135                 num_types = generics.types.len();
136             }
137         }
138
139         if !verbose {
140             if generics.types.last().map_or(false, |def| def.default.is_some()) {
141                 if let Some(substs) = tcx.lift(&substs) {
142                     let tps = substs.types().rev().skip(child_types);
143                     for (def, actual) in generics.types.iter().rev().zip(tps) {
144                         if def.default.subst(tcx, substs) != Some(actual) {
145                             break;
146                         }
147                         num_supplied_defaults += 1;
148                     }
149                 }
150             }
151         }
152
153         write!(f, "{}", tcx.item_path_str(path_def_id))?;
154         Ok(tcx.lang_items.fn_trait_kind(path_def_id))
155     })?;
156
157     if !verbose && fn_trait_kind.is_some() && projections.len() == 1 {
158         let projection_ty = projections[0].ty;
159         if let TyTuple(ref args, _) = substs.type_at(1).sty {
160             return fn_sig(f, args, false, projection_ty);
161         }
162     }
163
164     let empty = Cell::new(true);
165     let start_or_continue = |f: &mut fmt::Formatter, start: &str, cont: &str| {
166         if empty.get() {
167             empty.set(false);
168             write!(f, "{}", start)
169         } else {
170             write!(f, "{}", cont)
171         }
172     };
173
174     let print_regions = |f: &mut fmt::Formatter, start: &str, skip, count| {
175         // Don't print any regions if they're all erased.
176         let regions = || substs.regions().skip(skip).take(count);
177         if regions().all(|r: &ty::Region| *r == ty::ReErased) {
178             return Ok(());
179         }
180
181         for region in regions() {
182             let region: &ty::Region = region;
183             start_or_continue(f, start, ", ")?;
184             if verbose {
185                 write!(f, "{:?}", region)?;
186             } else {
187                 let s = region.to_string();
188                 if s.is_empty() {
189                     // This happens when the value of the region
190                     // parameter is not easily serialized. This may be
191                     // because the user omitted it in the first place,
192                     // or because it refers to some block in the code,
193                     // etc. I'm not sure how best to serialize this.
194                     write!(f, "'_")?;
195                 } else {
196                     write!(f, "{}", s)?;
197                 }
198             }
199         }
200
201         Ok(())
202     };
203
204     print_regions(f, "<", 0, num_regions)?;
205
206     let tps = substs.types().take(num_types - num_supplied_defaults)
207                             .skip(has_self as usize);
208
209     for ty in tps {
210         start_or_continue(f, "<", ", ")?;
211         write!(f, "{}", ty)?;
212     }
213
214     for projection in projections {
215         start_or_continue(f, "<", ", ")?;
216         write!(f, "{}={}",
217                projection.projection_ty.item_name,
218                projection.ty)?;
219     }
220
221     start_or_continue(f, "", ">")?;
222
223     // For values, also print their name and type parameters.
224     if is_value_path {
225         empty.set(true);
226
227         if has_self {
228             write!(f, ">")?;
229         }
230
231         if let Some(item_name) = item_name {
232             write!(f, "::{}", item_name)?;
233         }
234
235         print_regions(f, "::<", num_regions, usize::MAX)?;
236
237         // FIXME: consider being smart with defaults here too
238         for ty in substs.types().skip(num_types) {
239             start_or_continue(f, "::<", ", ")?;
240             write!(f, "{}", ty)?;
241         }
242
243         start_or_continue(f, "", ">")?;
244     }
245
246     Ok(())
247 }
248
249 fn in_binder<'a, 'gcx, 'tcx, T, U>(f: &mut fmt::Formatter,
250                                    tcx: TyCtxt<'a, 'gcx, 'tcx>,
251                                    original: &ty::Binder<T>,
252                                    lifted: Option<ty::Binder<U>>) -> fmt::Result
253     where T: fmt::Display, U: fmt::Display + TypeFoldable<'tcx>
254 {
255     // Replace any anonymous late-bound regions with named
256     // variants, using gensym'd identifiers, so that we can
257     // clearly differentiate between named and unnamed regions in
258     // the output. We'll probably want to tweak this over time to
259     // decide just how much information to give.
260     let value = if let Some(v) = lifted {
261         v
262     } else {
263         return write!(f, "{}", original.0);
264     };
265
266     let mut empty = true;
267     let mut start_or_continue = |f: &mut fmt::Formatter, start: &str, cont: &str| {
268         if empty {
269             empty = false;
270             write!(f, "{}", start)
271         } else {
272             write!(f, "{}", cont)
273         }
274     };
275
276     let new_value = tcx.replace_late_bound_regions(&value, |br| {
277         let _ = start_or_continue(f, "for<", ", ");
278         let br = match br {
279             ty::BrNamed(_, name, _) => {
280                 let _ = write!(f, "{}", name);
281                 br
282             }
283             ty::BrAnon(_) |
284             ty::BrFresh(_) |
285             ty::BrEnv => {
286                 let name = Symbol::intern("'r");
287                 let _ = write!(f, "{}", name);
288                 ty::BrNamed(tcx.hir.local_def_id(CRATE_NODE_ID),
289                             name,
290                             ty::Issue32330::WontChange)
291             }
292         };
293         tcx.mk_region(ty::ReLateBound(ty::DebruijnIndex::new(1), br))
294     }).0;
295
296     start_or_continue(f, "", "> ")?;
297     write!(f, "{}", new_value)
298 }
299
300 impl<'tcx> fmt::Display for &'tcx ty::Slice<ty::ExistentialPredicate<'tcx>> {
301     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
302         // Generate the main trait ref, including associated types.
303         ty::tls::with(|tcx| {
304             // Use a type that can't appear in defaults of type parameters.
305             let dummy_self = tcx.mk_infer(ty::FreshTy(0));
306
307             if let Some(p) = self.principal() {
308                 let principal = tcx.lift(&p).expect("could not lift TraitRef for printing")
309                     .with_self_ty(tcx, dummy_self);
310                 let projections = self.projection_bounds().map(|p| {
311                     tcx.lift(&p)
312                         .expect("could not lift projection for printing")
313                         .with_self_ty(tcx, dummy_self)
314                 }).collect::<Vec<_>>();
315                 parameterized(f, principal.substs, principal.def_id, &projections)?;
316             }
317
318             // Builtin bounds.
319             for did in self.auto_traits() {
320                 write!(f, " + {}", tcx.item_path_str(did))?;
321             }
322
323             Ok(())
324         })?;
325
326         Ok(())
327     }
328 }
329
330 impl<'tcx> fmt::Debug for ty::TypeParameterDef<'tcx> {
331     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
332         write!(f, "TypeParameterDef({}, {:?}, {})",
333                self.name,
334                self.def_id,
335                self.index)
336     }
337 }
338
339 impl fmt::Debug for ty::RegionParameterDef {
340     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
341         write!(f, "RegionParameterDef({}, {:?}, {})",
342                self.name,
343                self.def_id,
344                self.index)
345     }
346 }
347
348 impl<'tcx> fmt::Debug for ty::TyS<'tcx> {
349     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
350         write!(f, "{}", *self)
351     }
352 }
353
354 impl<'tcx> fmt::Display for ty::TypeAndMut<'tcx> {
355     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
356         write!(f, "{}{}",
357                if self.mutbl == hir::MutMutable { "mut " } else { "" },
358                self.ty)
359     }
360 }
361
362 impl<'tcx> fmt::Debug for ty::ItemSubsts<'tcx> {
363     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
364         write!(f, "ItemSubsts({:?})", self.substs)
365     }
366 }
367
368 impl<'tcx> fmt::Debug for ty::TraitRef<'tcx> {
369     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
370         // when printing out the debug representation, we don't need
371         // to enumerate the `for<...>` etc because the debruijn index
372         // tells you everything you need to know.
373         write!(f, "<{:?} as {}>", self.self_ty(), *self)
374     }
375 }
376
377 impl<'tcx> fmt::Debug for ty::ExistentialTraitRef<'tcx> {
378     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
379         ty::tls::with(|tcx| {
380             let dummy_self = tcx.mk_infer(ty::FreshTy(0));
381
382             let trait_ref = tcx.lift(&ty::Binder(*self))
383                                .expect("could not lift TraitRef for printing")
384                                .with_self_ty(tcx, dummy_self).0;
385             parameterized(f, trait_ref.substs, trait_ref.def_id, &[])
386         })
387     }
388 }
389
390 impl fmt::Debug for ty::TraitDef {
391     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
392         ty::tls::with(|tcx| {
393             write!(f, "{}", tcx.item_path_str(self.def_id))
394         })
395     }
396 }
397
398 impl fmt::Debug for ty::AdtDef {
399     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
400         ty::tls::with(|tcx| {
401             write!(f, "{}", tcx.item_path_str(self.did))
402         })
403     }
404 }
405
406 impl<'tcx> fmt::Debug for ty::adjustment::Adjustment<'tcx> {
407     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
408         write!(f, "{:?} -> {}", self.kind, self.target)
409     }
410 }
411
412 impl<'tcx> fmt::Debug for ty::Predicate<'tcx> {
413     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
414         match *self {
415             ty::Predicate::Trait(ref a) => write!(f, "{:?}", a),
416             ty::Predicate::Equate(ref pair) => write!(f, "{:?}", pair),
417             ty::Predicate::RegionOutlives(ref pair) => write!(f, "{:?}", pair),
418             ty::Predicate::TypeOutlives(ref pair) => write!(f, "{:?}", pair),
419             ty::Predicate::Projection(ref pair) => write!(f, "{:?}", pair),
420             ty::Predicate::WellFormed(ty) => write!(f, "WF({:?})", ty),
421             ty::Predicate::ObjectSafe(trait_def_id) => {
422                 write!(f, "ObjectSafe({:?})", trait_def_id)
423             }
424             ty::Predicate::ClosureKind(closure_def_id, kind) => {
425                 write!(f, "ClosureKind({:?}, {:?})", closure_def_id, kind)
426             }
427         }
428     }
429 }
430
431 impl fmt::Display for ty::BoundRegion {
432     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
433         if verbose() {
434             return write!(f, "{:?}", *self);
435         }
436
437         match *self {
438             BrNamed(_, name, _) => write!(f, "{}", name),
439             BrAnon(_) | BrFresh(_) | BrEnv => Ok(())
440         }
441     }
442 }
443
444 impl fmt::Debug for ty::BoundRegion {
445     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
446         match *self {
447             BrAnon(n) => write!(f, "BrAnon({:?})", n),
448             BrFresh(n) => write!(f, "BrFresh({:?})", n),
449             BrNamed(did, name, issue32330) => {
450                 write!(f, "BrNamed({:?}:{:?}, {:?}, {:?})",
451                        did.krate, did.index, name, issue32330)
452             }
453             BrEnv => "BrEnv".fmt(f),
454         }
455     }
456 }
457
458 impl fmt::Debug for ty::Region {
459     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
460         match *self {
461             ty::ReEarlyBound(ref data) => {
462                 write!(f, "ReEarlyBound({}, {})",
463                        data.index,
464                        data.name)
465             }
466
467             ty::ReLateBound(binder_id, ref bound_region) => {
468                 write!(f, "ReLateBound({:?}, {:?})",
469                        binder_id,
470                        bound_region)
471             }
472
473             ty::ReFree(ref fr) => write!(f, "{:?}", fr),
474
475             ty::ReScope(id) => {
476                 write!(f, "ReScope({:?})", id)
477             }
478
479             ty::ReStatic => write!(f, "ReStatic"),
480
481             ty::ReVar(ref vid) => {
482                 write!(f, "{:?}", vid)
483             }
484
485             ty::ReSkolemized(id, ref bound_region) => {
486                 write!(f, "ReSkolemized({}, {:?})", id.index, bound_region)
487             }
488
489             ty::ReEmpty => write!(f, "ReEmpty"),
490
491             ty::ReErased => write!(f, "ReErased")
492         }
493     }
494 }
495
496 impl<'tcx> fmt::Debug for ty::ClosureTy<'tcx> {
497     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
498         write!(f, "ClosureTy({},{:?},{})",
499                self.unsafety,
500                self.sig,
501                self.abi)
502     }
503 }
504
505 impl<'tcx> fmt::Debug for ty::ClosureUpvar<'tcx> {
506     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
507         write!(f, "ClosureUpvar({:?},{:?})",
508                self.def,
509                self.ty)
510     }
511 }
512
513 impl<'tcx> fmt::Debug for ty::ParameterEnvironment<'tcx> {
514     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
515         write!(f, "ParameterEnvironment(\
516             free_substs={:?}, \
517             implicit_region_bound={:?}, \
518             caller_bounds={:?})",
519             self.free_substs,
520             self.implicit_region_bound,
521             self.caller_bounds)
522     }
523 }
524
525 impl fmt::Display for ty::Region {
526     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
527         if verbose() {
528             return write!(f, "{:?}", *self);
529         }
530
531         // These printouts are concise.  They do not contain all the information
532         // the user might want to diagnose an error, but there is basically no way
533         // to fit that into a short string.  Hence the recommendation to use
534         // `explain_region()` or `note_and_explain_region()`.
535         match *self {
536             ty::ReEarlyBound(ref data) => {
537                 write!(f, "{}", data.name)
538             }
539             ty::ReLateBound(_, br) |
540             ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
541             ty::ReSkolemized(_, br) => {
542                 write!(f, "{}", br)
543             }
544             ty::ReScope(_) |
545             ty::ReVar(_) |
546             ty::ReErased => Ok(()),
547             ty::ReStatic => write!(f, "'static"),
548             ty::ReEmpty => write!(f, "'<empty>"),
549         }
550     }
551 }
552
553 impl fmt::Debug for ty::FreeRegion {
554     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
555         write!(f, "ReFree({:?}, {:?})",
556                self.scope, self.bound_region)
557     }
558 }
559
560 impl fmt::Debug for ty::Variance {
561     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
562         f.write_str(match *self {
563             ty::Covariant => "+",
564             ty::Contravariant => "-",
565             ty::Invariant => "o",
566             ty::Bivariant => "*",
567         })
568     }
569 }
570
571 impl<'tcx> fmt::Debug for ty::GenericPredicates<'tcx> {
572     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
573         write!(f, "GenericPredicates({:?})", self.predicates)
574     }
575 }
576
577 impl<'tcx> fmt::Debug for ty::InstantiatedPredicates<'tcx> {
578     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
579         write!(f, "InstantiatedPredicates({:?})",
580                self.predicates)
581     }
582 }
583
584 impl<'tcx> fmt::Display for ty::FnSig<'tcx> {
585     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
586         write!(f, "fn")?;
587         fn_sig(f, self.inputs(), self.variadic, self.output())
588     }
589 }
590
591 impl fmt::Debug for ty::TyVid {
592     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
593         write!(f, "_#{}t", self.index)
594     }
595 }
596
597 impl fmt::Debug for ty::IntVid {
598     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
599         write!(f, "_#{}i", self.index)
600     }
601 }
602
603 impl fmt::Debug for ty::FloatVid {
604     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
605         write!(f, "_#{}f", self.index)
606     }
607 }
608
609 impl fmt::Debug for ty::RegionVid {
610     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
611         write!(f, "'_#{}r", self.index)
612     }
613 }
614
615 impl<'tcx> fmt::Debug for ty::FnSig<'tcx> {
616     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
617         write!(f, "({:?}; variadic: {})->{:?}", self.inputs(), self.variadic, self.output())
618     }
619 }
620
621 impl fmt::Debug for ty::InferTy {
622     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
623         match *self {
624             ty::TyVar(ref v) => v.fmt(f),
625             ty::IntVar(ref v) => v.fmt(f),
626             ty::FloatVar(ref v) => v.fmt(f),
627             ty::FreshTy(v) => write!(f, "FreshTy({:?})", v),
628             ty::FreshIntTy(v) => write!(f, "FreshIntTy({:?})", v),
629             ty::FreshFloatTy(v) => write!(f, "FreshFloatTy({:?})", v)
630         }
631     }
632 }
633
634 impl fmt::Debug for ty::IntVarValue {
635     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
636         match *self {
637             ty::IntType(ref v) => v.fmt(f),
638             ty::UintType(ref v) => v.fmt(f),
639         }
640     }
641 }
642
643 // The generic impl doesn't work yet because projections are not
644 // normalized under HRTB.
645 /*impl<T> fmt::Display for ty::Binder<T>
646     where T: fmt::Display + for<'a> ty::Lift<'a>,
647           for<'a> <T as ty::Lift<'a>>::Lifted: fmt::Display + TypeFoldable<'a>
648 {
649     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
650         ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self)))
651     }
652 }*/
653
654 impl<'tcx> fmt::Display for ty::Binder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>> {
655     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
656         ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self)))
657     }
658 }
659
660 impl<'tcx> fmt::Display for ty::Binder<ty::TraitRef<'tcx>> {
661     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
662         ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self)))
663     }
664 }
665
666 impl<'tcx> fmt::Display for ty::Binder<ty::TraitPredicate<'tcx>> {
667     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
668         ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self)))
669     }
670 }
671
672 impl<'tcx> fmt::Display for ty::Binder<ty::EquatePredicate<'tcx>> {
673     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
674         ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self)))
675     }
676 }
677
678 impl<'tcx> fmt::Display for ty::Binder<ty::ProjectionPredicate<'tcx>> {
679     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
680         ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self)))
681     }
682 }
683
684 impl<'tcx> fmt::Display for ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, &'tcx ty::Region>> {
685     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
686         ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self)))
687     }
688 }
689
690 impl<'tcx> fmt::Display for ty::Binder<ty::OutlivesPredicate<&'tcx ty::Region,
691                                                              &'tcx ty::Region>> {
692     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
693         ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self)))
694     }
695 }
696
697 impl<'tcx> fmt::Display for ty::TraitRef<'tcx> {
698     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
699         parameterized(f, self.substs, self.def_id, &[])
700     }
701 }
702
703 impl<'tcx> fmt::Display for ty::TypeVariants<'tcx> {
704     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
705         match *self {
706             TyBool => write!(f, "bool"),
707             TyChar => write!(f, "char"),
708             TyInt(t) => write!(f, "{}", t.ty_to_string()),
709             TyUint(t) => write!(f, "{}", t.ty_to_string()),
710             TyFloat(t) => write!(f, "{}", t.ty_to_string()),
711             TyRawPtr(ref tm) => {
712                 write!(f, "*{} {}", match tm.mutbl {
713                     hir::MutMutable => "mut",
714                     hir::MutImmutable => "const",
715                 },  tm.ty)
716             }
717             TyRef(r, ref tm) => {
718                 write!(f, "&")?;
719                 let s = r.to_string();
720                 write!(f, "{}", s)?;
721                 if !s.is_empty() {
722                     write!(f, " ")?;
723                 }
724                 write!(f, "{}", tm)
725             }
726             TyNever => write!(f, "!"),
727             TyTuple(ref tys, _) => {
728                 write!(f, "(")?;
729                 let mut tys = tys.iter();
730                 if let Some(&ty) = tys.next() {
731                     write!(f, "{},", ty)?;
732                     if let Some(&ty) = tys.next() {
733                         write!(f, " {}", ty)?;
734                         for &ty in tys {
735                             write!(f, ", {}", ty)?;
736                         }
737                     }
738                 }
739                 write!(f, ")")
740             }
741             TyFnDef(def_id, substs, ref bare_fn) => {
742                 if bare_fn.unsafety == hir::Unsafety::Unsafe {
743                     write!(f, "unsafe ")?;
744                 }
745
746                 if bare_fn.abi != Abi::Rust {
747                     write!(f, "extern {} ", bare_fn.abi)?;
748                 }
749
750                 write!(f, "{} {{", bare_fn.sig.0)?;
751                 parameterized(f, substs, def_id, &[])?;
752                 write!(f, "}}")
753             }
754             TyFnPtr(ref bare_fn) => {
755                 if bare_fn.unsafety == hir::Unsafety::Unsafe {
756                     write!(f, "unsafe ")?;
757                 }
758
759                 if bare_fn.abi != Abi::Rust {
760                     write!(f, "extern {} ", bare_fn.abi)?;
761                 }
762
763                 write!(f, "{}", bare_fn.sig.0)
764             }
765             TyInfer(infer_ty) => write!(f, "{}", infer_ty),
766             TyError => write!(f, "[type error]"),
767             TyParam(ref param_ty) => write!(f, "{}", param_ty),
768             TyAdt(def, substs) => {
769                 ty::tls::with(|tcx| {
770                     if def.did.is_local() &&
771                           !tcx.item_types.borrow().contains_key(&def.did) {
772                         write!(f, "{}<..>", tcx.item_path_str(def.did))
773                     } else {
774                         parameterized(f, substs, def.did, &[])
775                     }
776                 })
777             }
778             TyDynamic(data, r) => {
779                 write!(f, "{}", data)?;
780                 let r = r.to_string();
781                 if !r.is_empty() {
782                     write!(f, " + {}", r)
783                 } else {
784                     Ok(())
785                 }
786             }
787             TyProjection(ref data) => write!(f, "{}", data),
788             TyAnon(def_id, substs) => {
789                 ty::tls::with(|tcx| {
790                     // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
791                     // by looking up the projections associated with the def_id.
792                     let item_predicates = tcx.item_predicates(def_id);
793                     let substs = tcx.lift(&substs).unwrap_or_else(|| {
794                         tcx.intern_substs(&[])
795                     });
796                     let bounds = item_predicates.instantiate(tcx, substs);
797
798                     let mut first = true;
799                     let mut is_sized = false;
800                     write!(f, "impl")?;
801                     for predicate in bounds.predicates {
802                         if let Some(trait_ref) = predicate.to_opt_poly_trait_ref() {
803                             // Don't print +Sized, but rather +?Sized if absent.
804                             if Some(trait_ref.def_id()) == tcx.lang_items.sized_trait() {
805                                 is_sized = true;
806                                 continue;
807                             }
808
809                             write!(f, "{}{}", if first { " " } else { "+" }, trait_ref)?;
810                             first = false;
811                         }
812                     }
813                     if !is_sized {
814                         write!(f, "{}?Sized", if first { " " } else { "+" })?;
815                     }
816                     Ok(())
817                 })
818             }
819             TyStr => write!(f, "str"),
820             TyClosure(did, substs) => ty::tls::with(|tcx| {
821                 let upvar_tys = substs.upvar_tys(did, tcx);
822                 write!(f, "[closure")?;
823
824                 if let Some(node_id) = tcx.hir.as_local_node_id(did) {
825                     write!(f, "@{:?}", tcx.hir.span(node_id))?;
826                     let mut sep = " ";
827                     tcx.with_freevars(node_id, |freevars| {
828                         for (freevar, upvar_ty) in freevars.iter().zip(upvar_tys) {
829                             let def_id = freevar.def.def_id();
830                             let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
831                             write!(f,
832                                         "{}{}:{}",
833                                         sep,
834                                         tcx.local_var_name_str(node_id),
835                                         upvar_ty)?;
836                             sep = ", ";
837                         }
838                         Ok(())
839                     })?
840                 } else {
841                     // cross-crate closure types should only be
842                     // visible in trans bug reports, I imagine.
843                     write!(f, "@{:?}", did)?;
844                     let mut sep = " ";
845                     for (index, upvar_ty) in upvar_tys.enumerate() {
846                         write!(f, "{}{}:{}", sep, index, upvar_ty)?;
847                         sep = ", ";
848                     }
849                 }
850
851                 write!(f, "]")
852             }),
853             TyArray(ty, sz) => write!(f, "[{}; {}]",  ty, sz),
854             TySlice(ty) => write!(f, "[{}]",  ty)
855         }
856     }
857 }
858
859 impl<'tcx> fmt::Display for ty::TyS<'tcx> {
860     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
861         write!(f, "{}", self.sty)
862     }
863 }
864
865 impl fmt::Debug for ty::UpvarId {
866     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
867         write!(f, "UpvarId({};`{}`;{})",
868                self.var_id,
869                ty::tls::with(|tcx| tcx.local_var_name_str(self.var_id)),
870                self.closure_expr_id)
871     }
872 }
873
874 impl<'tcx> fmt::Debug for ty::UpvarBorrow<'tcx> {
875     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
876         write!(f, "UpvarBorrow({:?}, {:?})",
877                self.kind, self.region)
878     }
879 }
880
881 impl fmt::Display for ty::InferTy {
882     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
883         let print_var_ids = verbose();
884         match *self {
885             ty::TyVar(ref vid) if print_var_ids => write!(f, "{:?}", vid),
886             ty::IntVar(ref vid) if print_var_ids => write!(f, "{:?}", vid),
887             ty::FloatVar(ref vid) if print_var_ids => write!(f, "{:?}", vid),
888             ty::TyVar(_) => write!(f, "_"),
889             ty::IntVar(_) => write!(f, "{}", "{integer}"),
890             ty::FloatVar(_) => write!(f, "{}", "{float}"),
891             ty::FreshTy(v) => write!(f, "FreshTy({})", v),
892             ty::FreshIntTy(v) => write!(f, "FreshIntTy({})", v),
893             ty::FreshFloatTy(v) => write!(f, "FreshFloatTy({})", v)
894         }
895     }
896 }
897
898 impl fmt::Display for ty::ParamTy {
899     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
900         write!(f, "{}", self.name)
901     }
902 }
903
904 impl fmt::Debug for ty::ParamTy {
905     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
906         write!(f, "{}/#{}", self, self.idx)
907     }
908 }
909
910 impl<'tcx, T, U> fmt::Display for ty::OutlivesPredicate<T,U>
911     where T: fmt::Display, U: fmt::Display
912 {
913     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
914         write!(f, "{} : {}", self.0, self.1)
915     }
916 }
917
918 impl<'tcx> fmt::Display for ty::EquatePredicate<'tcx> {
919     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
920         write!(f, "{} == {}", self.0, self.1)
921     }
922 }
923
924 impl<'tcx> fmt::Debug for ty::TraitPredicate<'tcx> {
925     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
926         write!(f, "TraitPredicate({:?})",
927                self.trait_ref)
928     }
929 }
930
931 impl<'tcx> fmt::Display for ty::TraitPredicate<'tcx> {
932     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
933         write!(f, "{}: {}", self.trait_ref.self_ty(), self.trait_ref)
934     }
935 }
936
937 impl<'tcx> fmt::Debug for ty::ProjectionPredicate<'tcx> {
938     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
939         write!(f, "ProjectionPredicate({:?}, {:?})",
940                self.projection_ty,
941                self.ty)
942     }
943 }
944
945 impl<'tcx> fmt::Display for ty::ProjectionPredicate<'tcx> {
946     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
947         write!(f, "{} == {}",
948                self.projection_ty,
949                self.ty)
950     }
951 }
952
953 impl<'tcx> fmt::Display for ty::ProjectionTy<'tcx> {
954     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
955         write!(f, "{:?}::{}",
956                self.trait_ref,
957                self.item_name)
958     }
959 }
960
961 impl fmt::Display for ty::ClosureKind {
962     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
963         match *self {
964             ty::ClosureKind::Fn => write!(f, "Fn"),
965             ty::ClosureKind::FnMut => write!(f, "FnMut"),
966             ty::ClosureKind::FnOnce => write!(f, "FnOnce"),
967         }
968     }
969 }
970
971 impl<'tcx> fmt::Display for ty::Predicate<'tcx> {
972     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
973         match *self {
974             ty::Predicate::Trait(ref data) => write!(f, "{}", data),
975             ty::Predicate::Equate(ref predicate) => write!(f, "{}", predicate),
976             ty::Predicate::RegionOutlives(ref predicate) => write!(f, "{}", predicate),
977             ty::Predicate::TypeOutlives(ref predicate) => write!(f, "{}", predicate),
978             ty::Predicate::Projection(ref predicate) => write!(f, "{}", predicate),
979             ty::Predicate::WellFormed(ty) => write!(f, "{} well-formed", ty),
980             ty::Predicate::ObjectSafe(trait_def_id) =>
981                 ty::tls::with(|tcx| {
982                     write!(f, "the trait `{}` is object-safe", tcx.item_path_str(trait_def_id))
983                 }),
984             ty::Predicate::ClosureKind(closure_def_id, kind) =>
985                 ty::tls::with(|tcx| {
986                     write!(f, "the closure `{}` implements the trait `{}`",
987                            tcx.item_path_str(closure_def_id), kind)
988                 }),
989         }
990     }
991 }