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