]> git.lizzy.rs Git - rust.git/blob - src/librustc/util/ppaux.rs
222de426432975b72f120bd1fc10a1b975d9017c
[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
12 use middle::def_id::DefId;
13 use middle::subst::{self, Subst};
14 use middle::ty::{BoundRegion, BrAnon, BrNamed};
15 use middle::ty::{ReEarlyBound, BrFresh, ctxt};
16 use middle::ty::{ReFree, ReScope, ReStatic, Region, ReEmpty};
17 use middle::ty::{ReSkolemized, ReVar, BrEnv};
18 use middle::ty::{TyBool, TyChar, TyStruct, TyEnum};
19 use middle::ty::{TyError, TyStr, TyArray, TySlice, TyFloat, TyBareFn};
20 use middle::ty::{TyParam, TyRawPtr, TyRef, TyTuple};
21 use middle::ty::TyClosure;
22 use middle::ty::{TyBox, TyTrait, TyInt, TyUint, TyInfer};
23 use middle::ty::{self, TypeAndMut, Ty, HasTypeFlags};
24 use middle::ty::fold::{self, TypeFoldable};
25
26 use std::fmt;
27 use syntax::abi;
28 use syntax::parse::token;
29 use syntax::ast::DUMMY_NODE_ID;
30 use rustc_front::hir as ast;
31
32 pub fn verbose() -> bool {
33     ty::tls::with(|tcx| tcx.sess.verbose())
34 }
35
36 fn fn_sig(f: &mut fmt::Formatter,
37           inputs: &[Ty],
38           variadic: bool,
39           output: ty::FnOutput)
40           -> fmt::Result {
41     try!(write!(f, "("));
42     let mut inputs = inputs.iter();
43     if let Some(&ty) = inputs.next() {
44         try!(write!(f, "{}", ty));
45         for &ty in inputs {
46             try!(write!(f, ", {}", ty));
47         }
48         if variadic {
49             try!(write!(f, ", ..."));
50         }
51     }
52     try!(write!(f, ")"));
53
54     match output {
55         ty::FnConverging(ty) => {
56             if !ty.is_nil() {
57                 try!(write!(f, " -> {}", ty));
58             }
59             Ok(())
60         }
61         ty::FnDiverging => {
62             write!(f, " -> !")
63         }
64     }
65 }
66
67 fn parameterized<GG>(f: &mut fmt::Formatter,
68                      substs: &subst::Substs,
69                      did: DefId,
70                      projections: &[ty::ProjectionPredicate],
71                      get_generics: GG)
72                      -> fmt::Result
73     where GG: for<'tcx> FnOnce(&ty::ctxt<'tcx>) -> ty::Generics<'tcx>
74 {
75     let (fn_trait_kind, verbose) = try!(ty::tls::with(|tcx| {
76         try!(write!(f, "{}", tcx.item_path_str(did)));
77         Ok((tcx.lang_items.fn_trait_kind(did), tcx.sess.verbose()))
78     }));
79
80     let mut empty = true;
81     let mut start_or_continue = |f: &mut fmt::Formatter, start: &str, cont: &str| {
82         if empty {
83             empty = false;
84             write!(f, "{}", start)
85         } else {
86             write!(f, "{}", cont)
87         }
88     };
89
90     if verbose {
91         match substs.regions {
92             subst::ErasedRegions => {
93                 try!(start_or_continue(f, "<", ", "));
94                 try!(write!(f, ".."));
95             }
96             subst::NonerasedRegions(ref regions) => {
97                 for region in regions {
98                     try!(start_or_continue(f, "<", ", "));
99                     try!(write!(f, "{:?}", region));
100                 }
101             }
102         }
103         for &ty in &substs.types {
104             try!(start_or_continue(f, "<", ", "));
105             try!(write!(f, "{}", ty));
106         }
107         for projection in projections {
108             try!(start_or_continue(f, "<", ", "));
109             try!(write!(f, "{}={}",
110                         projection.projection_ty.item_name,
111                         projection.ty));
112         }
113         return start_or_continue(f, "", ">");
114     }
115
116     if fn_trait_kind.is_some() && projections.len() == 1 {
117         let projection_ty = projections[0].ty;
118         if let TyTuple(ref args) = substs.types.get_slice(subst::TypeSpace)[0].sty {
119             return fn_sig(f, args, false, ty::FnConverging(projection_ty));
120         }
121     }
122
123     match substs.regions {
124         subst::ErasedRegions => { }
125         subst::NonerasedRegions(ref regions) => {
126             for &r in regions {
127                 try!(start_or_continue(f, "<", ", "));
128                 let s = r.to_string();
129                 if s.is_empty() {
130                     // This happens when the value of the region
131                     // parameter is not easily serialized. This may be
132                     // because the user omitted it in the first place,
133                     // or because it refers to some block in the code,
134                     // etc. I'm not sure how best to serialize this.
135                     try!(write!(f, "'_"));
136                 } else {
137                     try!(write!(f, "{}", s));
138                 }
139             }
140         }
141     }
142
143     // It is important to execute this conditionally, only if -Z
144     // verbose is false. Otherwise, debug logs can sometimes cause
145     // ICEs trying to fetch the generics early in the pipeline. This
146     // is kind of a hacky workaround in that -Z verbose is required to
147     // avoid those ICEs.
148     let tps = substs.types.get_slice(subst::TypeSpace);
149     let num_defaults = ty::tls::with(|tcx| {
150         let generics = get_generics(tcx);
151
152         let has_self = substs.self_ty().is_some();
153         let ty_params = generics.types.get_slice(subst::TypeSpace);
154         if ty_params.last().map_or(false, |def| def.default.is_some()) {
155             let substs = tcx.lift(&substs);
156             ty_params.iter().zip(tps).rev().take_while(|&(def, &actual)| {
157                 match def.default {
158                     Some(default) => {
159                         if !has_self && default.has_self_ty() {
160                             // In an object type, there is no `Self`, and
161                             // thus if the default value references Self,
162                             // the user will be required to give an
163                             // explicit value. We can't even do the
164                             // substitution below to check without causing
165                             // an ICE. (#18956).
166                             false
167                         } else {
168                             let default = tcx.lift(&default);
169                             substs.and_then(|substs| default.subst(tcx, substs)) == Some(actual)
170                         }
171                     }
172                     None => false
173                 }
174             }).count()
175         } else {
176             0
177         }
178     });
179
180     for &ty in &tps[..tps.len() - num_defaults] {
181         try!(start_or_continue(f, "<", ", "));
182         try!(write!(f, "{}", ty));
183     }
184
185     for projection in projections {
186         try!(start_or_continue(f, "<", ", "));
187         try!(write!(f, "{}={}",
188                     projection.projection_ty.item_name,
189                     projection.ty));
190     }
191
192     start_or_continue(f, "", ">")
193 }
194
195 fn in_binder<'tcx, T, U>(f: &mut fmt::Formatter,
196                          tcx: &ty::ctxt<'tcx>,
197                          original: &ty::Binder<T>,
198                          lifted: Option<ty::Binder<U>>) -> fmt::Result
199     where T: fmt::Display, U: fmt::Display + TypeFoldable<'tcx>
200 {
201     // Replace any anonymous late-bound regions with named
202     // variants, using gensym'd identifiers, so that we can
203     // clearly differentiate between named and unnamed regions in
204     // the output. We'll probably want to tweak this over time to
205     // decide just how much information to give.
206     let value = if let Some(v) = lifted {
207         v
208     } else {
209         return write!(f, "{}", original.0);
210     };
211
212     let mut empty = true;
213     let mut start_or_continue = |f: &mut fmt::Formatter, start: &str, cont: &str| {
214         if empty {
215             empty = false;
216             write!(f, "{}", start)
217         } else {
218             write!(f, "{}", cont)
219         }
220     };
221
222     let new_value = fold::replace_late_bound_regions(tcx, &value, |br| {
223         let _ = start_or_continue(f, "for<", ", ");
224         ty::ReLateBound(ty::DebruijnIndex::new(1), match br {
225             ty::BrNamed(_, name) => {
226                 let _ = write!(f, "{}", name);
227                 br
228             }
229             ty::BrAnon(_) |
230             ty::BrFresh(_) |
231             ty::BrEnv => {
232                 let name = token::intern("'r");
233                 let _ = write!(f, "{}", name);
234                 ty::BrNamed(DefId::local(DUMMY_NODE_ID), name)
235             }
236         })
237     }).0;
238
239     try!(start_or_continue(f, "", "> "));
240     write!(f, "{}", new_value)
241 }
242
243 /// This curious type is here to help pretty-print trait objects. In
244 /// a trait object, the projections are stored separately from the
245 /// main trait bound, but in fact we want to package them together
246 /// when printing out; they also have separate binders, but we want
247 /// them to share a binder when we print them out. (And the binder
248 /// pretty-printing logic is kind of clever and we don't want to
249 /// reproduce it.) So we just repackage up the structure somewhat.
250 ///
251 /// Right now there is only one trait in an object that can have
252 /// projection bounds, so we just stuff them altogether. But in
253 /// reality we should eventually sort things out better.
254 #[derive(Clone, Debug)]
255 struct TraitAndProjections<'tcx>(ty::TraitRef<'tcx>, Vec<ty::ProjectionPredicate<'tcx>>);
256
257 impl<'tcx> TypeFoldable<'tcx> for TraitAndProjections<'tcx> {
258     fn fold_with<F: fold::TypeFolder<'tcx>>(&self, folder: &mut F)
259                                               -> TraitAndProjections<'tcx> {
260         TraitAndProjections(self.0.fold_with(folder), self.1.fold_with(folder))
261     }
262 }
263
264 impl<'tcx> fmt::Display for TraitAndProjections<'tcx> {
265     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
266         let TraitAndProjections(ref trait_ref, ref projection_bounds) = *self;
267         parameterized(f, trait_ref.substs,
268                       trait_ref.def_id,
269                       projection_bounds,
270                       |tcx| tcx.lookup_trait_def(trait_ref.def_id).generics.clone())
271     }
272 }
273
274 impl<'tcx> fmt::Display for ty::TraitTy<'tcx> {
275     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
276         let bounds = &self.bounds;
277
278         // Generate the main trait ref, including associated types.
279         try!(ty::tls::with(|tcx| {
280             let principal = tcx.lift(&self.principal.0)
281                                .expect("could not lift TraitRef for printing");
282             let projections = tcx.lift(&bounds.projection_bounds[..])
283                                  .expect("could not lift projections for printing");
284             let projections = projections.into_iter().map(|p| p.0).collect();
285
286             let tap = ty::Binder(TraitAndProjections(principal, projections));
287             in_binder(f, tcx, &ty::Binder(""), Some(tap))
288         }));
289
290         // Builtin bounds.
291         for bound in &bounds.builtin_bounds {
292             try!(write!(f, " + {:?}", bound));
293         }
294
295         // FIXME: It'd be nice to compute from context when this bound
296         // is implied, but that's non-trivial -- we'd perhaps have to
297         // use thread-local data of some kind? There are also
298         // advantages to just showing the region, since it makes
299         // people aware that it's there.
300         let bound = bounds.region_bound.to_string();
301         if !bound.is_empty() {
302             try!(write!(f, " + {}", bound));
303         }
304
305         Ok(())
306     }
307 }
308
309 impl<'tcx> fmt::Debug for ty::TypeParameterDef<'tcx> {
310     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
311         write!(f, "TypeParameterDef({}, {}:{}, {:?}/{})",
312                self.name,
313                self.def_id.krate, self.def_id.node,
314                self.space, self.index)
315     }
316 }
317
318 impl fmt::Debug for ty::RegionParameterDef {
319     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
320         write!(f, "RegionParameterDef({}, {}:{}, {:?}/{}, {:?})",
321                self.name,
322                self.def_id.krate, self.def_id.node,
323                self.space, self.index,
324                self.bounds)
325     }
326 }
327
328 impl<'tcx> fmt::Debug for ty::TyS<'tcx> {
329     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
330         write!(f, "{}", *self)
331     }
332 }
333
334 impl<'tcx> fmt::Display for ty::TypeAndMut<'tcx> {
335     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
336         write!(f, "{}{}",
337                if self.mutbl == ast::MutMutable { "mut " } else { "" },
338                self.ty)
339     }
340 }
341
342 impl<'tcx> fmt::Debug for subst::Substs<'tcx> {
343     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
344         write!(f, "Substs[types={:?}, regions={:?}]",
345                self.types, self.regions)
346     }
347 }
348
349 impl<'tcx> fmt::Debug for ty::ItemSubsts<'tcx> {
350     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
351         write!(f, "ItemSubsts({:?})", self.substs)
352     }
353 }
354
355 impl fmt::Debug for subst::RegionSubsts {
356     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
357         match *self {
358             subst::ErasedRegions => write!(f, "erased"),
359             subst::NonerasedRegions(ref regions) => write!(f, "{:?}", regions)
360         }
361     }
362 }
363
364 impl<'tcx> fmt::Debug for ty::TraitRef<'tcx> {
365     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
366         // when printing out the debug representation, we don't need
367         // to enumerate the `for<...>` etc because the debruijn index
368         // tells you everything you need to know.
369         match self.substs.self_ty() {
370             None => write!(f, "{}", *self),
371             Some(self_ty) => write!(f, "<{:?} as {}>", self_ty, *self)
372         }
373     }
374 }
375
376 impl<'tcx> fmt::Debug for ty::TraitDef<'tcx> {
377     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
378         write!(f, "TraitDef(generics={:?}, trait_ref={:?})",
379                self.generics, self.trait_ref)
380     }
381 }
382
383 impl<'tcx, 'container> fmt::Debug for ty::AdtDefData<'tcx, 'container> {
384     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
385         ty::tls::with(|tcx| {
386             write!(f, "{}", tcx.item_path_str(self.did))
387         })
388     }
389 }
390
391 impl fmt::Display for ty::BoundRegion {
392     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
393         if verbose() {
394             return write!(f, "{:?}", *self);
395         }
396
397         match *self {
398             BrNamed(_, name) => write!(f, "{}", name),
399             BrAnon(_) | BrFresh(_) | BrEnv => Ok(())
400         }
401     }
402 }
403
404 impl fmt::Debug for ty::BoundRegion {
405     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
406         match *self {
407             BrAnon(n) => write!(f, "BrAnon({:?})", n),
408             BrFresh(n) => write!(f, "BrFresh({:?})", n),
409             BrNamed(did, name) => {
410                 write!(f, "BrNamed({}:{}, {:?})", did.krate, did.node, name)
411             }
412             BrEnv => "BrEnv".fmt(f),
413         }
414     }
415 }
416
417 impl fmt::Debug for ty::Region {
418     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
419         match *self {
420             ty::ReEarlyBound(ref data) => {
421                 write!(f, "ReEarlyBound({}, {:?}, {}, {})",
422                        data.param_id,
423                        data.space,
424                        data.index,
425                        data.name)
426             }
427
428             ty::ReLateBound(binder_id, ref bound_region) => {
429                 write!(f, "ReLateBound({:?}, {:?})",
430                        binder_id,
431                        bound_region)
432             }
433
434             ty::ReFree(ref fr) => write!(f, "{:?}", fr),
435
436             ty::ReScope(id) => {
437                 write!(f, "ReScope({:?})", id)
438             }
439
440             ty::ReStatic => write!(f, "ReStatic"),
441
442             ty::ReVar(ref vid) => {
443                 write!(f, "{:?}", vid)
444             }
445
446             ty::ReSkolemized(id, ref bound_region) => {
447                 write!(f, "ReSkolemized({}, {:?})", id.index, bound_region)
448             }
449
450             ty::ReEmpty => write!(f, "ReEmpty")
451         }
452     }
453 }
454
455 impl fmt::Display for ty::Region {
456     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
457         if verbose() {
458             return write!(f, "{:?}", *self);
459         }
460
461         // These printouts are concise.  They do not contain all the information
462         // the user might want to diagnose an error, but there is basically no way
463         // to fit that into a short string.  Hence the recommendation to use
464         // `explain_region()` or `note_and_explain_region()`.
465         match *self {
466             ty::ReEarlyBound(ref data) => {
467                 write!(f, "{}", data.name)
468             }
469             ty::ReLateBound(_, br) |
470             ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
471             ty::ReSkolemized(_, br) => {
472                 write!(f, "{}", br)
473             }
474             ty::ReScope(_) |
475             ty::ReVar(_) => Ok(()),
476             ty::ReStatic => write!(f, "'static"),
477             ty::ReEmpty => write!(f, "'<empty>"),
478         }
479     }
480 }
481
482 impl fmt::Debug for ty::FreeRegion {
483     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
484         write!(f, "ReFree({:?}, {:?})",
485                self.scope, self.bound_region)
486     }
487 }
488
489 impl fmt::Debug for ty::ItemVariances {
490     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
491         write!(f, "ItemVariances(types={:?}, regions={:?})",
492                self.types, self.regions)
493     }
494 }
495
496 impl<'tcx> fmt::Debug for ty::GenericPredicates<'tcx> {
497     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
498         write!(f, "GenericPredicates({:?})", self.predicates)
499     }
500 }
501
502 impl<'tcx> fmt::Debug for ty::InstantiatedPredicates<'tcx> {
503     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
504         write!(f, "InstantiatedPredicates({:?})",
505                self.predicates)
506     }
507 }
508
509 impl<'tcx> fmt::Debug for ty::ImplOrTraitItem<'tcx> {
510     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
511         try!(write!(f, "ImplOrTraitItem("));
512         try!(match *self {
513             ty::ImplOrTraitItem::MethodTraitItem(ref i) => write!(f, "{:?}", i),
514             ty::ImplOrTraitItem::ConstTraitItem(ref i) => write!(f, "{:?}", i),
515             ty::ImplOrTraitItem::TypeTraitItem(ref i) => write!(f, "{:?}", i),
516         });
517         write!(f, ")")
518     }
519 }
520
521 impl<'tcx> fmt::Display for ty::FnSig<'tcx> {
522     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
523         try!(write!(f, "fn"));
524         fn_sig(f, &self.inputs, self.variadic, self.output)
525     }
526 }
527
528 impl<'tcx> fmt::Debug for ty::ExistentialBounds<'tcx> {
529     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
530         let mut empty = true;
531         let mut maybe_continue = |f: &mut fmt::Formatter| {
532             if empty {
533                 empty = false;
534                 Ok(())
535             } else {
536                 write!(f, " + ")
537             }
538         };
539
540         let region_str = format!("{:?}", self.region_bound);
541         if !region_str.is_empty() {
542             try!(maybe_continue(f));
543             try!(write!(f, "{}", region_str));
544         }
545
546         for bound in &self.builtin_bounds {
547             try!(maybe_continue(f));
548             try!(write!(f, "{:?}", bound));
549         }
550
551         for projection_bound in &self.projection_bounds {
552             try!(maybe_continue(f));
553             try!(write!(f, "{:?}", projection_bound));
554         }
555
556         Ok(())
557     }
558 }
559
560 impl fmt::Display for ty::BuiltinBounds {
561     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
562         let mut bounds = self.iter();
563         if let Some(bound) = bounds.next() {
564             try!(write!(f, "{:?}", bound));
565             for bound in bounds {
566                 try!(write!(f, " + {:?}", bound));
567             }
568         }
569         Ok(())
570     }
571 }
572
573 // The generic impl doesn't work yet because projections are not
574 // normalized under HRTB.
575 /*impl<T> fmt::Display for ty::Binder<T>
576     where T: fmt::Display + for<'a> ty::Lift<'a>,
577           for<'a> <T as ty::Lift<'a>>::Lifted: fmt::Display + TypeFoldable<'a>
578 {
579     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
580         ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self)))
581     }
582 }*/
583
584 impl<'tcx> fmt::Display for ty::Binder<ty::TraitRef<'tcx>> {
585     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
586         ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self)))
587     }
588 }
589
590 impl<'tcx> fmt::Display for ty::Binder<ty::TraitPredicate<'tcx>> {
591     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
592         ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self)))
593     }
594 }
595
596 impl<'tcx> fmt::Display for ty::Binder<ty::EquatePredicate<'tcx>> {
597     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
598         ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self)))
599     }
600 }
601
602 impl<'tcx> fmt::Display for ty::Binder<ty::ProjectionPredicate<'tcx>> {
603     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
604         ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self)))
605     }
606 }
607
608 impl<'tcx> fmt::Display for ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region>> {
609     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
610         ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self)))
611     }
612 }
613
614 impl fmt::Display for ty::Binder<ty::OutlivesPredicate<ty::Region, ty::Region>> {
615     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
616         ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self)))
617     }
618 }
619
620 impl<'tcx> fmt::Display for ty::TraitRef<'tcx> {
621     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
622         parameterized(f, self.substs, self.def_id, &[],
623                       |tcx| tcx.lookup_trait_def(self.def_id).generics.clone())
624     }
625 }
626
627 pub fn int_ty_to_string(t: ast::IntTy, val: Option<i64>) -> String {
628     let s = match t {
629         ast::TyIs => "isize",
630         ast::TyI8 => "i8",
631         ast::TyI16 => "i16",
632         ast::TyI32 => "i32",
633         ast::TyI64 => "i64"
634     };
635
636     match val {
637         // cast to a u64 so we can correctly print INT64_MIN. All integral types
638         // are parsed as u64, so we wouldn't want to print an extra negative
639         // sign.
640         Some(n) => format!("{}{}", n as u64, s),
641         None => s.to_string()
642     }
643 }
644
645 pub fn uint_ty_to_string(t: ast::UintTy, val: Option<u64>) -> String {
646     let s = match t {
647         ast::TyUs => "usize",
648         ast::TyU8 => "u8",
649         ast::TyU16 => "u16",
650         ast::TyU32 => "u32",
651         ast::TyU64 => "u64"
652     };
653
654     match val {
655         Some(n) => format!("{}{}", n, s),
656         None => s.to_string()
657     }
658 }
659
660
661 pub fn float_ty_to_string(t: ast::FloatTy) -> String {
662     match t {
663         ast::TyF32 => "f32".to_string(),
664         ast::TyF64 => "f64".to_string(),
665     }
666 }
667
668 impl<'tcx> fmt::Display for ty::TypeVariants<'tcx> {
669     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
670         match *self {
671             TyBool => write!(f, "bool"),
672             TyChar => write!(f, "char"),
673             TyInt(t) => write!(f, "{}", int_ty_to_string(t, None)),
674             TyUint(t) => write!(f, "{}", uint_ty_to_string(t, None)),
675             TyFloat(t) => write!(f, "{}", float_ty_to_string(t)),
676             TyBox(typ) => write!(f, "Box<{}>",  typ),
677             TyRawPtr(ref tm) => {
678                 write!(f, "*{} {}", match tm.mutbl {
679                     ast::MutMutable => "mut",
680                     ast::MutImmutable => "const",
681                 },  tm.ty)
682             }
683             TyRef(r, ref tm) => {
684                 try!(write!(f, "&"));
685                 let s = r.to_string();
686                 try!(write!(f, "{}", s));
687                 if !s.is_empty() {
688                     try!(write!(f, " "));
689                 }
690                 write!(f, "{}", tm)
691             }
692             TyTuple(ref tys) => {
693                 try!(write!(f, "("));
694                 let mut tys = tys.iter();
695                 if let Some(&ty) = tys.next() {
696                     try!(write!(f, "{},", ty));
697                     if let Some(&ty) = tys.next() {
698                         try!(write!(f, " {}", ty));
699                         for &ty in tys {
700                             try!(write!(f, ", {}", ty));
701                         }
702                     }
703                 }
704                 write!(f, ")")
705             }
706             TyBareFn(opt_def_id, ref bare_fn) => {
707                 if bare_fn.unsafety == ast::Unsafety::Unsafe {
708                     try!(write!(f, "unsafe "));
709                 }
710
711                 if bare_fn.abi != abi::Rust {
712                     try!(write!(f, "extern {} ", bare_fn.abi));
713                 }
714
715                 try!(write!(f, "{}", bare_fn.sig.0));
716
717                 if let Some(def_id) = opt_def_id {
718                     try!(write!(f, " {{{}}}", ty::tls::with(|tcx| {
719                         tcx.item_path_str(def_id)
720                     })));
721                 }
722                 Ok(())
723             }
724             TyInfer(infer_ty) => write!(f, "{}", infer_ty),
725             TyError => write!(f, "[type error]"),
726             TyParam(ref param_ty) => write!(f, "{}", param_ty),
727             TyEnum(def, substs) | TyStruct(def, substs) => {
728                 ty::tls::with(|tcx| {
729                     if def.did.is_local() &&
730                           !tcx.tcache.borrow().contains_key(&def.did) {
731                         write!(f, "{}<..>", tcx.item_path_str(def.did))
732                     } else {
733                         parameterized(f, substs, def.did, &[],
734                                       |tcx| tcx.lookup_item_type(def.did).generics)
735                     }
736                 })
737             }
738             TyTrait(ref data) => write!(f, "{}", data),
739             ty::TyProjection(ref data) => write!(f, "{}", data),
740             TyStr => write!(f, "str"),
741             TyClosure(ref did, ref substs) => ty::tls::with(|tcx| {
742                 try!(write!(f, "[closure"));
743
744                 if did.is_local() {
745                     try!(write!(f, "@{:?}", tcx.map.span(did.node)));
746                     let mut sep = " ";
747                     try!(tcx.with_freevars(did.node, |freevars| {
748                         for (freevar, upvar_ty) in freevars.iter().zip(&substs.upvar_tys) {
749                             let node_id = freevar.def.local_node_id();
750                             try!(write!(f,
751                                         "{}{}:{}",
752                                         sep,
753                                         tcx.local_var_name_str(node_id),
754                                         upvar_ty));
755                             sep = ", ";
756                         }
757                         Ok(())
758                     }))
759                 } else {
760                     // cross-crate closure types should only be
761                     // visible in trans bug reports, I imagine.
762                     try!(write!(f, "@{:?}", did));
763                     let mut sep = " ";
764                     for (index, upvar_ty) in substs.upvar_tys.iter().enumerate() {
765                         try!(write!(f, "{}{}:{}", sep, index, upvar_ty));
766                         sep = ", ";
767                     }
768                 }
769
770                 write!(f, "]")
771             }),
772             TyArray(ty, sz) => write!(f, "[{}; {}]",  ty, sz),
773             TySlice(ty) => write!(f, "[{}]",  ty)
774         }
775     }
776 }
777
778 impl<'tcx> fmt::Display for ty::TyS<'tcx> {
779     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
780         write!(f, "{}", self.sty)
781     }
782 }
783
784 impl fmt::Debug for ty::UpvarId {
785     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
786         write!(f, "UpvarId({};`{}`;{})",
787                self.var_id,
788                ty::tls::with(|tcx| tcx.local_var_name_str(self.var_id)),
789                self.closure_expr_id)
790     }
791 }
792
793 impl fmt::Debug for ty::UpvarBorrow {
794     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
795         write!(f, "UpvarBorrow({:?}, {:?})",
796                self.kind, self.region)
797     }
798 }
799
800 impl fmt::Display for ty::InferTy {
801     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
802         let print_var_ids = verbose();
803         match *self {
804             ty::TyVar(ref vid) if print_var_ids => write!(f, "{:?}", vid),
805             ty::IntVar(ref vid) if print_var_ids => write!(f, "{:?}", vid),
806             ty::FloatVar(ref vid) if print_var_ids => write!(f, "{:?}", vid),
807             ty::TyVar(_) | ty::IntVar(_) | ty::FloatVar(_) => write!(f, "_"),
808             ty::FreshTy(v) => write!(f, "FreshTy({})", v),
809             ty::FreshIntTy(v) => write!(f, "FreshIntTy({})", v),
810             ty::FreshFloatTy(v) => write!(f, "FreshFloatTy({})", v)
811         }
812     }
813 }
814
815 impl fmt::Display for ty::ExplicitSelfCategory {
816     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
817         f.write_str(match *self {
818             ty::StaticExplicitSelfCategory => "static",
819             ty::ByValueExplicitSelfCategory => "self",
820             ty::ByReferenceExplicitSelfCategory(_, ast::MutMutable) => {
821                 "&mut self"
822             }
823             ty::ByReferenceExplicitSelfCategory(_, ast::MutImmutable) => "&self",
824             ty::ByBoxExplicitSelfCategory => "Box<self>",
825         })
826     }
827 }
828
829 impl fmt::Display for ty::ParamTy {
830     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
831         write!(f, "{}", self.name)
832     }
833 }
834
835 impl fmt::Debug for ty::ParamTy {
836     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
837         write!(f, "{}/{:?}.{}", self, self.space, self.idx)
838     }
839 }
840
841 impl<'tcx, T, U> fmt::Display for ty::OutlivesPredicate<T,U>
842     where T: fmt::Display, U: fmt::Display
843 {
844     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
845         write!(f, "{} : {}", self.0, self.1)
846     }
847 }
848
849 impl<'tcx> fmt::Display for ty::EquatePredicate<'tcx> {
850     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
851         write!(f, "{} == {}", self.0, self.1)
852     }
853 }
854
855 impl<'tcx> fmt::Debug for ty::TraitPredicate<'tcx> {
856     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
857         write!(f, "TraitPredicate({:?})",
858                self.trait_ref)
859     }
860 }
861
862 impl<'tcx> fmt::Display for ty::TraitPredicate<'tcx> {
863     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
864         write!(f, "{} : {}",
865                self.trait_ref.self_ty(),
866                self.trait_ref)
867     }
868 }
869
870 impl<'tcx> fmt::Debug for ty::ProjectionPredicate<'tcx> {
871     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
872         write!(f, "ProjectionPredicate({:?}, {:?})",
873                self.projection_ty,
874                self.ty)
875     }
876 }
877
878 impl<'tcx> fmt::Display for ty::ProjectionPredicate<'tcx> {
879     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
880         write!(f, "{} == {}",
881                self.projection_ty,
882                self.ty)
883     }
884 }
885
886 impl<'tcx> fmt::Display for ty::ProjectionTy<'tcx> {
887     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
888         write!(f, "{:?}::{}",
889                self.trait_ref,
890                self.item_name)
891     }
892 }
893
894 impl<'tcx> fmt::Display for ty::Predicate<'tcx> {
895     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
896         match *self {
897             ty::Predicate::Trait(ref data) => write!(f, "{}", data),
898             ty::Predicate::Equate(ref predicate) => write!(f, "{}", predicate),
899             ty::Predicate::RegionOutlives(ref predicate) => write!(f, "{}", predicate),
900             ty::Predicate::TypeOutlives(ref predicate) => write!(f, "{}", predicate),
901             ty::Predicate::Projection(ref predicate) => write!(f, "{}", predicate),
902             ty::Predicate::WellFormed(ty) => write!(f, "{} well-formed", ty),
903             ty::Predicate::ObjectSafe(trait_def_id) =>
904                 ty::tls::with(|tcx| {
905                     write!(f, "the trait `{}` is object-safe", tcx.item_path_str(trait_def_id))
906                 }),
907         }
908     }
909 }