]> git.lizzy.rs Git - rust.git/blob - src/librustc/util/ppaux.rs
80f3508d0cd354bd678b7fc3a8592803eba3e294
[rust.git] / src / librustc / util / ppaux.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11
12 use middle::def;
13 use middle::subst;
14 use middle::subst::{VecPerParamSpace,Subst};
15 use middle::ty::{ReSkolemized, ReVar};
16 use middle::ty::{BoundRegion, BrAnon, BrNamed};
17 use middle::ty::{BrFresh, ctxt};
18 use middle::ty::{mt, t, ParamTy};
19 use middle::ty::{ReFree, ReScope, ReInfer, ReStatic, Region,
20                  ReEmpty};
21 use middle::ty::{ty_bool, ty_char, ty_bot, ty_box, ty_struct, ty_enum};
22 use middle::ty::{ty_err, ty_str, ty_vec, ty_float, ty_bare_fn, ty_closure};
23 use middle::ty::{ty_nil, ty_param, ty_ptr, ty_rptr, ty_tup};
24 use middle::ty::{ty_uniq, ty_trait, ty_int, ty_uint, ty_infer};
25 use middle::ty;
26 use middle::typeck;
27
28 use std::rc::Rc;
29 use std::gc::Gc;
30 use syntax::abi;
31 use syntax::ast_map;
32 use syntax::codemap::{Span, Pos};
33 use syntax::parse::token;
34 use syntax::print::pprust;
35 use syntax::{ast, ast_util};
36 use syntax::owned_slice::OwnedSlice;
37
38 /// Produces a string suitable for debugging output.
39 pub trait Repr {
40     fn repr(&self, tcx: &ctxt) -> String;
41 }
42
43 /// Produces a string suitable for showing to the user.
44 pub trait UserString {
45     fn user_string(&self, tcx: &ctxt) -> String;
46 }
47
48 pub fn note_and_explain_region(cx: &ctxt,
49                                prefix: &str,
50                                region: ty::Region,
51                                suffix: &str) {
52     match explain_region_and_span(cx, region) {
53       (ref str, Some(span)) => {
54         cx.sess.span_note(
55             span,
56             format!("{}{}{}", prefix, *str, suffix).as_slice());
57       }
58       (ref str, None) => {
59         cx.sess.note(
60             format!("{}{}{}", prefix, *str, suffix).as_slice());
61       }
62     }
63 }
64
65 pub fn explain_region_and_span(cx: &ctxt, region: ty::Region)
66                             -> (String, Option<Span>) {
67     return match region {
68       ReScope(node_id) => {
69         match cx.map.find(node_id) {
70           Some(ast_map::NodeBlock(ref blk)) => {
71             explain_span(cx, "block", blk.span)
72           }
73           Some(ast_map::NodeExpr(expr)) => {
74             match expr.node {
75               ast::ExprCall(..) => explain_span(cx, "call", expr.span),
76               ast::ExprMethodCall(..) => {
77                 explain_span(cx, "method call", expr.span)
78               },
79               ast::ExprMatch(..) => explain_span(cx, "match", expr.span),
80               _ => explain_span(cx, "expression", expr.span)
81             }
82           }
83           Some(ast_map::NodeStmt(stmt)) => {
84               explain_span(cx, "statement", stmt.span)
85           }
86           Some(ast_map::NodeItem(it)) if (match it.node {
87                 ast::ItemFn(..) => true, _ => false}) => {
88               explain_span(cx, "function body", it.span)
89           }
90           Some(_) | None => {
91             // this really should not happen
92             (format!("unknown scope: {}.  Please report a bug.", node_id), None)
93           }
94         }
95       }
96
97       ReFree(ref fr) => {
98         let prefix = match fr.bound_region {
99           #[cfg(stage0)]
100           BrAnon(idx) => {
101               format!("the anonymous lifetime \\#{} defined on", idx + 1)
102           }
103           #[cfg(not(stage0))]
104           BrAnon(idx) => {
105               format!("the anonymous lifetime #{} defined on", idx + 1)
106           }
107           BrFresh(_) => "an anonymous lifetime defined on".to_string(),
108           _ => {
109               format!("the lifetime {} as defined on",
110                       bound_region_ptr_to_str(cx, fr.bound_region))
111           }
112         };
113
114         match cx.map.find(fr.scope_id) {
115           Some(ast_map::NodeBlock(ref blk)) => {
116             let (msg, opt_span) = explain_span(cx, "block", blk.span);
117             (format!("{} {}", prefix, msg), opt_span)
118           }
119           Some(ast_map::NodeItem(it)) if match it.node {
120                 ast::ItemImpl(..) => true, _ => false} => {
121             let (msg, opt_span) = explain_span(cx, "impl", it.span);
122             (format!("{} {}", prefix, msg), opt_span)
123           }
124           Some(_) | None => {
125             // this really should not happen
126             (format!("{} node {}", prefix, fr.scope_id), None)
127           }
128         }
129       }
130
131       ReStatic => { ("the static lifetime".to_string(), None) }
132
133       ReEmpty => { ("the empty lifetime".to_string(), None) }
134
135       // I believe these cases should not occur (except when debugging,
136       // perhaps)
137       ty::ReInfer(_) | ty::ReEarlyBound(..) | ty::ReLateBound(..) => {
138         (format!("lifetime {:?}", region), None)
139       }
140     };
141
142     fn explain_span(cx: &ctxt, heading: &str, span: Span)
143         -> (String, Option<Span>) {
144         let lo = cx.sess.codemap().lookup_char_pos_adj(span.lo);
145         (format!("the {} at {}:{}", heading, lo.line, lo.col.to_uint()),
146          Some(span))
147     }
148 }
149
150 pub fn bound_region_ptr_to_str(cx: &ctxt, br: BoundRegion) -> String {
151     bound_region_to_str(cx, "", false, br)
152 }
153
154 pub fn bound_region_to_str(cx: &ctxt,
155                            prefix: &str, space: bool,
156                            br: BoundRegion) -> String {
157     let space_str = if space { " " } else { "" };
158
159     if cx.sess.verbose() {
160         return format!("{}{}{}", prefix, br.repr(cx), space_str)
161     }
162
163     match br {
164         BrNamed(_, name) => {
165             format!("{}{}{}", prefix, token::get_name(name), space_str)
166         }
167         BrAnon(_) => prefix.to_string(),
168         BrFresh(_) => prefix.to_string(),
169     }
170 }
171
172 // In general, if you are giving a region error message,
173 // you should use `explain_region()` or, better yet,
174 // `note_and_explain_region()`
175 pub fn region_ptr_to_str(cx: &ctxt, region: Region) -> String {
176     region_to_str(cx, "&", true, region)
177 }
178
179 pub fn region_to_str(cx: &ctxt, prefix: &str, space: bool, region: Region) -> String {
180     let space_str = if space { " " } else { "" };
181
182     if cx.sess.verbose() {
183         return format!("{}{}{}", prefix, region.repr(cx), space_str)
184     }
185
186     // These printouts are concise.  They do not contain all the information
187     // the user might want to diagnose an error, but there is basically no way
188     // to fit that into a short string.  Hence the recommendation to use
189     // `explain_region()` or `note_and_explain_region()`.
190     match region {
191         ty::ReScope(_) => prefix.to_string(),
192         ty::ReEarlyBound(_, _, _, name) => {
193             token::get_name(name).get().to_string()
194         }
195         ty::ReLateBound(_, br) => bound_region_to_str(cx, prefix, space, br),
196         ty::ReFree(ref fr) => bound_region_to_str(cx, prefix, space, fr.bound_region),
197         ty::ReInfer(ReSkolemized(_, br)) => {
198             bound_region_to_str(cx, prefix, space, br)
199         }
200         ty::ReInfer(ReVar(_)) => prefix.to_string(),
201         ty::ReStatic => format!("{}'static{}", prefix, space_str),
202         ty::ReEmpty => format!("{}'<empty>{}", prefix, space_str),
203     }
204 }
205
206 pub fn mutability_to_str(m: ast::Mutability) -> String {
207     match m {
208         ast::MutMutable => "mut ".to_string(),
209         ast::MutImmutable => "".to_string(),
210     }
211 }
212
213 pub fn mt_to_str(cx: &ctxt, m: &mt) -> String {
214     format!("{}{}", mutability_to_str(m.mutbl), ty_to_str(cx, m.ty))
215 }
216
217 pub fn trait_store_to_str(cx: &ctxt, s: ty::TraitStore) -> String {
218     match s {
219         ty::UniqTraitStore => "Box ".to_string(),
220         ty::RegionTraitStore(r, m) => {
221             format!("{}{}", region_ptr_to_str(cx, r), mutability_to_str(m))
222         }
223     }
224 }
225
226 pub fn vec_map_to_str<T>(ts: &[T], f: |t: &T| -> String) -> String {
227     let tstrs = ts.iter().map(f).collect::<Vec<String>>();
228     format!("[{}]", tstrs.connect(", "))
229 }
230
231 pub fn fn_sig_to_str(cx: &ctxt, typ: &ty::FnSig) -> String {
232     format!("fn{}{} -> {}", typ.binder_id, typ.inputs.repr(cx),
233             typ.output.repr(cx))
234 }
235
236 pub fn trait_ref_to_str(cx: &ctxt, trait_ref: &ty::TraitRef) -> String {
237     trait_ref.user_string(cx).to_string()
238 }
239
240 pub fn ty_to_str(cx: &ctxt, typ: t) -> String {
241     fn fn_input_to_str(cx: &ctxt, input: ty::t) -> String {
242         ty_to_str(cx, input).to_string()
243     }
244     fn bare_fn_to_str(cx: &ctxt,
245                       fn_style: ast::FnStyle,
246                       abi: abi::Abi,
247                       ident: Option<ast::Ident>,
248                       sig: &ty::FnSig)
249                       -> String {
250         let mut s = String::new();
251         match fn_style {
252             ast::NormalFn => {}
253             _ => {
254                 s.push_str(fn_style.to_str().as_slice());
255                 s.push_char(' ');
256             }
257         };
258
259         if abi != abi::Rust {
260             s.push_str(format!("extern {} ", abi.to_str()).as_slice());
261         };
262
263         s.push_str("fn");
264
265         match ident {
266             Some(i) => {
267                 s.push_char(' ');
268                 s.push_str(token::get_ident(i).get());
269             }
270             _ => { }
271         }
272
273         push_sig_to_str(cx, &mut s, '(', ')', sig);
274
275         s
276     }
277
278     fn closure_to_str(cx: &ctxt, cty: &ty::ClosureTy) -> String {
279         let mut s = String::new();
280
281         match cty.store {
282             ty::UniqTraitStore => {}
283             ty::RegionTraitStore(region, _) => {
284                 s.push_str(region_to_str(cx, "", true, region).as_slice());
285             }
286         }
287
288         match cty.fn_style {
289             ast::NormalFn => {}
290             _ => {
291                 s.push_str(cty.fn_style.to_str().as_slice());
292                 s.push_char(' ');
293             }
294         };
295
296         match cty.store {
297             ty::UniqTraitStore => {
298                 assert_eq!(cty.onceness, ast::Once);
299                 s.push_str("proc");
300                 push_sig_to_str(cx, &mut s, '(', ')', &cty.sig);
301             }
302             ty::RegionTraitStore(..) => {
303                 match cty.onceness {
304                     ast::Many => {}
305                     ast::Once => s.push_str("once ")
306                 }
307                 push_sig_to_str(cx, &mut s, '|', '|', &cty.sig);
308             }
309         }
310
311         if !cty.bounds.is_empty() {
312             s.push_str(":");
313             s.push_str(cty.bounds.repr(cx).as_slice());
314         }
315
316         s
317     }
318
319     fn push_sig_to_str(cx: &ctxt,
320                        s: &mut String,
321                        bra: char,
322                        ket: char,
323                        sig: &ty::FnSig) {
324         s.push_char(bra);
325         let strs: Vec<String> = sig.inputs.iter().map(|a| fn_input_to_str(cx, *a)).collect();
326         s.push_str(strs.connect(", ").as_slice());
327         if sig.variadic {
328             s.push_str(", ...");
329         }
330         s.push_char(ket);
331
332         if ty::get(sig.output).sty != ty_nil {
333             s.push_str(" -> ");
334             if ty::type_is_bot(sig.output) {
335                 s.push_char('!');
336             } else {
337                 s.push_str(ty_to_str(cx, sig.output).as_slice());
338             }
339         }
340     }
341
342     // if there is an id, print that instead of the structural type:
343     /*for def_id in ty::type_def_id(typ).iter() {
344         // note that this typedef cannot have type parameters
345         return ty::item_path_str(cx, *def_id);
346     }*/
347
348     // pretty print the structural type representation:
349     return match ty::get(typ).sty {
350       ty_nil => "()".to_string(),
351       ty_bot => "!".to_string(),
352       ty_bool => "bool".to_string(),
353       ty_char => "char".to_string(),
354       ty_int(t) => ast_util::int_ty_to_str(t, None,
355                                            ast_util::AutoSuffix).to_string(),
356       ty_uint(t) => ast_util::uint_ty_to_str(t, None,
357                                              ast_util::AutoSuffix).to_string(),
358       ty_float(t) => ast_util::float_ty_to_str(t).to_string(),
359       ty_box(typ) => format!("@{}", ty_to_str(cx, typ)),
360       ty_uniq(typ) => format!("~{}", ty_to_str(cx, typ)),
361       ty_ptr(ref tm) => format!("*{}", mt_to_str(cx, tm)),
362       ty_rptr(r, ref tm) => {
363           let mut buf = region_ptr_to_str(cx, r);
364           buf.push_str(mt_to_str(cx, tm).as_slice());
365           buf
366       }
367       ty_tup(ref elems) => {
368         let strs: Vec<String> = elems.iter().map(|elem| ty_to_str(cx, *elem)).collect();
369         format!("({})", strs.connect(","))
370       }
371       ty_closure(ref f) => {
372           closure_to_str(cx, *f)
373       }
374       ty_bare_fn(ref f) => {
375           bare_fn_to_str(cx, f.fn_style, f.abi, None, &f.sig)
376       }
377       ty_infer(infer_ty) => infer_ty.to_str(),
378       ty_err => "[type error]".to_string(),
379       ty_param(ParamTy {idx: id, def_id: did, ..}) => {
380           let ident = match cx.ty_param_defs.borrow().find(&did.node) {
381               Some(def) => token::get_ident(def.ident).get().to_string(),
382               // This can only happen when a type mismatch error happens and
383               // the actual type has more type parameters than the expected one.
384               #[cfg(stage0)]
385               None => format!("<generic \\#{}>", id),
386               #[cfg(not(stage0))]
387               None => format!("<generic #{}>", id),
388           };
389           if !cx.sess.verbose() {
390               ident
391           } else {
392               format!("{}:{:?}", ident, did)
393           }
394       }
395       ty_enum(did, ref substs) | ty_struct(did, ref substs) => {
396           let base = ty::item_path_str(cx, did);
397           let generics = ty::lookup_item_type(cx, did).generics;
398           parameterized(cx, base.as_slice(), substs, &generics)
399       }
400       ty_trait(box ty::TyTrait {
401           def_id: did, ref substs, store, ref bounds
402       }) => {
403           let base = ty::item_path_str(cx, did);
404           let trait_def = ty::lookup_trait_def(cx, did);
405           let ty = parameterized(cx, base.as_slice(),
406                                  substs, &trait_def.generics);
407           let bound_sep = if bounds.is_empty() { "" } else { ":" };
408           let bound_str = bounds.repr(cx);
409           format!("{}{}{}{}",
410                   trait_store_to_str(cx, store),
411                   ty,
412                   bound_sep,
413                   bound_str)
414       }
415       ty_str => "str".to_string(),
416       ty_vec(ref mt, sz) => {
417           match sz {
418               Some(n) => {
419                   format!("[{}, .. {}]", mt_to_str(cx, mt), n)
420               }
421               None => format!("[{}]", ty_to_str(cx, mt.ty)),
422           }
423       }
424     }
425 }
426
427 pub fn parameterized(cx: &ctxt,
428                      base: &str,
429                      substs: &subst::Substs,
430                      generics: &ty::Generics)
431                      -> String
432 {
433     let mut strs = Vec::new();
434
435     match substs.regions {
436         subst::ErasedRegions => { }
437         subst::NonerasedRegions(ref regions) => {
438             for &r in regions.iter() {
439                 let s = region_to_str(cx, "", false, r);
440                 if !s.is_empty() {
441                     strs.push(s)
442                 } else {
443                     // This happens when the value of the region
444                     // parameter is not easily serialized. This may be
445                     // because the user omitted it in the first place,
446                     // or because it refers to some block in the code,
447                     // etc. I'm not sure how best to serialize this.
448                     strs.push(format!("'_"));
449                 }
450             }
451         }
452     }
453
454     let tps = substs.types.get_vec(subst::TypeSpace);
455     let ty_params = generics.types.get_vec(subst::TypeSpace);
456     let has_defaults = ty_params.last().map_or(false, |def| def.default.is_some());
457     let num_defaults = if has_defaults && !cx.sess.verbose() {
458         ty_params.iter().zip(tps.iter()).rev().take_while(|&(def, &actual)| {
459             match def.default {
460                 Some(default) => default.subst(cx, substs) == actual,
461                 None => false
462             }
463         }).count()
464     } else {
465         0
466     };
467
468     for t in tps.slice_to(tps.len() - num_defaults).iter() {
469         strs.push(ty_to_str(cx, *t))
470     }
471
472     if cx.sess.verbose() {
473         for t in substs.types.get_vec(subst::SelfSpace).iter() {
474             strs.push(format!("for {}", t.repr(cx)));
475         }
476     }
477
478     if strs.len() > 0u {
479         format!("{}<{}>", base, strs.connect(","))
480     } else {
481         format!("{}", base)
482     }
483 }
484
485 pub fn ty_to_short_str(cx: &ctxt, typ: t) -> String {
486     let mut s = typ.repr(cx).to_string();
487     if s.len() >= 32u {
488         s = s.as_slice().slice(0u, 32u).to_string();
489     }
490     return s;
491 }
492
493 impl<T:Repr> Repr for Option<T> {
494     fn repr(&self, tcx: &ctxt) -> String {
495         match self {
496             &None => "None".to_string(),
497             &Some(ref t) => t.repr(tcx),
498         }
499     }
500 }
501
502 impl<T:Repr,U:Repr> Repr for Result<T,U> {
503     fn repr(&self, tcx: &ctxt) -> String {
504         match self {
505             &Ok(ref t) => t.repr(tcx),
506             &Err(ref u) => format!("Err({})", u.repr(tcx))
507         }
508     }
509 }
510
511 impl Repr for () {
512     fn repr(&self, _tcx: &ctxt) -> String {
513         "()".to_string()
514     }
515 }
516
517 impl<T:Repr> Repr for Rc<T> {
518     fn repr(&self, tcx: &ctxt) -> String {
519         (&**self).repr(tcx)
520     }
521 }
522
523 impl<T:Repr + 'static> Repr for Gc<T> {
524     fn repr(&self, tcx: &ctxt) -> String {
525         (&**self).repr(tcx)
526     }
527 }
528
529 impl<T:Repr> Repr for Box<T> {
530     fn repr(&self, tcx: &ctxt) -> String {
531         (&**self).repr(tcx)
532     }
533 }
534
535 fn repr_vec<T:Repr>(tcx: &ctxt, v: &[T]) -> String {
536     vec_map_to_str(v, |t| t.repr(tcx))
537 }
538
539 impl<'a, T:Repr> Repr for &'a [T] {
540     fn repr(&self, tcx: &ctxt) -> String {
541         repr_vec(tcx, *self)
542     }
543 }
544
545 impl<T:Repr> Repr for OwnedSlice<T> {
546     fn repr(&self, tcx: &ctxt) -> String {
547         repr_vec(tcx, self.as_slice())
548     }
549 }
550
551 // This is necessary to handle types like Option<~[T]>, for which
552 // autoderef cannot convert the &[T] handler
553 impl<T:Repr> Repr for Vec<T> {
554     fn repr(&self, tcx: &ctxt) -> String {
555         repr_vec(tcx, self.as_slice())
556     }
557 }
558
559 impl Repr for def::Def {
560     fn repr(&self, _tcx: &ctxt) -> String {
561         format!("{:?}", *self)
562     }
563 }
564
565 impl Repr for ty::TypeParameterDef {
566     fn repr(&self, tcx: &ctxt) -> String {
567         format!("TypeParameterDef({:?}, {})", self.def_id,
568                 self.bounds.repr(tcx))
569     }
570 }
571
572 impl Repr for ty::RegionParameterDef {
573     fn repr(&self, _tcx: &ctxt) -> String {
574         format!("RegionParameterDef({}, {:?})",
575                 token::get_name(self.name),
576                 self.def_id)
577     }
578 }
579
580 impl Repr for ty::t {
581     fn repr(&self, tcx: &ctxt) -> String {
582         ty_to_str(tcx, *self)
583     }
584 }
585
586 impl Repr for subst::Substs {
587     fn repr(&self, tcx: &ctxt) -> String {
588         format!("Substs[types={}, regions={}]",
589                        self.types.repr(tcx),
590                        self.regions.repr(tcx))
591     }
592 }
593
594 impl<T:Repr> Repr for subst::VecPerParamSpace<T> {
595     fn repr(&self, tcx: &ctxt) -> String {
596         format!("[{};{};{}]",
597                        self.get_vec(subst::TypeSpace).repr(tcx),
598                        self.get_vec(subst::SelfSpace).repr(tcx),
599                        self.get_vec(subst::FnSpace).repr(tcx))
600     }
601 }
602
603 impl Repr for ty::ItemSubsts {
604     fn repr(&self, tcx: &ctxt) -> String {
605         format!("ItemSubsts({})", self.substs.repr(tcx))
606     }
607 }
608
609 impl Repr for subst::RegionSubsts {
610     fn repr(&self, tcx: &ctxt) -> String {
611         match *self {
612             subst::ErasedRegions => "erased".to_string(),
613             subst::NonerasedRegions(ref regions) => regions.repr(tcx)
614         }
615     }
616 }
617
618 impl Repr for ty::ParamBounds {
619     fn repr(&self, tcx: &ctxt) -> String {
620         let mut res = Vec::new();
621         for b in self.builtin_bounds.iter() {
622             res.push(match b {
623                 ty::BoundStatic => "'static".to_string(),
624                 ty::BoundSend => "Send".to_string(),
625                 ty::BoundSized => "Sized".to_string(),
626                 ty::BoundCopy => "Copy".to_string(),
627                 ty::BoundShare => "Share".to_string(),
628             });
629         }
630         for t in self.trait_bounds.iter() {
631             res.push(t.repr(tcx));
632         }
633         res.connect("+").to_string()
634     }
635 }
636
637 impl Repr for ty::TraitRef {
638     fn repr(&self, tcx: &ctxt) -> String {
639         trait_ref_to_str(tcx, self)
640     }
641 }
642
643 impl Repr for ast::Expr {
644     fn repr(&self, _tcx: &ctxt) -> String {
645         format!("expr({}: {})", self.id, pprust::expr_to_str(self))
646     }
647 }
648
649 impl Repr for ast::Path {
650     fn repr(&self, _tcx: &ctxt) -> String {
651         format!("path({})", pprust::path_to_str(self))
652     }
653 }
654
655 impl Repr for ast::Item {
656     fn repr(&self, tcx: &ctxt) -> String {
657         format!("item({})", tcx.map.node_to_str(self.id))
658     }
659 }
660
661 impl Repr for ast::Stmt {
662     fn repr(&self, _tcx: &ctxt) -> String {
663         format!("stmt({}: {})",
664                 ast_util::stmt_id(self),
665                 pprust::stmt_to_str(self))
666     }
667 }
668
669 impl Repr for ast::Pat {
670     fn repr(&self, _tcx: &ctxt) -> String {
671         format!("pat({}: {})", self.id, pprust::pat_to_str(self))
672     }
673 }
674
675 impl Repr for ty::BoundRegion {
676     fn repr(&self, tcx: &ctxt) -> String {
677         match *self {
678             ty::BrAnon(id) => format!("BrAnon({})", id),
679             ty::BrNamed(id, name) => {
680                 format!("BrNamed({}, {})", id.repr(tcx), token::get_name(name))
681             }
682             ty::BrFresh(id) => format!("BrFresh({})", id),
683         }
684     }
685 }
686
687 impl Repr for ty::Region {
688     fn repr(&self, tcx: &ctxt) -> String {
689         match *self {
690             ty::ReEarlyBound(id, space, index, name) => {
691                 format!("ReEarlyBound({}, {}, {}, {})",
692                                id,
693                                space,
694                                index,
695                                token::get_name(name))
696             }
697
698             ty::ReLateBound(binder_id, ref bound_region) => {
699                 format!("ReLateBound({}, {})",
700                         binder_id,
701                         bound_region.repr(tcx))
702             }
703
704             ty::ReFree(ref fr) => {
705                 format!("ReFree({}, {})",
706                         fr.scope_id,
707                         fr.bound_region.repr(tcx))
708             }
709
710             ty::ReScope(id) => {
711                 format!("ReScope({})", id)
712             }
713
714             ty::ReStatic => {
715                 "ReStatic".to_string()
716             }
717
718             ty::ReInfer(ReVar(ref vid)) => {
719                 format!("ReInfer({})", vid.id)
720             }
721
722             ty::ReInfer(ReSkolemized(id, ref bound_region)) => {
723                 format!("re_skolemized({}, {})", id, bound_region.repr(tcx))
724             }
725
726             ty::ReEmpty => {
727                 "ReEmpty".to_string()
728             }
729         }
730     }
731 }
732
733 impl Repr for ast::DefId {
734     fn repr(&self, tcx: &ctxt) -> String {
735         // Unfortunately, there seems to be no way to attempt to print
736         // a path for a def-id, so I'll just make a best effort for now
737         // and otherwise fallback to just printing the crate/node pair
738         if self.krate == ast::LOCAL_CRATE {
739             {
740                 match tcx.map.find(self.node) {
741                     Some(ast_map::NodeItem(..)) |
742                     Some(ast_map::NodeForeignItem(..)) |
743                     Some(ast_map::NodeMethod(..)) |
744                     Some(ast_map::NodeTraitMethod(..)) |
745                     Some(ast_map::NodeVariant(..)) |
746                     Some(ast_map::NodeStructCtor(..)) => {
747                         return format!(
748                                 "{:?}:{}",
749                                 *self,
750                                 ty::item_path_str(tcx, *self))
751                     }
752                     _ => {}
753                 }
754             }
755         }
756         return format!("{:?}", *self)
757     }
758 }
759
760 impl Repr for ty::ty_param_bounds_and_ty {
761     #[cfg(stage0)]
762     fn repr(&self, tcx: &ctxt) -> String {
763         format!("ty_param_bounds_and_ty \\{generics: {}, ty: {}\\}",
764                 self.generics.repr(tcx),
765                 self.ty.repr(tcx))
766     }
767     #[cfg(not(stage0))]
768     fn repr(&self, tcx: &ctxt) -> String {
769         format!("ty_param_bounds_and_ty {{generics: {}, ty: {}}}",
770                 self.generics.repr(tcx),
771                 self.ty.repr(tcx))
772     }
773 }
774
775 impl Repr for ty::Generics {
776     fn repr(&self, tcx: &ctxt) -> String {
777         format!("Generics(types: {}, regions: {})",
778                 self.types.repr(tcx),
779                 self.regions.repr(tcx))
780     }
781 }
782
783 impl Repr for ty::ItemVariances {
784     fn repr(&self, tcx: &ctxt) -> String {
785         format!("ItemVariances(types={}, \
786                 regions={})",
787                 self.types.repr(tcx),
788                 self.regions.repr(tcx))
789     }
790 }
791
792 impl Repr for ty::Variance {
793     fn repr(&self, _: &ctxt) -> String {
794         // The first `.to_str()` returns a &'static str (it is not an implementation
795         // of the ToStr trait). Because of that, we need to call `.to_str()` again
796         // if we want to have a `String`.
797         self.to_str().to_str()
798     }
799 }
800
801 impl Repr for ty::Method {
802     fn repr(&self, tcx: &ctxt) -> String {
803         format!("method(ident: {}, generics: {}, fty: {}, \
804                  explicit_self: {}, vis: {}, def_id: {})",
805                 self.ident.repr(tcx),
806                 self.generics.repr(tcx),
807                 self.fty.repr(tcx),
808                 self.explicit_self.repr(tcx),
809                 self.vis.repr(tcx),
810                 self.def_id.repr(tcx))
811     }
812 }
813
814 impl Repr for ast::Name {
815     fn repr(&self, _tcx: &ctxt) -> String {
816         token::get_name(*self).get().to_string()
817     }
818 }
819
820 impl Repr for ast::Ident {
821     fn repr(&self, _tcx: &ctxt) -> String {
822         token::get_ident(*self).get().to_string()
823     }
824 }
825
826 impl Repr for ast::ExplicitSelf_ {
827     fn repr(&self, _tcx: &ctxt) -> String {
828         format!("{:?}", *self)
829     }
830 }
831
832 impl Repr for ast::Visibility {
833     fn repr(&self, _tcx: &ctxt) -> String {
834         format!("{:?}", *self)
835     }
836 }
837
838 impl Repr for ty::BareFnTy {
839     #[cfg(stage0)]
840     fn repr(&self, tcx: &ctxt) -> String {
841         format!("BareFnTy \\{fn_style: {:?}, abi: {}, sig: {}\\}",
842                 self.fn_style,
843                 self.abi.to_str(),
844                 self.sig.repr(tcx))
845     }
846     #[cfg(not(stage0))]
847     fn repr(&self, tcx: &ctxt) -> String {
848         format!("BareFnTy {{fn_style: {:?}, abi: {}, sig: {}}}",
849                 self.fn_style,
850                 self.abi.to_str(),
851                 self.sig.repr(tcx))
852     }
853 }
854
855 impl Repr for ty::FnSig {
856     fn repr(&self, tcx: &ctxt) -> String {
857         fn_sig_to_str(tcx, self)
858     }
859 }
860
861 impl Repr for typeck::MethodCallee {
862     #[cfg(stage0)]
863     fn repr(&self, tcx: &ctxt) -> String {
864         format!("MethodCallee \\{origin: {}, ty: {}, {}\\}",
865                 self.origin.repr(tcx),
866                 self.ty.repr(tcx),
867                 self.substs.repr(tcx))
868     }
869     #[cfg(not(stage0))]
870     fn repr(&self, tcx: &ctxt) -> String {
871         format!("MethodCallee {{origin: {}, ty: {}, {}}}",
872                 self.origin.repr(tcx),
873                 self.ty.repr(tcx),
874                 self.substs.repr(tcx))
875     }
876 }
877
878 impl Repr for typeck::MethodOrigin {
879     fn repr(&self, tcx: &ctxt) -> String {
880         match self {
881             &typeck::MethodStatic(def_id) => {
882                 format!("MethodStatic({})", def_id.repr(tcx))
883             }
884             &typeck::MethodParam(ref p) => {
885                 p.repr(tcx)
886             }
887             &typeck::MethodObject(ref p) => {
888                 p.repr(tcx)
889             }
890         }
891     }
892 }
893
894 impl Repr for typeck::MethodParam {
895     fn repr(&self, tcx: &ctxt) -> String {
896         format!("MethodParam({},{:?},{:?},{:?})",
897                 self.trait_id.repr(tcx),
898                 self.method_num,
899                 self.param_num,
900                 self.bound_num)
901     }
902 }
903
904 impl Repr for typeck::MethodObject {
905     fn repr(&self, tcx: &ctxt) -> String {
906         format!("MethodObject({},{:?},{:?})",
907                 self.trait_id.repr(tcx),
908                 self.method_num,
909                 self.real_index)
910     }
911 }
912
913
914 impl Repr for ty::RegionVid {
915     fn repr(&self, _tcx: &ctxt) -> String {
916         format!("{:?}", *self)
917     }
918 }
919
920 impl Repr for ty::TraitStore {
921     fn repr(&self, tcx: &ctxt) -> String {
922         trait_store_to_str(tcx, *self)
923     }
924 }
925
926 impl Repr for ty::BuiltinBound {
927     fn repr(&self, _tcx: &ctxt) -> String {
928         format!("{:?}", *self)
929     }
930 }
931
932 impl UserString for ty::BuiltinBound {
933     fn user_string(&self, _tcx: &ctxt) -> String {
934         match *self {
935             ty::BoundStatic => "'static".to_string(),
936             ty::BoundSend => "Send".to_string(),
937             ty::BoundSized => "Sized".to_string(),
938             ty::BoundCopy => "Copy".to_string(),
939             ty::BoundShare => "Share".to_string(),
940         }
941     }
942 }
943
944 impl Repr for ty::BuiltinBounds {
945     fn repr(&self, tcx: &ctxt) -> String {
946         self.user_string(tcx)
947     }
948 }
949
950 impl Repr for Span {
951     fn repr(&self, tcx: &ctxt) -> String {
952         tcx.sess.codemap().span_to_str(*self).to_string()
953     }
954 }
955
956 impl<A:UserString> UserString for Rc<A> {
957     fn user_string(&self, tcx: &ctxt) -> String {
958         let this: &A = &**self;
959         this.user_string(tcx)
960     }
961 }
962
963 impl UserString for ty::BuiltinBounds {
964     fn user_string(&self, tcx: &ctxt) -> String {
965         self.iter()
966             .map(|bb| bb.user_string(tcx))
967             .collect::<Vec<String>>()
968             .connect("+")
969             .to_string()
970     }
971 }
972
973 impl UserString for ty::TraitRef {
974     fn user_string(&self, tcx: &ctxt) -> String {
975         let base = ty::item_path_str(tcx, self.def_id);
976         let trait_def = ty::lookup_trait_def(tcx, self.def_id);
977         parameterized(tcx, base.as_slice(), &self.substs, &trait_def.generics)
978     }
979 }
980
981 impl UserString for ty::t {
982     fn user_string(&self, tcx: &ctxt) -> String {
983         ty_to_str(tcx, *self)
984     }
985 }
986
987 impl UserString for ast::Ident {
988     fn user_string(&self, _tcx: &ctxt) -> String {
989         token::get_name(self.name).get().to_string()
990     }
991 }
992
993 impl Repr for abi::Abi {
994     fn repr(&self, _tcx: &ctxt) -> String {
995         self.to_str()
996     }
997 }
998
999 impl UserString for abi::Abi {
1000     fn user_string(&self, _tcx: &ctxt) -> String {
1001         self.to_str()
1002     }
1003 }
1004
1005 impl Repr for ty::UpvarId {
1006     fn repr(&self, tcx: &ctxt) -> String {
1007         format!("UpvarId({};`{}`;{})",
1008                 self.var_id,
1009                 ty::local_var_name_str(tcx, self.var_id),
1010                 self.closure_expr_id)
1011     }
1012 }
1013
1014 impl Repr for ast::Mutability {
1015     fn repr(&self, _tcx: &ctxt) -> String {
1016         format!("{:?}", *self)
1017     }
1018 }
1019
1020 impl Repr for ty::BorrowKind {
1021     fn repr(&self, _tcx: &ctxt) -> String {
1022         format!("{:?}", *self)
1023     }
1024 }
1025
1026 impl Repr for ty::UpvarBorrow {
1027     fn repr(&self, tcx: &ctxt) -> String {
1028         format!("UpvarBorrow({}, {})",
1029                 self.kind.repr(tcx),
1030                 self.region.repr(tcx))
1031     }
1032 }