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