]> git.lizzy.rs Git - rust.git/blob - src/librustc/util/ppaux.rs
2d433369366eb9f4d397c0ae851eb1f02eab29ea
[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;
13 use middle::subst::{VecPerParamSpace,Subst};
14 use middle::subst;
15 use middle::ty::{BoundRegion, BrAnon, BrNamed};
16 use middle::ty::{ReEarlyBound, BrFresh, ctxt};
17 use middle::ty::{ReFree, ReScope, ReInfer, ReStatic, Region, ReEmpty};
18 use middle::ty::{ReSkolemized, ReVar, BrEnv};
19 use middle::ty::{mt, Ty, ParamTy};
20 use middle::ty::{ty_bool, ty_char, ty_struct, ty_enum};
21 use middle::ty::{ty_err, ty_str, ty_vec, ty_float, ty_bare_fn};
22 use middle::ty::{ty_param, ty_ptr, ty_rptr, ty_tup, ty_open};
23 use middle::ty::{ty_unboxed_closure};
24 use middle::ty::{ty_uniq, ty_trait, ty_int, ty_uint, ty_infer};
25 use middle::ty;
26 use middle::ty_fold::TypeFoldable;
27
28 use std::collections::HashMap;
29 use std::hash::{Hash, Hasher};
30 use std::rc::Rc;
31 use syntax::abi;
32 use syntax::ast_map;
33 use syntax::codemap::{Span, Pos};
34 use syntax::parse::token;
35 use syntax::print::pprust;
36 use syntax::ptr::P;
37 use syntax::{ast, ast_util};
38 use syntax::owned_slice::OwnedSlice;
39
40 /// Produces a string suitable for debugging output.
41 pub trait Repr<'tcx> {
42     fn repr(&self, tcx: &ctxt<'tcx>) -> String;
43 }
44
45 /// Produces a string suitable for showing to the user.
46 pub trait UserString<'tcx> : Repr<'tcx> {
47     fn user_string(&self, tcx: &ctxt<'tcx>) -> String;
48 }
49
50 pub fn note_and_explain_region(cx: &ctxt,
51                                prefix: &str,
52                                region: ty::Region,
53                                suffix: &str) -> Option<Span> {
54     match explain_region_and_span(cx, region) {
55       (ref str, Some(span)) => {
56         cx.sess.span_note(
57             span,
58             format!("{}{}{}", prefix, *str, suffix).index(&FullRange));
59         Some(span)
60       }
61       (ref str, None) => {
62         cx.sess.note(
63             format!("{}{}{}", prefix, *str, suffix).index(&FullRange));
64         None
65       }
66     }
67 }
68
69 /// When a free region is associated with `item`, how should we describe the item in the error
70 /// message.
71 fn item_scope_tag(item: &ast::Item) -> &'static str {
72     match item.node {
73         ast::ItemImpl(..) => "impl",
74         ast::ItemStruct(..) => "struct",
75         ast::ItemEnum(..) => "enum",
76         ast::ItemTrait(..) => "trait",
77         ast::ItemFn(..) => "function body",
78         _ => "item"
79     }
80 }
81
82 pub fn explain_region_and_span(cx: &ctxt, region: ty::Region)
83                             -> (String, Option<Span>) {
84     return match region {
85       ReScope(scope) => {
86         match cx.map.find(scope.node_id()) {
87           Some(ast_map::NodeBlock(ref blk)) => {
88             explain_span(cx, "block", blk.span)
89           }
90           Some(ast_map::NodeExpr(expr)) => {
91             match expr.node {
92               ast::ExprCall(..) => explain_span(cx, "call", expr.span),
93               ast::ExprMethodCall(..) => {
94                 explain_span(cx, "method call", expr.span)
95               },
96               ast::ExprMatch(_, _, ast::MatchSource::IfLetDesugar { .. }) =>
97                   explain_span(cx, "if let", expr.span),
98               ast::ExprMatch(_, _, ast::MatchSource::WhileLetDesugar) => {
99                   explain_span(cx, "while let", expr.span)
100               },
101               ast::ExprMatch(..) => explain_span(cx, "match", expr.span),
102               _ => explain_span(cx, "expression", expr.span)
103             }
104           }
105           Some(ast_map::NodeStmt(stmt)) => {
106               explain_span(cx, "statement", stmt.span)
107           }
108           Some(ast_map::NodeItem(it)) => {
109               let tag = item_scope_tag(&*it);
110               explain_span(cx, tag, it.span)
111           }
112           Some(_) | None => {
113             // this really should not happen
114             (format!("unknown scope: {:?}.  Please report a bug.", scope), None)
115           }
116         }
117       }
118
119       ReFree(ref fr) => {
120         let prefix = match fr.bound_region {
121           BrAnon(idx) => {
122               format!("the anonymous lifetime #{} defined on", idx + 1)
123           }
124           BrFresh(_) => "an anonymous lifetime defined on".to_string(),
125           _ => {
126               format!("the lifetime {} as defined on",
127                       bound_region_ptr_to_string(cx, fr.bound_region))
128           }
129         };
130
131         match cx.map.find(fr.scope.node_id()) {
132           Some(ast_map::NodeBlock(ref blk)) => {
133               let (msg, opt_span) = explain_span(cx, "block", blk.span);
134               (format!("{} {}", prefix, msg), opt_span)
135           }
136           Some(ast_map::NodeItem(it)) => {
137               let tag = item_scope_tag(&*it);
138               let (msg, opt_span) = explain_span(cx, tag, it.span);
139               (format!("{} {}", prefix, msg), opt_span)
140           }
141           Some(_) | None => {
142               // this really should not happen
143               (format!("{} unknown free region bounded by scope {:?}", prefix, fr.scope), None)
144           }
145         }
146       }
147
148       ReStatic => { ("the static lifetime".to_string(), None) }
149
150       ReEmpty => { ("the empty lifetime".to_string(), None) }
151
152       ReEarlyBound(_, _, _, name) => {
153         (format!("{}", token::get_name(name)), None)
154       }
155
156       // I believe these cases should not occur (except when debugging,
157       // perhaps)
158       ty::ReInfer(_) | ty::ReLateBound(..) => {
159         (format!("lifetime {:?}", region), None)
160       }
161     };
162
163     fn explain_span(cx: &ctxt, heading: &str, span: Span)
164                     -> (String, Option<Span>) {
165         let lo = cx.sess.codemap().lookup_char_pos_adj(span.lo);
166         (format!("the {} at {}:{}", heading, lo.line, lo.col.to_uint()),
167          Some(span))
168     }
169 }
170
171 pub fn bound_region_ptr_to_string(cx: &ctxt, br: BoundRegion) -> String {
172     bound_region_to_string(cx, "", false, br)
173 }
174
175 pub fn bound_region_to_string(cx: &ctxt,
176                            prefix: &str, space: bool,
177                            br: BoundRegion) -> String {
178     let space_str = if space { " " } else { "" };
179
180     if cx.sess.verbose() {
181         return format!("{}{}{}", prefix, br.repr(cx), space_str)
182     }
183
184     match br {
185         BrNamed(_, name) => {
186             format!("{}{}{}", prefix, token::get_name(name), space_str)
187         }
188         BrAnon(_) | BrFresh(_) | BrEnv => prefix.to_string()
189     }
190 }
191
192 // In general, if you are giving a region error message,
193 // you should use `explain_region()` or, better yet,
194 // `note_and_explain_region()`
195 pub fn region_ptr_to_string(cx: &ctxt, region: Region) -> String {
196     region_to_string(cx, "&", true, region)
197 }
198
199 pub fn region_to_string(cx: &ctxt, prefix: &str, space: bool, region: Region) -> String {
200     let space_str = if space { " " } else { "" };
201
202     if cx.sess.verbose() {
203         return format!("{}{}{}", prefix, region.repr(cx), space_str)
204     }
205
206     // These printouts are concise.  They do not contain all the information
207     // the user might want to diagnose an error, but there is basically no way
208     // to fit that into a short string.  Hence the recommendation to use
209     // `explain_region()` or `note_and_explain_region()`.
210     match region {
211         ty::ReScope(_) => prefix.to_string(),
212         ty::ReEarlyBound(_, _, _, name) => {
213             token::get_name(name).get().to_string()
214         }
215         ty::ReLateBound(_, br) => bound_region_to_string(cx, prefix, space, br),
216         ty::ReFree(ref fr) => bound_region_to_string(cx, prefix, space, fr.bound_region),
217         ty::ReInfer(ReSkolemized(_, br)) => {
218             bound_region_to_string(cx, prefix, space, br)
219         }
220         ty::ReInfer(ReVar(_)) => prefix.to_string(),
221         ty::ReStatic => format!("{}'static{}", prefix, space_str),
222         ty::ReEmpty => format!("{}'<empty>{}", prefix, space_str),
223     }
224 }
225
226 pub fn mutability_to_string(m: ast::Mutability) -> String {
227     match m {
228         ast::MutMutable => "mut ".to_string(),
229         ast::MutImmutable => "".to_string(),
230     }
231 }
232
233 pub fn mt_to_string<'tcx>(cx: &ctxt<'tcx>, m: &mt<'tcx>) -> String {
234     format!("{}{}",
235         mutability_to_string(m.mutbl),
236         ty_to_string(cx, m.ty))
237 }
238
239 pub fn trait_store_to_string(cx: &ctxt, s: ty::TraitStore) -> String {
240     match s {
241         ty::UniqTraitStore => "Box ".to_string(),
242         ty::RegionTraitStore(r, m) => {
243             format!("{}{}", region_ptr_to_string(cx, r), mutability_to_string(m))
244         }
245     }
246 }
247
248 pub fn vec_map_to_string<T, F>(ts: &[T], f: F) -> String where
249     F: FnMut(&T) -> String,
250 {
251     let tstrs = ts.iter().map(f).collect::<Vec<String>>();
252     format!("[{}]", tstrs.connect(", "))
253 }
254
255 pub fn ty_to_string<'tcx>(cx: &ctxt<'tcx>, typ: &ty::TyS<'tcx>) -> String {
256     fn bare_fn_to_string<'tcx>(cx: &ctxt<'tcx>,
257                                opt_def_id: Option<ast::DefId>,
258                                unsafety: ast::Unsafety,
259                                abi: abi::Abi,
260                                ident: Option<ast::Ident>,
261                                sig: &ty::PolyFnSig<'tcx>)
262                                -> String {
263         let mut s = String::new();
264
265         match unsafety {
266             ast::Unsafety::Normal => {}
267             ast::Unsafety::Unsafe => {
268                 s.push_str(unsafety.to_string().as_slice());
269                 s.push(' ');
270             }
271         };
272
273         if abi != abi::Rust {
274             s.push_str(format!("extern {} ", abi.to_string()).index(&FullRange));
275         };
276
277         s.push_str("fn");
278
279         match ident {
280             Some(i) => {
281                 s.push(' ');
282                 s.push_str(token::get_ident(i).get());
283             }
284             _ => { }
285         }
286
287         push_sig_to_string(cx, &mut s, '(', ')', sig, "");
288
289         match opt_def_id {
290             Some(def_id) => {
291                 s.push_str(" {");
292                 let path_str = ty::item_path_str(cx, def_id);
293                 s.push_str(path_str.index(&FullRange));
294                 s.push_str("}");
295             }
296             None => { }
297         }
298
299         s
300     }
301
302     fn closure_to_string<'tcx>(cx: &ctxt<'tcx>, cty: &ty::ClosureTy<'tcx>) -> String {
303         let mut s = String::new();
304
305         match cty.store {
306             ty::UniqTraitStore => {}
307             ty::RegionTraitStore(region, _) => {
308                 s.push_str(region_to_string(cx, "", true, region).index(&FullRange));
309             }
310         }
311
312         match cty.unsafety {
313             ast::Unsafety::Normal => {}
314             ast::Unsafety::Unsafe => {
315                 s.push_str(cty.unsafety.to_string().as_slice());
316                 s.push(' ');
317             }
318         };
319
320         let bounds_str = cty.bounds.user_string(cx);
321
322         match cty.store {
323             ty::UniqTraitStore => {
324                 assert_eq!(cty.onceness, ast::Once);
325                 s.push_str("proc");
326                 push_sig_to_string(cx, &mut s, '(', ')', &cty.sig,
327                                    bounds_str.index(&FullRange));
328             }
329             ty::RegionTraitStore(..) => {
330                 match cty.onceness {
331                     ast::Many => {}
332                     ast::Once => s.push_str("once ")
333                 }
334                 push_sig_to_string(cx, &mut s, '|', '|', &cty.sig,
335                                    bounds_str.index(&FullRange));
336             }
337         }
338
339         s
340     }
341
342     fn push_sig_to_string<'tcx>(cx: &ctxt<'tcx>,
343                                 s: &mut String,
344                                 bra: char,
345                                 ket: char,
346                                 sig: &ty::PolyFnSig<'tcx>,
347                                 bounds: &str) {
348         s.push(bra);
349         let strs = sig.0.inputs
350             .iter()
351             .map(|a| ty_to_string(cx, *a))
352             .collect::<Vec<_>>();
353         s.push_str(strs.connect(", ").as_slice());
354         if sig.0.variadic {
355             s.push_str(", ...");
356         }
357         s.push(ket);
358
359         if !bounds.is_empty() {
360             s.push_str(":");
361             s.push_str(bounds);
362         }
363
364         match sig.0.output {
365             ty::FnConverging(t) => {
366                 if !ty::type_is_nil(t) {
367                    s.push_str(" -> ");
368                    s.push_str(ty_to_string(cx, t).index(&FullRange));
369                 }
370             }
371             ty::FnDiverging => {
372                 s.push_str(" -> !");
373             }
374         }
375     }
376
377     fn infer_ty_to_string(cx: &ctxt, ty: ty::InferTy) -> String {
378         let print_var_ids = cx.sess.verbose();
379         match ty {
380             ty::TyVar(ref vid) if print_var_ids => vid.repr(cx),
381             ty::IntVar(ref vid) if print_var_ids => vid.repr(cx),
382             ty::FloatVar(ref vid) if print_var_ids => vid.repr(cx),
383             ty::TyVar(_) | ty::IntVar(_) | ty::FloatVar(_) => format!("_"),
384             ty::FreshTy(v) => format!("FreshTy({})", v),
385             ty::FreshIntTy(v) => format!("FreshIntTy({})", v)
386         }
387     }
388
389     // pretty print the structural type representation:
390     match typ.sty {
391         ty_bool => "bool".to_string(),
392         ty_char => "char".to_string(),
393         ty_int(t) => ast_util::int_ty_to_string(t, None).to_string(),
394         ty_uint(t) => ast_util::uint_ty_to_string(t, None).to_string(),
395         ty_float(t) => ast_util::float_ty_to_string(t).to_string(),
396         ty_uniq(typ) => format!("Box<{}>", ty_to_string(cx, typ)),
397         ty_ptr(ref tm) => {
398             format!("*{} {}", match tm.mutbl {
399                 ast::MutMutable => "mut",
400                 ast::MutImmutable => "const",
401             }, ty_to_string(cx, tm.ty))
402         }
403         ty_rptr(r, ref tm) => {
404             let mut buf = region_ptr_to_string(cx, *r);
405             buf.push_str(mt_to_string(cx, tm).index(&FullRange));
406             buf
407         }
408         ty_open(typ) =>
409             format!("opened<{}>", ty_to_string(cx, typ)),
410         ty_tup(ref elems) => {
411             let strs = elems
412                 .iter()
413                 .map(|elem| ty_to_string(cx, *elem))
414                 .collect::<Vec<_>>();
415             match strs.index(&FullRange) {
416                 [ref string] => format!("({},)", string),
417                 strs => format!("({})", strs.connect(", "))
418             }
419         }
420         ty_bare_fn(opt_def_id, ref f) => {
421             bare_fn_to_string(cx, opt_def_id, f.unsafety, f.abi, None, &f.sig)
422         }
423         ty_infer(infer_ty) => infer_ty_to_string(cx, infer_ty),
424         ty_err => "[type error]".to_string(),
425         ty_param(ref param_ty) => {
426             if cx.sess.verbose() {
427                 param_ty.repr(cx)
428             } else {
429                 param_ty.user_string(cx)
430             }
431         }
432         ty_enum(did, substs) | ty_struct(did, substs) => {
433             let base = ty::item_path_str(cx, did);
434             let generics = ty::lookup_item_type(cx, did).generics;
435             parameterized(cx, base.as_slice(), substs, &generics, did)
436         }
437         ty_trait(box ty::TyTrait {
438             ref principal, ref bounds
439         }) => {
440             let principal = principal.user_string(cx);
441             let bound_str = bounds.user_string(cx);
442             let bound_sep = if bound_str.is_empty() { "" } else { " + " };
443             format!("{}{}{}",
444                     principal,
445                     bound_sep,
446                     bound_str)
447         }
448         ty::ty_projection(ref data) => {
449             format!("<{} as {}>::{}",
450                     data.trait_ref.self_ty().user_string(cx),
451                     data.trait_ref.user_string(cx),
452                     data.item_name.user_string(cx))
453         }
454         ty_str => "str".to_string(),
455         ty_unboxed_closure(ref did, _, substs) => {
456             let unboxed_closures = cx.unboxed_closures.borrow();
457             unboxed_closures.get(did).map(|cl| {
458                 closure_to_string(cx, &cl.closure_type.subst(cx, substs))
459             }).unwrap_or_else(|| {
460                 if did.krate == ast::LOCAL_CRATE {
461                     let span = cx.map.span(did.node);
462                     format!("closure[{}]", span.repr(cx))
463                 } else {
464                     format!("closure")
465                 }
466             })
467         }
468         ty_vec(t, sz) => {
469             let inner_str = ty_to_string(cx, t);
470             match sz {
471                 Some(n) => format!("[{}; {}]", inner_str, n),
472                 None => format!("[{}]", inner_str),
473             }
474         }
475     }
476 }
477
478 pub fn explicit_self_category_to_str(category: &ty::ExplicitSelfCategory)
479                                      -> &'static str {
480     match *category {
481         ty::StaticExplicitSelfCategory => "static",
482         ty::ByValueExplicitSelfCategory => "self",
483         ty::ByReferenceExplicitSelfCategory(_, ast::MutMutable) => {
484             "&mut self"
485         }
486         ty::ByReferenceExplicitSelfCategory(_, ast::MutImmutable) => "&self",
487         ty::ByBoxExplicitSelfCategory => "Box<self>",
488     }
489 }
490
491 pub fn parameterized<'tcx>(cx: &ctxt<'tcx>,
492                            base: &str,
493                            substs: &subst::Substs<'tcx>,
494                            generics: &ty::Generics<'tcx>,
495                            did: ast::DefId)
496                            -> String
497 {
498     if cx.sess.verbose() {
499         if substs.is_noop() {
500             return format!("{}", base);
501         } else {
502             return format!("{}<{},{}>",
503                            base,
504                            substs.regions.repr(cx),
505                            substs.types.repr(cx));
506         }
507     }
508
509     let mut strs = Vec::new();
510
511     match substs.regions {
512         subst::ErasedRegions => { }
513         subst::NonerasedRegions(ref regions) => {
514             for &r in regions.iter() {
515                 let s = region_to_string(cx, "", false, r);
516                 if s.is_empty() {
517                     // This happens when the value of the region
518                     // parameter is not easily serialized. This may be
519                     // because the user omitted it in the first place,
520                     // or because it refers to some block in the code,
521                     // etc. I'm not sure how best to serialize this.
522                     strs.push(format!("'_"));
523                 } else {
524                     strs.push(s)
525                 }
526             }
527         }
528     }
529
530     let tps = substs.types.get_slice(subst::TypeSpace);
531     let ty_params = generics.types.get_slice(subst::TypeSpace);
532     let has_defaults = ty_params.last().map_or(false, |def| def.default.is_some());
533     let num_defaults = if has_defaults {
534         ty_params.iter().zip(tps.iter()).rev().take_while(|&(def, &actual)| {
535             match def.default {
536                 Some(default) => default.subst(cx, substs) == actual,
537                 None => false
538             }
539         }).count()
540     } else {
541         0
542     };
543
544     for t in tps.index(&(0..(tps.len() - num_defaults))).iter() {
545         strs.push(ty_to_string(cx, *t))
546     }
547
548     if cx.lang_items.fn_trait_kind(did).is_some() {
549         format!("{}({}){}",
550                 base,
551                 if strs[0].starts_with("(") && strs[0].ends_with(",)") {
552                     strs[0].index(&(1 .. (strs[0].len() - 2))) // Remove '(' and ',)'
553                 } else if strs[0].starts_with("(") && strs[0].ends_with(")") {
554                     strs[0].index(&(1 .. (strs[0].len() - 1))) // Remove '(' and ')'
555                 } else {
556                     strs[0].index(&FullRange)
557                 },
558                 if &*strs[1] == "()" { String::new() } else { format!(" -> {}", strs[1]) })
559     } else if strs.len() > 0 {
560         format!("{}<{}>", base, strs.connect(", "))
561     } else {
562         format!("{}", base)
563     }
564 }
565
566 pub fn ty_to_short_str<'tcx>(cx: &ctxt<'tcx>, typ: Ty<'tcx>) -> String {
567     let mut s = typ.repr(cx).to_string();
568     if s.len() >= 32u {
569         s = s.index(&(0u..32u)).to_string();
570     }
571     return s;
572 }
573
574 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for Option<T> {
575     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
576         match self {
577             &None => "None".to_string(),
578             &Some(ref t) => t.repr(tcx),
579         }
580     }
581 }
582
583 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for P<T> {
584     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
585         (*self).repr(tcx)
586     }
587 }
588
589 impl<'tcx,T:Repr<'tcx>,U:Repr<'tcx>> Repr<'tcx> for Result<T,U> {
590     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
591         match self {
592             &Ok(ref t) => t.repr(tcx),
593             &Err(ref u) => format!("Err({})", u.repr(tcx))
594         }
595     }
596 }
597
598 impl<'tcx> Repr<'tcx> for () {
599     fn repr(&self, _tcx: &ctxt) -> String {
600         "()".to_string()
601     }
602 }
603
604 impl<'a, 'tcx, T: ?Sized +Repr<'tcx>> Repr<'tcx> for &'a T {
605     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
606         Repr::repr(*self, tcx)
607     }
608 }
609
610 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for Rc<T> {
611     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
612         (&**self).repr(tcx)
613     }
614 }
615
616 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for Box<T> {
617     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
618         (&**self).repr(tcx)
619     }
620 }
621
622 fn repr_vec<'tcx, T:Repr<'tcx>>(tcx: &ctxt<'tcx>, v: &[T]) -> String {
623     vec_map_to_string(v, |t| t.repr(tcx))
624 }
625
626 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for [T] {
627     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
628         repr_vec(tcx, self)
629     }
630 }
631
632 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for OwnedSlice<T> {
633     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
634         repr_vec(tcx, self.index(&FullRange))
635     }
636 }
637
638 // This is necessary to handle types like Option<~[T]>, for which
639 // autoderef cannot convert the &[T] handler
640 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for Vec<T> {
641     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
642         repr_vec(tcx, self.index(&FullRange))
643     }
644 }
645
646 impl<'tcx, T:UserString<'tcx>> UserString<'tcx> for Vec<T> {
647     fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
648         let strs: Vec<String> =
649             self.iter().map(|t| t.user_string(tcx)).collect();
650         strs.connect(", ")
651     }
652 }
653
654 impl<'tcx> Repr<'tcx> for def::Def {
655     fn repr(&self, _tcx: &ctxt) -> String {
656         format!("{:?}", *self)
657     }
658 }
659
660 impl<'tcx> Repr<'tcx> for ty::TypeParameterDef<'tcx> {
661     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
662         format!("TypeParameterDef({:?}, {}, {:?}/{})",
663                 self.def_id,
664                 self.bounds.repr(tcx),
665                 self.space,
666                 self.index)
667     }
668 }
669
670 impl<'tcx> Repr<'tcx> for ty::RegionParameterDef {
671     fn repr(&self, tcx: &ctxt) -> String {
672         format!("RegionParameterDef(name={}, def_id={}, bounds={})",
673                 token::get_name(self.name),
674                 self.def_id.repr(tcx),
675                 self.bounds.repr(tcx))
676     }
677 }
678
679 impl<'tcx> Repr<'tcx> for ty::TyS<'tcx> {
680     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
681         ty_to_string(tcx, self)
682     }
683 }
684
685 impl<'tcx> Repr<'tcx> for ty::mt<'tcx> {
686     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
687         mt_to_string(tcx, self)
688     }
689 }
690
691 impl<'tcx> Repr<'tcx> for subst::Substs<'tcx> {
692     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
693         format!("Substs[types={}, regions={}]",
694                        self.types.repr(tcx),
695                        self.regions.repr(tcx))
696     }
697 }
698
699 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for subst::VecPerParamSpace<T> {
700     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
701         format!("[{};{};{}]",
702                 self.get_slice(subst::TypeSpace).repr(tcx),
703                 self.get_slice(subst::SelfSpace).repr(tcx),
704                 self.get_slice(subst::FnSpace).repr(tcx))
705     }
706 }
707
708 impl<'tcx> Repr<'tcx> for ty::ItemSubsts<'tcx> {
709     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
710         format!("ItemSubsts({})", self.substs.repr(tcx))
711     }
712 }
713
714 impl<'tcx> Repr<'tcx> for subst::RegionSubsts {
715     fn repr(&self, tcx: &ctxt) -> String {
716         match *self {
717             subst::ErasedRegions => "erased".to_string(),
718             subst::NonerasedRegions(ref regions) => regions.repr(tcx)
719         }
720     }
721 }
722
723 impl<'tcx> Repr<'tcx> for ty::BuiltinBounds {
724     fn repr(&self, _tcx: &ctxt) -> String {
725         let mut res = Vec::new();
726         for b in self.iter() {
727             res.push(match b {
728                 ty::BoundSend => "Send".to_string(),
729                 ty::BoundSized => "Sized".to_string(),
730                 ty::BoundCopy => "Copy".to_string(),
731                 ty::BoundSync => "Sync".to_string(),
732             });
733         }
734         res.connect("+")
735     }
736 }
737
738 impl<'tcx> Repr<'tcx> for ty::ExistentialBounds<'tcx> {
739     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
740         self.user_string(tcx)
741     }
742 }
743
744 impl<'tcx> Repr<'tcx> for ty::ParamBounds<'tcx> {
745     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
746         let mut res = Vec::new();
747         res.push(self.builtin_bounds.repr(tcx));
748         for t in self.trait_bounds.iter() {
749             res.push(t.repr(tcx));
750         }
751         res.connect("+")
752     }
753 }
754
755 impl<'tcx> Repr<'tcx> for ty::TraitRef<'tcx> {
756     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
757         // when printing out the debug representation, we don't need
758         // to enumerate the `for<...>` etc because the debruijn index
759         // tells you everything you need to know.
760         let base = ty::item_path_str(tcx, self.def_id);
761         let trait_def = ty::lookup_trait_def(tcx, self.def_id);
762         format!("TraitRef({}, {})",
763                 self.substs.self_ty().repr(tcx),
764                 parameterized(tcx, base.as_slice(), self.substs, &trait_def.generics, self.def_id))
765     }
766 }
767
768 impl<'tcx> Repr<'tcx> for ty::TraitDef<'tcx> {
769     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
770         format!("TraitDef(generics={}, bounds={}, trait_ref={})",
771                 self.generics.repr(tcx),
772                 self.bounds.repr(tcx),
773                 self.trait_ref.repr(tcx))
774     }
775 }
776
777 impl<'tcx> Repr<'tcx> for ast::TraitItem {
778     fn repr(&self, _tcx: &ctxt) -> String {
779         match *self {
780             ast::RequiredMethod(ref data) => format!("RequiredMethod({}, id={})",
781                                                      data.ident, data.id),
782             ast::ProvidedMethod(ref data) => format!("ProvidedMethod(id={})",
783                                                      data.id),
784             ast::TypeTraitItem(ref data) => format!("TypeTraitItem({}, id={})",
785                                                      data.ty_param.ident, data.ty_param.id),
786         }
787     }
788 }
789
790 impl<'tcx> Repr<'tcx> for ast::Expr {
791     fn repr(&self, _tcx: &ctxt) -> String {
792         format!("expr({}: {})", self.id, pprust::expr_to_string(self))
793     }
794 }
795
796 impl<'tcx> Repr<'tcx> for ast::Path {
797     fn repr(&self, _tcx: &ctxt) -> String {
798         format!("path({})", pprust::path_to_string(self))
799     }
800 }
801
802 impl<'tcx> UserString<'tcx> for ast::Path {
803     fn user_string(&self, _tcx: &ctxt) -> String {
804         pprust::path_to_string(self)
805     }
806 }
807
808 impl<'tcx> Repr<'tcx> for ast::Ty {
809     fn repr(&self, _tcx: &ctxt) -> String {
810         format!("type({})", pprust::ty_to_string(self))
811     }
812 }
813
814 impl<'tcx> Repr<'tcx> for ast::Item {
815     fn repr(&self, tcx: &ctxt) -> String {
816         format!("item({})", tcx.map.node_to_string(self.id))
817     }
818 }
819
820 impl<'tcx> Repr<'tcx> for ast::Lifetime {
821     fn repr(&self, _tcx: &ctxt) -> String {
822         format!("lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
823     }
824 }
825
826 impl<'tcx> Repr<'tcx> for ast::Stmt {
827     fn repr(&self, _tcx: &ctxt) -> String {
828         format!("stmt({}: {})",
829                 ast_util::stmt_id(self),
830                 pprust::stmt_to_string(self))
831     }
832 }
833
834 impl<'tcx> Repr<'tcx> for ast::Pat {
835     fn repr(&self, _tcx: &ctxt) -> String {
836         format!("pat({}: {})", self.id, pprust::pat_to_string(self))
837     }
838 }
839
840 impl<'tcx> Repr<'tcx> for ty::BoundRegion {
841     fn repr(&self, tcx: &ctxt) -> String {
842         match *self {
843             ty::BrAnon(id) => format!("BrAnon({})", id),
844             ty::BrNamed(id, name) => {
845                 format!("BrNamed({}, {})", id.repr(tcx), token::get_name(name))
846             }
847             ty::BrFresh(id) => format!("BrFresh({})", id),
848             ty::BrEnv => "BrEnv".to_string()
849         }
850     }
851 }
852
853 impl<'tcx> Repr<'tcx> for ty::Region {
854     fn repr(&self, tcx: &ctxt) -> String {
855         match *self {
856             ty::ReEarlyBound(id, space, index, name) => {
857                 format!("ReEarlyBound({}, {:?}, {}, {})",
858                                id,
859                                space,
860                                index,
861                                token::get_name(name))
862             }
863
864             ty::ReLateBound(binder_id, ref bound_region) => {
865                 format!("ReLateBound({:?}, {})",
866                         binder_id,
867                         bound_region.repr(tcx))
868             }
869
870             ty::ReFree(ref fr) => fr.repr(tcx),
871
872             ty::ReScope(id) => {
873                 format!("ReScope({:?})", id)
874             }
875
876             ty::ReStatic => {
877                 "ReStatic".to_string()
878             }
879
880             ty::ReInfer(ReVar(ref vid)) => {
881                 format!("{:?}", vid)
882             }
883
884             ty::ReInfer(ReSkolemized(id, ref bound_region)) => {
885                 format!("re_skolemized({}, {})", id, bound_region.repr(tcx))
886             }
887
888             ty::ReEmpty => {
889                 "ReEmpty".to_string()
890             }
891         }
892     }
893 }
894
895 impl<'tcx> UserString<'tcx> for ty::Region {
896     fn user_string(&self, tcx: &ctxt) -> String {
897         region_to_string(tcx, "", false, *self)
898     }
899 }
900
901 impl<'tcx> Repr<'tcx> for ty::FreeRegion {
902     fn repr(&self, tcx: &ctxt) -> String {
903         format!("ReFree({}, {})",
904                 self.scope.node_id(),
905                 self.bound_region.repr(tcx))
906     }
907 }
908
909 impl<'tcx> Repr<'tcx> for ast::DefId {
910     fn repr(&self, tcx: &ctxt) -> String {
911         // Unfortunately, there seems to be no way to attempt to print
912         // a path for a def-id, so I'll just make a best effort for now
913         // and otherwise fallback to just printing the crate/node pair
914         if self.krate == ast::LOCAL_CRATE {
915             match tcx.map.find(self.node) {
916                 Some(ast_map::NodeItem(..)) |
917                 Some(ast_map::NodeForeignItem(..)) |
918                 Some(ast_map::NodeImplItem(..)) |
919                 Some(ast_map::NodeTraitItem(..)) |
920                 Some(ast_map::NodeVariant(..)) |
921                 Some(ast_map::NodeStructCtor(..)) => {
922                     return format!(
923                                 "{:?}:{}",
924                                 *self,
925                                 ty::item_path_str(tcx, *self))
926                 }
927                 _ => {}
928             }
929         }
930         return format!("{:?}", *self)
931     }
932 }
933
934 impl<'tcx> Repr<'tcx> for ty::TypeScheme<'tcx> {
935     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
936         format!("TypeScheme {{generics: {}, ty: {}}}",
937                 self.generics.repr(tcx),
938                 self.ty.repr(tcx))
939     }
940 }
941
942 impl<'tcx> Repr<'tcx> for ty::Generics<'tcx> {
943     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
944         format!("Generics(types: {}, regions: {}, predicates: {})",
945                 self.types.repr(tcx),
946                 self.regions.repr(tcx),
947                 self.predicates.repr(tcx))
948     }
949 }
950
951 impl<'tcx> Repr<'tcx> for ty::GenericBounds<'tcx> {
952     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
953         format!("GenericBounds({})",
954                 self.predicates.repr(tcx))
955     }
956 }
957
958 impl<'tcx> Repr<'tcx> for ty::ItemVariances {
959     fn repr(&self, tcx: &ctxt) -> String {
960         format!("ItemVariances(types={}, \
961                 regions={})",
962                 self.types.repr(tcx),
963                 self.regions.repr(tcx))
964     }
965 }
966
967 impl<'tcx> Repr<'tcx> for ty::Variance {
968     fn repr(&self, _: &ctxt) -> String {
969         // The first `.to_string()` returns a &'static str (it is not an implementation
970         // of the ToString trait). Because of that, we need to call `.to_string()` again
971         // if we want to have a `String`.
972         let result: &'static str = (*self).to_string();
973         result.to_string()
974     }
975 }
976
977 impl<'tcx> Repr<'tcx> for ty::Method<'tcx> {
978     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
979         format!("method(name: {}, generics: {}, fty: {}, \
980                  explicit_self: {}, vis: {}, def_id: {})",
981                 self.name.repr(tcx),
982                 self.generics.repr(tcx),
983                 self.fty.repr(tcx),
984                 self.explicit_self.repr(tcx),
985                 self.vis.repr(tcx),
986                 self.def_id.repr(tcx))
987     }
988 }
989
990 impl<'tcx> Repr<'tcx> for ast::Name {
991     fn repr(&self, _tcx: &ctxt) -> String {
992         token::get_name(*self).get().to_string()
993     }
994 }
995
996 impl<'tcx> UserString<'tcx> for ast::Name {
997     fn user_string(&self, _tcx: &ctxt) -> String {
998         token::get_name(*self).get().to_string()
999     }
1000 }
1001
1002 impl<'tcx> Repr<'tcx> for ast::Ident {
1003     fn repr(&self, _tcx: &ctxt) -> String {
1004         token::get_ident(*self).get().to_string()
1005     }
1006 }
1007
1008 impl<'tcx> Repr<'tcx> for ast::ExplicitSelf_ {
1009     fn repr(&self, _tcx: &ctxt) -> String {
1010         format!("{:?}", *self)
1011     }
1012 }
1013
1014 impl<'tcx> Repr<'tcx> for ast::Visibility {
1015     fn repr(&self, _tcx: &ctxt) -> String {
1016         format!("{:?}", *self)
1017     }
1018 }
1019
1020 impl<'tcx> Repr<'tcx> for ty::BareFnTy<'tcx> {
1021     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1022         format!("BareFnTy {{unsafety: {}, abi: {}, sig: {}}}",
1023                 self.unsafety,
1024                 self.abi.to_string(),
1025                 self.sig.repr(tcx))
1026     }
1027 }
1028
1029
1030 impl<'tcx> Repr<'tcx> for ty::FnSig<'tcx> {
1031     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1032         format!("fn{} -> {}", self.inputs.repr(tcx), self.output.repr(tcx))
1033     }
1034 }
1035
1036 impl<'tcx> Repr<'tcx> for ty::FnOutput<'tcx> {
1037     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1038         match *self {
1039             ty::FnConverging(ty) =>
1040                 format!("FnConverging({0})", ty.repr(tcx)),
1041             ty::FnDiverging =>
1042                 "FnDiverging".to_string()
1043         }
1044     }
1045 }
1046
1047 impl<'tcx> Repr<'tcx> for ty::MethodCallee<'tcx> {
1048     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1049         format!("MethodCallee {{origin: {}, ty: {}, {}}}",
1050                 self.origin.repr(tcx),
1051                 self.ty.repr(tcx),
1052                 self.substs.repr(tcx))
1053     }
1054 }
1055
1056 impl<'tcx> Repr<'tcx> for ty::MethodOrigin<'tcx> {
1057     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1058         match self {
1059             &ty::MethodStatic(def_id) => {
1060                 format!("MethodStatic({})", def_id.repr(tcx))
1061             }
1062             &ty::MethodStaticUnboxedClosure(def_id) => {
1063                 format!("MethodStaticUnboxedClosure({})", def_id.repr(tcx))
1064             }
1065             &ty::MethodTypeParam(ref p) => {
1066                 p.repr(tcx)
1067             }
1068             &ty::MethodTraitObject(ref p) => {
1069                 p.repr(tcx)
1070             }
1071         }
1072     }
1073 }
1074
1075 impl<'tcx> Repr<'tcx> for ty::MethodParam<'tcx> {
1076     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1077         format!("MethodParam({},{})",
1078                 self.trait_ref.repr(tcx),
1079                 self.method_num)
1080     }
1081 }
1082
1083 impl<'tcx> Repr<'tcx> for ty::MethodObject<'tcx> {
1084     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1085         format!("MethodObject({},{},{})",
1086                 self.trait_ref.repr(tcx),
1087                 self.method_num,
1088                 self.real_index)
1089     }
1090 }
1091
1092 impl<'tcx> Repr<'tcx> for ty::TraitStore {
1093     fn repr(&self, tcx: &ctxt) -> String {
1094         trait_store_to_string(tcx, *self)
1095     }
1096 }
1097
1098 impl<'tcx> Repr<'tcx> for ty::BuiltinBound {
1099     fn repr(&self, _tcx: &ctxt) -> String {
1100         format!("{:?}", *self)
1101     }
1102 }
1103
1104 impl<'tcx> UserString<'tcx> for ty::BuiltinBound {
1105     fn user_string(&self, _tcx: &ctxt) -> String {
1106         match *self {
1107             ty::BoundSend => "Send".to_string(),
1108             ty::BoundSized => "Sized".to_string(),
1109             ty::BoundCopy => "Copy".to_string(),
1110             ty::BoundSync => "Sync".to_string(),
1111         }
1112     }
1113 }
1114
1115 impl<'tcx> Repr<'tcx> for Span {
1116     fn repr(&self, tcx: &ctxt) -> String {
1117         tcx.sess.codemap().span_to_string(*self).to_string()
1118     }
1119 }
1120
1121 impl<'tcx, A:UserString<'tcx>> UserString<'tcx> for Rc<A> {
1122     fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1123         let this: &A = &**self;
1124         this.user_string(tcx)
1125     }
1126 }
1127
1128 impl<'tcx> UserString<'tcx> for ty::ParamBounds<'tcx> {
1129     fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1130         let mut result = Vec::new();
1131         let s = self.builtin_bounds.user_string(tcx);
1132         if !s.is_empty() {
1133             result.push(s);
1134         }
1135         for n in self.trait_bounds.iter() {
1136             result.push(n.user_string(tcx));
1137         }
1138         result.connect(" + ")
1139     }
1140 }
1141
1142 impl<'tcx> UserString<'tcx> for ty::ExistentialBounds<'tcx> {
1143     fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1144         if self.builtin_bounds.contains(&ty::BoundSend) &&
1145             self.region_bound == ty::ReStatic
1146         { // Region bound is implied by builtin bounds:
1147             return self.builtin_bounds.repr(tcx);
1148         }
1149
1150         let mut res = Vec::new();
1151
1152         let region_str = self.region_bound.user_string(tcx);
1153         if !region_str.is_empty() {
1154             res.push(region_str);
1155         }
1156
1157         for bound in self.builtin_bounds.iter() {
1158             res.push(bound.user_string(tcx));
1159         }
1160
1161         res.connect("+")
1162     }
1163 }
1164
1165 impl<'tcx> UserString<'tcx> for ty::BuiltinBounds {
1166     fn user_string(&self, tcx: &ctxt) -> String {
1167         self.iter()
1168             .map(|bb| bb.user_string(tcx))
1169             .collect::<Vec<String>>()
1170             .connect("+")
1171             .to_string()
1172     }
1173 }
1174
1175 impl<'tcx, T> UserString<'tcx> for ty::Binder<T>
1176     where T : UserString<'tcx> + TypeFoldable<'tcx>
1177 {
1178     fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1179         // Replace any anonymous late-bound regions with named
1180         // variants, using gensym'd identifiers, so that we can
1181         // clearly differentiate between named and unnamed regions in
1182         // the output. We'll probably want to tweak this over time to
1183         // decide just how much information to give.
1184         let mut names = Vec::new();
1185         let (unbound_value, _) = ty::replace_late_bound_regions(tcx, self, |br, debruijn| {
1186             ty::ReLateBound(debruijn, match br {
1187                 ty::BrNamed(_, name) => {
1188                     names.push(token::get_name(name));
1189                     br
1190                 }
1191                 ty::BrAnon(_) |
1192                 ty::BrFresh(_) |
1193                 ty::BrEnv => {
1194                     let name = token::gensym("'r");
1195                     names.push(token::get_name(name));
1196                     ty::BrNamed(ast_util::local_def(ast::DUMMY_NODE_ID), name)
1197                 }
1198             })
1199         });
1200         let names: Vec<_> = names.iter().map(|s| s.get()).collect();
1201
1202         let value_str = unbound_value.user_string(tcx);
1203         if names.len() == 0 {
1204             value_str
1205         } else {
1206             format!("for<{}> {}", names.connect(","), value_str)
1207         }
1208     }
1209 }
1210
1211 impl<'tcx> UserString<'tcx> for ty::TraitRef<'tcx> {
1212     fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1213         let path_str = ty::item_path_str(tcx, self.def_id);
1214         let trait_def = ty::lookup_trait_def(tcx, self.def_id);
1215         parameterized(tcx, path_str.as_slice(), self.substs,
1216                       &trait_def.generics, self.def_id)
1217     }
1218 }
1219
1220 impl<'tcx> UserString<'tcx> for Ty<'tcx> {
1221     fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1222         ty_to_string(tcx, *self)
1223     }
1224 }
1225
1226 impl<'tcx> UserString<'tcx> for ast::Ident {
1227     fn user_string(&self, _tcx: &ctxt) -> String {
1228         token::get_name(self.name).get().to_string()
1229     }
1230 }
1231
1232 impl<'tcx> Repr<'tcx> for abi::Abi {
1233     fn repr(&self, _tcx: &ctxt) -> String {
1234         self.to_string()
1235     }
1236 }
1237
1238 impl<'tcx> UserString<'tcx> for abi::Abi {
1239     fn user_string(&self, _tcx: &ctxt) -> String {
1240         self.to_string()
1241     }
1242 }
1243
1244 impl<'tcx> Repr<'tcx> for ty::UpvarId {
1245     fn repr(&self, tcx: &ctxt) -> String {
1246         format!("UpvarId({};`{}`;{})",
1247                 self.var_id,
1248                 ty::local_var_name_str(tcx, self.var_id),
1249                 self.closure_expr_id)
1250     }
1251 }
1252
1253 impl<'tcx> Repr<'tcx> for ast::Mutability {
1254     fn repr(&self, _tcx: &ctxt) -> String {
1255         format!("{:?}", *self)
1256     }
1257 }
1258
1259 impl<'tcx> Repr<'tcx> for ty::BorrowKind {
1260     fn repr(&self, _tcx: &ctxt) -> String {
1261         format!("{:?}", *self)
1262     }
1263 }
1264
1265 impl<'tcx> Repr<'tcx> for ty::UpvarBorrow {
1266     fn repr(&self, tcx: &ctxt) -> String {
1267         format!("UpvarBorrow({}, {})",
1268                 self.kind.repr(tcx),
1269                 self.region.repr(tcx))
1270     }
1271 }
1272
1273 impl<'tcx> Repr<'tcx> for ty::IntVid {
1274     fn repr(&self, _tcx: &ctxt) -> String {
1275         format!("{:?}", self)
1276     }
1277 }
1278
1279 impl<'tcx> Repr<'tcx> for ty::FloatVid {
1280     fn repr(&self, _tcx: &ctxt) -> String {
1281         format!("{:?}", self)
1282     }
1283 }
1284
1285 impl<'tcx> Repr<'tcx> for ty::RegionVid {
1286     fn repr(&self, _tcx: &ctxt) -> String {
1287         format!("{:?}", self)
1288     }
1289 }
1290
1291 impl<'tcx> Repr<'tcx> for ty::TyVid {
1292     fn repr(&self, _tcx: &ctxt) -> String {
1293         format!("{:?}", self)
1294     }
1295 }
1296
1297 impl<'tcx> Repr<'tcx> for ty::IntVarValue {
1298     fn repr(&self, _tcx: &ctxt) -> String {
1299         format!("{:?}", *self)
1300     }
1301 }
1302
1303 impl<'tcx> Repr<'tcx> for ast::IntTy {
1304     fn repr(&self, _tcx: &ctxt) -> String {
1305         format!("{:?}", *self)
1306     }
1307 }
1308
1309 impl<'tcx> Repr<'tcx> for ast::UintTy {
1310     fn repr(&self, _tcx: &ctxt) -> String {
1311         format!("{:?}", *self)
1312     }
1313 }
1314
1315 impl<'tcx> Repr<'tcx> for ast::FloatTy {
1316     fn repr(&self, _tcx: &ctxt) -> String {
1317         format!("{:?}", *self)
1318     }
1319 }
1320
1321 impl<'tcx> Repr<'tcx> for ty::ExplicitSelfCategory {
1322     fn repr(&self, _: &ctxt) -> String {
1323         explicit_self_category_to_str(self).to_string()
1324     }
1325 }
1326
1327 impl<'tcx> UserString<'tcx> for ParamTy {
1328     fn user_string(&self, _tcx: &ctxt) -> String {
1329         format!("{}", token::get_name(self.name))
1330     }
1331 }
1332
1333 impl<'tcx> Repr<'tcx> for ParamTy {
1334     fn repr(&self, tcx: &ctxt) -> String {
1335         let ident = self.user_string(tcx);
1336         format!("{}/{:?}.{}", ident, self.space, self.idx)
1337     }
1338 }
1339
1340 impl<'tcx, A:Repr<'tcx>, B:Repr<'tcx>> Repr<'tcx> for (A,B) {
1341     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1342         let &(ref a, ref b) = self;
1343         format!("({},{})", a.repr(tcx), b.repr(tcx))
1344     }
1345 }
1346
1347 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for ty::Binder<T> {
1348     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1349         format!("Binder({})", self.0.repr(tcx))
1350     }
1351 }
1352
1353 #[old_impl_check]
1354 impl<'tcx, S, H, K, V> Repr<'tcx> for HashMap<K,V,H>
1355     where K : Hash<S> + Eq + Repr<'tcx>,
1356           V : Repr<'tcx>,
1357           H : Hasher<S>
1358 {
1359     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1360         format!("HashMap({})",
1361                 self.iter()
1362                     .map(|(k,v)| format!("{} => {}", k.repr(tcx), v.repr(tcx)))
1363                     .collect::<Vec<String>>()
1364                     .connect(", "))
1365     }
1366 }
1367
1368 impl<'tcx, T, U> Repr<'tcx> for ty::OutlivesPredicate<T,U>
1369     where T : Repr<'tcx> + TypeFoldable<'tcx>,
1370           U : Repr<'tcx> + TypeFoldable<'tcx>,
1371 {
1372     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1373         format!("OutlivesPredicate({}, {})",
1374                 self.0.repr(tcx),
1375                 self.1.repr(tcx))
1376     }
1377 }
1378
1379 impl<'tcx, T, U> UserString<'tcx> for ty::OutlivesPredicate<T,U>
1380     where T : UserString<'tcx> + TypeFoldable<'tcx>,
1381           U : UserString<'tcx> + TypeFoldable<'tcx>,
1382 {
1383     fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1384         format!("{} : {}",
1385                 self.0.user_string(tcx),
1386                 self.1.user_string(tcx))
1387     }
1388 }
1389
1390 impl<'tcx> Repr<'tcx> for ty::EquatePredicate<'tcx> {
1391     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1392         format!("EquatePredicate({}, {})",
1393                 self.0.repr(tcx),
1394                 self.1.repr(tcx))
1395     }
1396 }
1397
1398 impl<'tcx> UserString<'tcx> for ty::EquatePredicate<'tcx> {
1399     fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1400         format!("{} == {}",
1401                 self.0.user_string(tcx),
1402                 self.1.user_string(tcx))
1403     }
1404 }
1405
1406 impl<'tcx> Repr<'tcx> for ty::TraitPredicate<'tcx> {
1407     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1408         format!("TraitPredicate({})",
1409                 self.trait_ref.repr(tcx))
1410     }
1411 }
1412
1413 impl<'tcx> UserString<'tcx> for ty::TraitPredicate<'tcx> {
1414     fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1415         format!("{} : {}",
1416                 self.trait_ref.self_ty().user_string(tcx),
1417                 self.trait_ref.user_string(tcx))
1418     }
1419 }
1420
1421 impl<'tcx> UserString<'tcx> for ty::ProjectionPredicate<'tcx> {
1422     fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1423         format!("{} == {}",
1424                 self.projection_ty.user_string(tcx),
1425                 self.ty.user_string(tcx))
1426     }
1427 }
1428
1429 impl<'tcx> Repr<'tcx> for ty::ProjectionTy<'tcx> {
1430     fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1431         format!("<{} as {}>::{}",
1432                 self.trait_ref.self_ty().repr(tcx),
1433                 self.trait_ref.repr(tcx),
1434                 self.item_name.repr(tcx))
1435     }
1436 }
1437
1438 impl<'tcx> UserString<'tcx> for ty::ProjectionTy<'tcx> {
1439     fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1440         format!("<{} as {}>::{}",
1441                 self.trait_ref.self_ty().user_string(tcx),
1442                 self.trait_ref.user_string(tcx),
1443                 self.item_name.user_string(tcx))
1444     }
1445 }
1446
1447 impl<'tcx> UserString<'tcx> for ty::Predicate<'tcx> {
1448     fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1449         match *self {
1450             ty::Predicate::Trait(ref data) => data.user_string(tcx),
1451             ty::Predicate::Equate(ref predicate) => predicate.user_string(tcx),
1452             ty::Predicate::RegionOutlives(ref predicate) => predicate.user_string(tcx),
1453             ty::Predicate::TypeOutlives(ref predicate) => predicate.user_string(tcx),
1454             ty::Predicate::Projection(ref predicate) => predicate.user_string(tcx),
1455         }
1456     }
1457 }