]> git.lizzy.rs Git - rust.git/blob - src/librustc/util/ppaux.rs
auto merge of #16512 : wickerwaka/rust/getopt-16348, r=brson
[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};
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_tup(ref elems) => {
374         let strs: Vec<String> = elems.iter().map(|elem| ty_to_string(cx, *elem)).collect();
375         format!("({})", strs.connect(","))
376       }
377       ty_closure(ref f) => {
378           closure_to_string(cx, &**f)
379       }
380       ty_bare_fn(ref f) => {
381           bare_fn_to_string(cx, f.fn_style, f.abi, None, &f.sig)
382       }
383       ty_infer(infer_ty) => infer_ty.to_string(),
384       ty_err => "[type error]".to_string(),
385       ty_param(ParamTy {idx: id, def_id: did, ..}) => {
386           let ident = match cx.ty_param_defs.borrow().find(&did.node) {
387               Some(def) => token::get_ident(def.ident).get().to_string(),
388               // This can only happen when a type mismatch error happens and
389               // the actual type has more type parameters than the expected one.
390               None => format!("<generic #{}>", id),
391           };
392           if !cx.sess.verbose() {
393               ident
394           } else {
395               format!("{}:{:?}", ident, did)
396           }
397       }
398       ty_enum(did, ref substs) | ty_struct(did, ref substs) => {
399           let base = ty::item_path_str(cx, did);
400           let generics = ty::lookup_item_type(cx, did).generics;
401           parameterized(cx, base.as_slice(), substs, &generics)
402       }
403       ty_trait(box ty::TyTrait {
404           def_id: did, ref substs, ref bounds
405       }) => {
406           let base = ty::item_path_str(cx, did);
407           let trait_def = ty::lookup_trait_def(cx, did);
408           let ty = parameterized(cx, base.as_slice(),
409                                  substs, &trait_def.generics);
410           let bound_sep = if bounds.is_empty() { "" } else { ":" };
411           let bound_str = bounds.repr(cx);
412           format!("{}{}{}",
413                   ty,
414                   bound_sep,
415                   bound_str)
416       }
417       ty_str => "str".to_string(),
418       ty_unboxed_closure(..) => "closure".to_string(),
419       ty_vec(ref mt, sz) => {
420           match sz {
421               Some(n) => {
422                   format!("[{}, .. {}]", mt_to_string(cx, mt), n)
423               }
424               None => format!("[{}]", ty_to_string(cx, mt.ty)),
425           }
426       }
427     }
428 }
429
430 pub fn explicit_self_category_to_str(category: &ty::ExplicitSelfCategory)
431                                      -> &'static str {
432     match *category {
433         ty::StaticExplicitSelfCategory => "static",
434         ty::ByValueExplicitSelfCategory => "self",
435         ty::ByReferenceExplicitSelfCategory(_, ast::MutMutable) => {
436             "&mut self"
437         }
438         ty::ByReferenceExplicitSelfCategory(_, ast::MutImmutable) => "&self",
439         ty::ByBoxExplicitSelfCategory => "Box<self>",
440     }
441 }
442
443 pub fn parameterized(cx: &ctxt,
444                      base: &str,
445                      substs: &subst::Substs,
446                      generics: &ty::Generics)
447                      -> String
448 {
449     let mut strs = Vec::new();
450
451     match substs.regions {
452         subst::ErasedRegions => { }
453         subst::NonerasedRegions(ref regions) => {
454             for &r in regions.iter() {
455                 let s = region_to_string(cx, "", false, r);
456                 if !s.is_empty() {
457                     strs.push(s)
458                 } else {
459                     // This happens when the value of the region
460                     // parameter is not easily serialized. This may be
461                     // because the user omitted it in the first place,
462                     // or because it refers to some block in the code,
463                     // etc. I'm not sure how best to serialize this.
464                     strs.push(format!("'_"));
465                 }
466             }
467         }
468     }
469
470     let tps = substs.types.get_slice(subst::TypeSpace);
471     let ty_params = generics.types.get_slice(subst::TypeSpace);
472     let has_defaults = ty_params.last().map_or(false, |def| def.default.is_some());
473     let num_defaults = if has_defaults && !cx.sess.verbose() {
474         ty_params.iter().zip(tps.iter()).rev().take_while(|&(def, &actual)| {
475             match def.default {
476                 Some(default) => default.subst(cx, substs) == actual,
477                 None => false
478             }
479         }).count()
480     } else {
481         0
482     };
483
484     for t in tps.slice_to(tps.len() - num_defaults).iter() {
485         strs.push(ty_to_string(cx, *t))
486     }
487
488     if cx.sess.verbose() {
489         for t in substs.types.get_slice(subst::SelfSpace).iter() {
490             strs.push(format!("for {}", t.repr(cx)));
491         }
492     }
493
494     if strs.len() > 0u {
495         format!("{}<{}>", base, strs.connect(","))
496     } else {
497         format!("{}", base)
498     }
499 }
500
501 pub fn ty_to_short_str(cx: &ctxt, typ: t) -> String {
502     let mut s = typ.repr(cx).to_string();
503     if s.len() >= 32u {
504         s = s.as_slice().slice(0u, 32u).to_string();
505     }
506     return s;
507 }
508
509 impl<T:Repr> Repr for Option<T> {
510     fn repr(&self, tcx: &ctxt) -> String {
511         match self {
512             &None => "None".to_string(),
513             &Some(ref t) => t.repr(tcx),
514         }
515     }
516 }
517
518 impl<T:Repr,U:Repr> Repr for Result<T,U> {
519     fn repr(&self, tcx: &ctxt) -> String {
520         match self {
521             &Ok(ref t) => t.repr(tcx),
522             &Err(ref u) => format!("Err({})", u.repr(tcx))
523         }
524     }
525 }
526
527 impl Repr for () {
528     fn repr(&self, _tcx: &ctxt) -> String {
529         "()".to_string()
530     }
531 }
532
533 impl<T:Repr> Repr for Rc<T> {
534     fn repr(&self, tcx: &ctxt) -> String {
535         (&**self).repr(tcx)
536     }
537 }
538
539 impl<T:Repr + 'static> Repr for Gc<T> {
540     fn repr(&self, tcx: &ctxt) -> String {
541         (&**self).repr(tcx)
542     }
543 }
544
545 impl<T:Repr> Repr for Box<T> {
546     fn repr(&self, tcx: &ctxt) -> String {
547         (&**self).repr(tcx)
548     }
549 }
550
551 fn repr_vec<T:Repr>(tcx: &ctxt, v: &[T]) -> String {
552     vec_map_to_string(v, |t| t.repr(tcx))
553 }
554
555 impl<'a, T:Repr> Repr for &'a [T] {
556     fn repr(&self, tcx: &ctxt) -> String {
557         repr_vec(tcx, *self)
558     }
559 }
560
561 impl<T:Repr> Repr for OwnedSlice<T> {
562     fn repr(&self, tcx: &ctxt) -> String {
563         repr_vec(tcx, self.as_slice())
564     }
565 }
566
567 // This is necessary to handle types like Option<~[T]>, for which
568 // autoderef cannot convert the &[T] handler
569 impl<T:Repr> Repr for Vec<T> {
570     fn repr(&self, tcx: &ctxt) -> String {
571         repr_vec(tcx, self.as_slice())
572     }
573 }
574
575 impl Repr for def::Def {
576     fn repr(&self, _tcx: &ctxt) -> String {
577         format!("{:?}", *self)
578     }
579 }
580
581 impl Repr for ty::TypeParameterDef {
582     fn repr(&self, tcx: &ctxt) -> String {
583         format!("TypeParameterDef({:?}, {})", self.def_id,
584                 self.bounds.repr(tcx))
585     }
586 }
587
588 impl Repr for ty::RegionParameterDef {
589     fn repr(&self, _tcx: &ctxt) -> String {
590         format!("RegionParameterDef({}, {:?})",
591                 token::get_name(self.name),
592                 self.def_id)
593     }
594 }
595
596 impl Repr for ty::t {
597     fn repr(&self, tcx: &ctxt) -> String {
598         ty_to_string(tcx, *self)
599     }
600 }
601
602 impl Repr for ty::mt {
603     fn repr(&self, tcx: &ctxt) -> String {
604         mt_to_string(tcx, self)
605     }
606 }
607
608 impl Repr for subst::Substs {
609     fn repr(&self, tcx: &ctxt) -> String {
610         format!("Substs[types={}, regions={}]",
611                        self.types.repr(tcx),
612                        self.regions.repr(tcx))
613     }
614 }
615
616 impl<T:Repr> Repr for subst::VecPerParamSpace<T> {
617     fn repr(&self, tcx: &ctxt) -> String {
618         format!("[{};{};{}]",
619                        self.get_slice(subst::TypeSpace).repr(tcx),
620                        self.get_slice(subst::SelfSpace).repr(tcx),
621                        self.get_slice(subst::FnSpace).repr(tcx))
622     }
623 }
624
625 impl Repr for ty::ItemSubsts {
626     fn repr(&self, tcx: &ctxt) -> String {
627         format!("ItemSubsts({})", self.substs.repr(tcx))
628     }
629 }
630
631 impl Repr for subst::RegionSubsts {
632     fn repr(&self, tcx: &ctxt) -> String {
633         match *self {
634             subst::ErasedRegions => "erased".to_string(),
635             subst::NonerasedRegions(ref regions) => regions.repr(tcx)
636         }
637     }
638 }
639
640 impl Repr for ty::ParamBounds {
641     fn repr(&self, tcx: &ctxt) -> String {
642         let mut res = Vec::new();
643         for b in self.builtin_bounds.iter() {
644             res.push(match b {
645                 ty::BoundStatic => "'static".to_string(),
646                 ty::BoundSend => "Send".to_string(),
647                 ty::BoundSized => "Sized".to_string(),
648                 ty::BoundCopy => "Copy".to_string(),
649                 ty::BoundSync => "Sync".to_string(),
650             });
651         }
652         for t in self.trait_bounds.iter() {
653             res.push(t.repr(tcx));
654         }
655         res.connect("+")
656     }
657 }
658
659 impl Repr for ty::TraitRef {
660     fn repr(&self, tcx: &ctxt) -> String {
661         trait_ref_to_string(tcx, self)
662     }
663 }
664
665 impl Repr for ast::Expr {
666     fn repr(&self, _tcx: &ctxt) -> String {
667         format!("expr({}: {})", self.id, pprust::expr_to_string(self))
668     }
669 }
670
671 impl Repr for ast::Path {
672     fn repr(&self, _tcx: &ctxt) -> String {
673         format!("path({})", pprust::path_to_string(self))
674     }
675 }
676
677 impl Repr for ast::Item {
678     fn repr(&self, tcx: &ctxt) -> String {
679         format!("item({})", tcx.map.node_to_string(self.id))
680     }
681 }
682
683 impl Repr for ast::Stmt {
684     fn repr(&self, _tcx: &ctxt) -> String {
685         format!("stmt({}: {})",
686                 ast_util::stmt_id(self),
687                 pprust::stmt_to_string(self))
688     }
689 }
690
691 impl Repr for ast::Pat {
692     fn repr(&self, _tcx: &ctxt) -> String {
693         format!("pat({}: {})", self.id, pprust::pat_to_string(self))
694     }
695 }
696
697 impl Repr for ty::BoundRegion {
698     fn repr(&self, tcx: &ctxt) -> String {
699         match *self {
700             ty::BrAnon(id) => format!("BrAnon({})", id),
701             ty::BrNamed(id, name) => {
702                 format!("BrNamed({}, {})", id.repr(tcx), token::get_name(name))
703             }
704             ty::BrFresh(id) => format!("BrFresh({})", id),
705         }
706     }
707 }
708
709 impl Repr for ty::Region {
710     fn repr(&self, tcx: &ctxt) -> String {
711         match *self {
712             ty::ReEarlyBound(id, space, index, name) => {
713                 format!("ReEarlyBound({}, {}, {}, {})",
714                                id,
715                                space,
716                                index,
717                                token::get_name(name))
718             }
719
720             ty::ReLateBound(binder_id, ref bound_region) => {
721                 format!("ReLateBound({}, {})",
722                         binder_id,
723                         bound_region.repr(tcx))
724             }
725
726             ty::ReFree(ref fr) => {
727                 format!("ReFree({}, {})",
728                         fr.scope_id,
729                         fr.bound_region.repr(tcx))
730             }
731
732             ty::ReScope(id) => {
733                 format!("ReScope({})", id)
734             }
735
736             ty::ReStatic => {
737                 "ReStatic".to_string()
738             }
739
740             ty::ReInfer(ReVar(ref vid)) => {
741                 format!("ReInfer({})", vid.index)
742             }
743
744             ty::ReInfer(ReSkolemized(id, ref bound_region)) => {
745                 format!("re_skolemized({}, {})", id, bound_region.repr(tcx))
746             }
747
748             ty::ReEmpty => {
749                 "ReEmpty".to_string()
750             }
751         }
752     }
753 }
754
755 impl Repr for ast::DefId {
756     fn repr(&self, tcx: &ctxt) -> String {
757         // Unfortunately, there seems to be no way to attempt to print
758         // a path for a def-id, so I'll just make a best effort for now
759         // and otherwise fallback to just printing the crate/node pair
760         if self.krate == ast::LOCAL_CRATE {
761             {
762                 match tcx.map.find(self.node) {
763                     Some(ast_map::NodeItem(..)) |
764                     Some(ast_map::NodeForeignItem(..)) |
765                     Some(ast_map::NodeImplItem(..)) |
766                     Some(ast_map::NodeTraitItem(..)) |
767                     Some(ast_map::NodeVariant(..)) |
768                     Some(ast_map::NodeStructCtor(..)) => {
769                         return format!(
770                                 "{:?}:{}",
771                                 *self,
772                                 ty::item_path_str(tcx, *self))
773                     }
774                     _ => {}
775                 }
776             }
777         }
778         return format!("{:?}", *self)
779     }
780 }
781
782 impl Repr for ty::Polytype {
783     fn repr(&self, tcx: &ctxt) -> String {
784         format!("Polytype {{generics: {}, ty: {}}}",
785                 self.generics.repr(tcx),
786                 self.ty.repr(tcx))
787     }
788 }
789
790 impl Repr for ty::Generics {
791     fn repr(&self, tcx: &ctxt) -> String {
792         format!("Generics(types: {}, regions: {})",
793                 self.types.repr(tcx),
794                 self.regions.repr(tcx))
795     }
796 }
797
798 impl Repr for ty::ItemVariances {
799     fn repr(&self, tcx: &ctxt) -> String {
800         format!("ItemVariances(types={}, \
801                 regions={})",
802                 self.types.repr(tcx),
803                 self.regions.repr(tcx))
804     }
805 }
806
807 impl Repr for ty::Variance {
808     fn repr(&self, _: &ctxt) -> String {
809         // The first `.to_string()` returns a &'static str (it is not an implementation
810         // of the ToString trait). Because of that, we need to call `.to_string()` again
811         // if we want to have a `String`.
812         self.to_string().to_string()
813     }
814 }
815
816 impl Repr for ty::Method {
817     fn repr(&self, tcx: &ctxt) -> String {
818         format!("method(ident: {}, generics: {}, fty: {}, \
819                  explicit_self: {}, vis: {}, def_id: {})",
820                 self.ident.repr(tcx),
821                 self.generics.repr(tcx),
822                 self.fty.repr(tcx),
823                 self.explicit_self.repr(tcx),
824                 self.vis.repr(tcx),
825                 self.def_id.repr(tcx))
826     }
827 }
828
829 impl Repr for ast::Name {
830     fn repr(&self, _tcx: &ctxt) -> String {
831         token::get_name(*self).get().to_string()
832     }
833 }
834
835 impl Repr for ast::Ident {
836     fn repr(&self, _tcx: &ctxt) -> String {
837         token::get_ident(*self).get().to_string()
838     }
839 }
840
841 impl Repr for ast::ExplicitSelf_ {
842     fn repr(&self, _tcx: &ctxt) -> String {
843         format!("{:?}", *self)
844     }
845 }
846
847 impl Repr for ast::Visibility {
848     fn repr(&self, _tcx: &ctxt) -> String {
849         format!("{:?}", *self)
850     }
851 }
852
853 impl Repr for ty::BareFnTy {
854     fn repr(&self, tcx: &ctxt) -> String {
855         format!("BareFnTy {{fn_style: {:?}, abi: {}, sig: {}}}",
856                 self.fn_style,
857                 self.abi.to_string(),
858                 self.sig.repr(tcx))
859     }
860 }
861
862 impl Repr for ty::FnSig {
863     fn repr(&self, tcx: &ctxt) -> String {
864         fn_sig_to_string(tcx, self)
865     }
866 }
867
868 impl Repr for typeck::MethodCallee {
869     fn repr(&self, tcx: &ctxt) -> String {
870         format!("MethodCallee {{origin: {}, ty: {}, {}}}",
871                 self.origin.repr(tcx),
872                 self.ty.repr(tcx),
873                 self.substs.repr(tcx))
874     }
875 }
876
877 impl Repr for typeck::MethodOrigin {
878     fn repr(&self, tcx: &ctxt) -> String {
879         match self {
880             &typeck::MethodStatic(def_id) => {
881                 format!("MethodStatic({})", def_id.repr(tcx))
882             }
883             &typeck::MethodStaticUnboxedClosure(def_id) => {
884                 format!("MethodStaticUnboxedClosure({})", def_id.repr(tcx))
885             }
886             &typeck::MethodParam(ref p) => {
887                 p.repr(tcx)
888             }
889             &typeck::MethodObject(ref p) => {
890                 p.repr(tcx)
891             }
892         }
893     }
894 }
895
896 impl Repr for typeck::MethodParam {
897     fn repr(&self, tcx: &ctxt) -> String {
898         format!("MethodParam({},{:?},{:?},{:?})",
899                 self.trait_id.repr(tcx),
900                 self.method_num,
901                 self.param_num,
902                 self.bound_num)
903     }
904 }
905
906 impl Repr for typeck::MethodObject {
907     fn repr(&self, tcx: &ctxt) -> String {
908         format!("MethodObject({},{:?},{:?})",
909                 self.trait_id.repr(tcx),
910                 self.method_num,
911                 self.real_index)
912     }
913 }
914
915 impl Repr for ty::TraitStore {
916     fn repr(&self, tcx: &ctxt) -> String {
917         trait_store_to_string(tcx, *self)
918     }
919 }
920
921 impl Repr for ty::BuiltinBound {
922     fn repr(&self, _tcx: &ctxt) -> String {
923         format!("{:?}", *self)
924     }
925 }
926
927 impl UserString for ty::BuiltinBound {
928     fn user_string(&self, _tcx: &ctxt) -> String {
929         match *self {
930             ty::BoundStatic => "'static".to_string(),
931             ty::BoundSend => "Send".to_string(),
932             ty::BoundSized => "Sized".to_string(),
933             ty::BoundCopy => "Copy".to_string(),
934             ty::BoundSync => "Sync".to_string(),
935         }
936     }
937 }
938
939 impl Repr for ty::BuiltinBounds {
940     fn repr(&self, tcx: &ctxt) -> String {
941         self.user_string(tcx)
942     }
943 }
944
945 impl Repr for Span {
946     fn repr(&self, tcx: &ctxt) -> String {
947         tcx.sess.codemap().span_to_string(*self).to_string()
948     }
949 }
950
951 impl<A:UserString> UserString for Rc<A> {
952     fn user_string(&self, tcx: &ctxt) -> String {
953         let this: &A = &**self;
954         this.user_string(tcx)
955     }
956 }
957
958 impl UserString for ty::BuiltinBounds {
959     fn user_string(&self, tcx: &ctxt) -> String {
960         self.iter()
961             .map(|bb| bb.user_string(tcx))
962             .collect::<Vec<String>>()
963             .connect("+")
964             .to_string()
965     }
966 }
967
968 impl UserString for ty::TraitRef {
969     fn user_string(&self, tcx: &ctxt) -> String {
970         let base = ty::item_path_str(tcx, self.def_id);
971         let trait_def = ty::lookup_trait_def(tcx, self.def_id);
972         parameterized(tcx, base.as_slice(), &self.substs, &trait_def.generics)
973     }
974 }
975
976 impl UserString for ty::t {
977     fn user_string(&self, tcx: &ctxt) -> String {
978         ty_to_string(tcx, *self)
979     }
980 }
981
982 impl UserString for ast::Ident {
983     fn user_string(&self, _tcx: &ctxt) -> String {
984         token::get_name(self.name).get().to_string()
985     }
986 }
987
988 impl Repr for abi::Abi {
989     fn repr(&self, _tcx: &ctxt) -> String {
990         self.to_string()
991     }
992 }
993
994 impl UserString for abi::Abi {
995     fn user_string(&self, _tcx: &ctxt) -> String {
996         self.to_string()
997     }
998 }
999
1000 impl Repr for ty::UpvarId {
1001     fn repr(&self, tcx: &ctxt) -> String {
1002         format!("UpvarId({};`{}`;{})",
1003                 self.var_id,
1004                 ty::local_var_name_str(tcx, self.var_id),
1005                 self.closure_expr_id)
1006     }
1007 }
1008
1009 impl Repr for ast::Mutability {
1010     fn repr(&self, _tcx: &ctxt) -> String {
1011         format!("{:?}", *self)
1012     }
1013 }
1014
1015 impl Repr for ty::BorrowKind {
1016     fn repr(&self, _tcx: &ctxt) -> String {
1017         format!("{:?}", *self)
1018     }
1019 }
1020
1021 impl Repr for ty::UpvarBorrow {
1022     fn repr(&self, tcx: &ctxt) -> String {
1023         format!("UpvarBorrow({}, {})",
1024                 self.kind.repr(tcx),
1025                 self.region.repr(tcx))
1026     }
1027 }
1028
1029 impl Repr for ty::IntVid {
1030     fn repr(&self, _tcx: &ctxt) -> String {
1031         format!("{}", self)
1032     }
1033 }
1034
1035 impl Repr for ty::FloatVid {
1036     fn repr(&self, _tcx: &ctxt) -> String {
1037         format!("{}", self)
1038     }
1039 }
1040
1041 impl Repr for ty::RegionVid {
1042     fn repr(&self, _tcx: &ctxt) -> String {
1043         format!("{}", self)
1044     }
1045 }
1046
1047 impl Repr for ty::TyVid {
1048     fn repr(&self, _tcx: &ctxt) -> String {
1049         format!("{}", self)
1050     }
1051 }
1052
1053 impl Repr for ty::IntVarValue {
1054     fn repr(&self, _tcx: &ctxt) -> String {
1055         format!("{:?}", *self)
1056     }
1057 }
1058
1059 impl Repr for ast::IntTy {
1060     fn repr(&self, _tcx: &ctxt) -> String {
1061         format!("{:?}", *self)
1062     }
1063 }
1064
1065 impl Repr for ast::UintTy {
1066     fn repr(&self, _tcx: &ctxt) -> String {
1067         format!("{:?}", *self)
1068     }
1069 }
1070
1071 impl Repr for ast::FloatTy {
1072     fn repr(&self, _tcx: &ctxt) -> String {
1073         format!("{:?}", *self)
1074     }
1075 }
1076
1077 impl<T:Repr> Repr for infer::Bounds<T> {
1078     fn repr(&self, tcx: &ctxt) -> String {
1079         format!("({} <= {})",
1080                 self.lb.repr(tcx),
1081                 self.ub.repr(tcx))
1082     }
1083 }
1084
1085 impl<K:Repr,V:Repr> Repr for VV<K,V> {
1086     fn repr(&self, tcx: &ctxt) -> String {
1087         match *self {
1088             unify::Redirect(ref k) =>
1089                 format!("Redirect({})", k.repr(tcx)),
1090             unify::Root(ref v, r) =>
1091                 format!("Root({}, {})", v.repr(tcx), r)
1092         }
1093     }
1094 }
1095
1096 impl Repr for region_inference::VarValue {
1097     fn repr(&self, tcx: &ctxt) -> String {
1098         match *self {
1099             infer::region_inference::NoValue =>
1100                 format!("NoValue"),
1101             infer::region_inference::Value(r) =>
1102                 format!("Value({})", r.repr(tcx)),
1103             infer::region_inference::ErrorValue =>
1104                 format!("ErrorValue"),
1105         }
1106     }
1107 }
1108
1109 impl Repr for ty::ExplicitSelfCategory {
1110     fn repr(&self, _: &ctxt) -> String {
1111         explicit_self_category_to_str(self).to_string()
1112     }
1113 }
1114