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