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