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