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