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