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