]> git.lizzy.rs Git - rust.git/blob - src/librustc/util/ppaux.rs
auto merge of #13424 : eddyb/rust/ty-mut-in-store, r=nikomatsakis
[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     format!("{}{}", mutability_to_str(m.mutbl), ty_to_str(cx, m.ty))
202 }
203
204 pub fn trait_store_to_str(cx: &ctxt, s: ty::TraitStore) -> ~str {
205     match s {
206         ty::UniqTraitStore => ~"~",
207         ty::RegionTraitStore(r, m) => {
208             format!("{}{}", region_ptr_to_str(cx, r), mutability_to_str(m))
209         }
210     }
211 }
212
213 pub fn vec_map_to_str<T>(ts: &[T], f: |t: &T| -> ~str) -> ~str {
214     let tstrs = ts.iter().map(f).collect::<Vec<~str>>();
215     format!("[{}]", tstrs.connect(", "))
216 }
217
218 pub fn fn_sig_to_str(cx: &ctxt, typ: &ty::FnSig) -> ~str {
219     format!("fn{}{} -> {}",
220             typ.binder_id,
221             typ.inputs.repr(cx),
222             typ.output.repr(cx))
223 }
224
225 pub fn trait_ref_to_str(cx: &ctxt, trait_ref: &ty::TraitRef) -> ~str {
226     trait_ref.user_string(cx)
227 }
228
229 pub fn ty_to_str(cx: &ctxt, typ: t) -> ~str {
230     fn fn_input_to_str(cx: &ctxt, input: ty::t) -> ~str {
231         ty_to_str(cx, input)
232     }
233     fn bare_fn_to_str(cx: &ctxt,
234                       fn_style: ast::FnStyle,
235                       abi: abi::Abi,
236                       ident: Option<ast::Ident>,
237                       sig: &ty::FnSig)
238                       -> ~str {
239         let mut s = if abi == abi::Rust {
240             StrBuf::new()
241         } else {
242             StrBuf::from_owned_str(format!("extern {} ", abi.to_str()))
243         };
244
245         match fn_style {
246             ast::NormalFn => {}
247             _ => {
248                 s.push_str(fn_style.to_str());
249                 s.push_char(' ');
250             }
251         };
252
253         s.push_str("fn");
254
255         match ident {
256             Some(i) => {
257                 s.push_char(' ');
258                 s.push_str(token::get_ident(i).get());
259             }
260             _ => { }
261         }
262
263         push_sig_to_str(cx, &mut s, '(', ')', sig);
264
265         s.into_owned()
266     }
267
268     fn closure_to_str(cx: &ctxt, cty: &ty::ClosureTy) -> ~str {
269         let is_proc =
270             (cty.sigil, cty.onceness) == (ast::OwnedSigil, ast::Once);
271         let is_borrowed_closure = cty.sigil == ast::BorrowedSigil;
272
273         let mut s = if is_proc || is_borrowed_closure {
274             StrBuf::new()
275         } else {
276             StrBuf::from_owned_str(cty.sigil.to_str())
277         };
278
279         match (cty.sigil, cty.region) {
280             (ast::ManagedSigil, ty::ReStatic) |
281             (ast::OwnedSigil, ty::ReStatic) => {}
282
283             (_, region) => {
284                 s.push_str(region_to_str(cx, "", true, region));
285             }
286         }
287
288         match cty.fn_style {
289             ast::NormalFn => {}
290             _ => {
291                 s.push_str(cty.fn_style.to_str());
292                 s.push_char(' ');
293             }
294         };
295
296         if is_proc {
297             s.push_str("proc");
298         } else {
299             match cty.onceness {
300                 ast::Many => {}
301                 ast::Once => {
302                     s.push_str(cty.onceness.to_str());
303                     s.push_char(' ');
304                 }
305             };
306
307             if !is_borrowed_closure {
308                 s.push_str("fn");
309             }
310         }
311
312         if !is_borrowed_closure {
313             // Print bounds before `fn` if this is not a borrowed closure.
314             if !cty.bounds.is_empty() {
315                 s.push_str(":");
316                 s.push_str(cty.bounds.repr(cx));
317             }
318
319             push_sig_to_str(cx, &mut s, '(', ')', &cty.sig);
320         } else {
321             // Print bounds after the signature if this is a borrowed closure.
322             push_sig_to_str(cx, &mut s, '|', '|', &cty.sig);
323
324             if is_borrowed_closure {
325                 if !cty.bounds.is_empty() {
326                     s.push_str(":");
327                     s.push_str(cty.bounds.repr(cx));
328                 }
329             }
330         }
331
332         s.into_owned()
333     }
334
335     fn push_sig_to_str(cx: &ctxt,
336                        s: &mut StrBuf,
337                        bra: char,
338                        ket: char,
339                        sig: &ty::FnSig) {
340         s.push_char(bra);
341         let strs: Vec<~str> = sig.inputs.iter().map(|a| fn_input_to_str(cx, *a)).collect();
342         s.push_str(strs.connect(", "));
343         if sig.variadic {
344             s.push_str(", ...");
345         }
346         s.push_char(ket);
347
348         if ty::get(sig.output).sty != ty_nil {
349             s.push_str(" -> ");
350             if ty::type_is_bot(sig.output) {
351                 s.push_char('!');
352             } else {
353                 s.push_str(ty_to_str(cx, sig.output));
354             }
355         }
356     }
357
358     // if there is an id, print that instead of the structural type:
359     /*for def_id in ty::type_def_id(typ).iter() {
360         // note that this typedef cannot have type parameters
361         return ty::item_path_str(cx, *def_id);
362     }*/
363
364     // pretty print the structural type representation:
365     return match ty::get(typ).sty {
366       ty_nil => ~"()",
367       ty_bot => ~"!",
368       ty_bool => ~"bool",
369       ty_char => ~"char",
370       ty_int(ast::TyI) => ~"int",
371       ty_int(t) => ast_util::int_ty_to_str(t),
372       ty_uint(ast::TyU) => ~"uint",
373       ty_uint(t) => ast_util::uint_ty_to_str(t),
374       ty_float(t) => ast_util::float_ty_to_str(t),
375       ty_box(typ) => ~"@" + ty_to_str(cx, typ),
376       ty_uniq(typ) => ~"~" + ty_to_str(cx, typ),
377       ty_ptr(ref tm) => ~"*" + mt_to_str(cx, tm),
378       ty_rptr(r, ref tm) => {
379         region_ptr_to_str(cx, r) + mt_to_str(cx, tm)
380       }
381       ty_tup(ref elems) => {
382         let strs: Vec<~str> = elems.iter().map(|elem| ty_to_str(cx, *elem)).collect();
383         ~"(" + strs.connect(",") + ")"
384       }
385       ty_closure(ref f) => {
386           closure_to_str(cx, *f)
387       }
388       ty_bare_fn(ref f) => {
389           bare_fn_to_str(cx, f.fn_style, f.abi, None, &f.sig)
390       }
391       ty_infer(infer_ty) => infer_ty.to_str(),
392       ty_err => ~"[type error]",
393       ty_param(param_ty {idx: id, def_id: did}) => {
394           let ident = match cx.ty_param_defs.borrow().find(&did.node) {
395               Some(def) => token::get_ident(def.ident).get().to_str(),
396               // This should not happen...
397               None => format!("BUG[{:?}]", id)
398           };
399           if !cx.sess.verbose() {
400               ident
401           } else {
402             format!("{}:{:?}", ident, did)
403           }
404       }
405       ty_self(..) => ~"Self",
406       ty_enum(did, ref substs) | ty_struct(did, ref substs) => {
407         let base = ty::item_path_str(cx, did);
408         parameterized(cx,
409                       base,
410                       &substs.regions,
411                       substs.tps.as_slice(),
412                       did,
413                       false)
414       }
415       ty_trait(~ty::TyTrait {
416           def_id: did, ref substs, store, ref bounds
417       }) => {
418         let base = ty::item_path_str(cx, did);
419         let ty = parameterized(cx, base, &substs.regions,
420                                substs.tps.as_slice(), did, true);
421         let bound_sep = if bounds.is_empty() { "" } else { ":" };
422         let bound_str = bounds.repr(cx);
423         format!("{}{}{}{}", trait_store_to_str(cx, store), ty, bound_sep, bound_str)
424       }
425       ty_vec(ty, vs) => {
426         match vs {
427             ty::VstoreFixed(n) => {
428                 format!("[{}, .. {}]", ty_to_str(cx, ty), n)
429             }
430             _ => {
431                 format!("{}[{}]", vs.repr(cx), ty_to_str(cx, ty))
432             }
433         }
434       }
435       ty_str(vs) => {
436         match vs {
437             ty::VstoreFixed(n) => format!("str/{}", n),
438             ty::VstoreUniq => ~"~str",
439             ty::VstoreSlice(r, ()) => format!("{}str", region_ptr_to_str(cx, r))
440         }
441       }
442     }
443 }
444
445 pub fn parameterized(cx: &ctxt,
446                      base: &str,
447                      regions: &ty::RegionSubsts,
448                      tps: &[ty::t],
449                      did: ast::DefId,
450                      is_trait: bool) -> ~str {
451
452     let mut strs = Vec::new();
453     match *regions {
454         ty::ErasedRegions => { }
455         ty::NonerasedRegions(ref regions) => {
456             for &r in regions.iter() {
457                 strs.push(region_to_str(cx, "", false, r))
458             }
459         }
460     }
461
462     let generics = if is_trait {
463         ty::lookup_trait_def(cx, did).generics.clone()
464     } else {
465         ty::lookup_item_type(cx, did).generics
466     };
467     let ty_params = generics.type_param_defs();
468     let has_defaults = ty_params.last().map_or(false, |def| def.default.is_some());
469     let num_defaults = if has_defaults {
470         // We should have a borrowed version of substs instead of cloning.
471         let mut substs = ty::substs {
472             tps: Vec::from_slice(tps),
473             regions: regions.clone(),
474             self_ty: None
475         };
476         ty_params.iter().zip(tps.iter()).rev().take_while(|&(def, &actual)| {
477             substs.tps.pop();
478             match def.default {
479                 Some(default) => ty::subst(cx, &substs, default) == actual,
480                 None => false
481             }
482         }).len()
483     } else {
484         0
485     };
486
487     for t in tps.slice_to(tps.len() - num_defaults).iter() {
488         strs.push(ty_to_str(cx, *t))
489     }
490
491     if strs.len() > 0u {
492         format!("{}<{}>", base, strs.connect(","))
493     } else {
494         format!("{}", base)
495     }
496 }
497
498 pub fn ty_to_short_str(cx: &ctxt, typ: t) -> ~str {
499     let mut s = encoder::encoded_ty(cx, typ);
500     if s.len() >= 32u { s = s.slice(0u, 32u).to_owned(); }
501     return s;
502 }
503
504 impl<T:Repr> Repr for Option<T> {
505     fn repr(&self, tcx: &ctxt) -> ~str {
506         match self {
507             &None => ~"None",
508             &Some(ref t) => t.repr(tcx),
509         }
510     }
511 }
512
513 impl<T:Repr,U:Repr> Repr for Result<T,U> {
514     fn repr(&self, tcx: &ctxt) -> ~str {
515         match self {
516             &Ok(ref t) => t.repr(tcx),
517             &Err(ref u) => format!("Err({})", u.repr(tcx))
518         }
519     }
520 }
521
522 impl Repr for () {
523     fn repr(&self, _tcx: &ctxt) -> ~str {
524         ~"()"
525     }
526 }
527
528 impl<T:Repr> Repr for @T {
529     fn repr(&self, tcx: &ctxt) -> ~str {
530         (&**self).repr(tcx)
531     }
532 }
533
534 impl<T:Repr> Repr for ~T {
535     fn repr(&self, tcx: &ctxt) -> ~str {
536         (&**self).repr(tcx)
537     }
538 }
539
540 fn repr_vec<T:Repr>(tcx: &ctxt, v: &[T]) -> ~str {
541     vec_map_to_str(v, |t| t.repr(tcx))
542 }
543
544 impl<'a, T:Repr> Repr for &'a [T] {
545     fn repr(&self, tcx: &ctxt) -> ~str {
546         repr_vec(tcx, *self)
547     }
548 }
549
550 impl<T:Repr> Repr for OwnedSlice<T> {
551     fn repr(&self, tcx: &ctxt) -> ~str {
552         repr_vec(tcx, self.as_slice())
553     }
554 }
555
556 // This is necessary to handle types like Option<~[T]>, for which
557 // autoderef cannot convert the &[T] handler
558 impl<T:Repr> Repr for Vec<T> {
559     fn repr(&self, tcx: &ctxt) -> ~str {
560         repr_vec(tcx, self.as_slice())
561     }
562 }
563
564 impl Repr for ty::TypeParameterDef {
565     fn repr(&self, tcx: &ctxt) -> ~str {
566         format!("TypeParameterDef({:?}, {})",
567                 self.def_id,
568                 self.bounds.repr(tcx))
569     }
570 }
571
572 impl Repr for ty::RegionParameterDef {
573     fn repr(&self, _tcx: &ctxt) -> ~str {
574         format!("RegionParameterDef({}, {:?})",
575                 token::get_name(self.name),
576                 self.def_id)
577     }
578 }
579
580 impl Repr for ty::t {
581     fn repr(&self, tcx: &ctxt) -> ~str {
582         ty_to_str(tcx, *self)
583     }
584 }
585
586 impl Repr for ty::substs {
587     fn repr(&self, tcx: &ctxt) -> ~str {
588         format!("substs(regions={}, self_ty={}, tps={})",
589              self.regions.repr(tcx),
590              self.self_ty.repr(tcx),
591              self.tps.repr(tcx))
592     }
593 }
594
595 impl Repr for ty::RegionSubsts {
596     fn repr(&self, tcx: &ctxt) -> ~str {
597         match *self {
598             ty::ErasedRegions => ~"erased",
599             ty::NonerasedRegions(ref regions) => regions.repr(tcx)
600         }
601     }
602 }
603
604 impl Repr for ty::ParamBounds {
605     fn repr(&self, tcx: &ctxt) -> ~str {
606         let mut res = Vec::new();
607         for b in self.builtin_bounds.iter() {
608             res.push(match b {
609                 ty::BoundStatic => ~"'static",
610                 ty::BoundSend => ~"Send",
611                 ty::BoundSized => ~"Sized",
612                 ty::BoundCopy => ~"Pod",
613                 ty::BoundShare => ~"Share",
614             });
615         }
616         for t in self.trait_bounds.iter() {
617             res.push(t.repr(tcx));
618         }
619         res.connect("+")
620     }
621 }
622
623 impl Repr for ty::TraitRef {
624     fn repr(&self, tcx: &ctxt) -> ~str {
625         trait_ref_to_str(tcx, self)
626     }
627 }
628
629 impl Repr for ast::Expr {
630     fn repr(&self, _tcx: &ctxt) -> ~str {
631         format!("expr({}: {})", self.id, pprust::expr_to_str(self))
632     }
633 }
634
635 impl Repr for ast::Item {
636     fn repr(&self, tcx: &ctxt) -> ~str {
637         format!("item({})", tcx.map.node_to_str(self.id))
638     }
639 }
640
641 impl Repr for ast::Stmt {
642     fn repr(&self, _tcx: &ctxt) -> ~str {
643         format!("stmt({}: {})",
644                 ast_util::stmt_id(self),
645                 pprust::stmt_to_str(self))
646     }
647 }
648
649 impl Repr for ast::Pat {
650     fn repr(&self, _tcx: &ctxt) -> ~str {
651         format!("pat({}: {})",
652              self.id,
653              pprust::pat_to_str(self))
654     }
655 }
656
657 impl Repr for ty::BoundRegion {
658     fn repr(&self, tcx: &ctxt) -> ~str {
659         match *self {
660             ty::BrAnon(id) => format!("BrAnon({})", id),
661             ty::BrNamed(id, name) => format!("BrNamed({}, {})",
662                                              id.repr(tcx),
663                                              token::get_name(name)),
664             ty::BrFresh(id) => format!("BrFresh({})", id),
665         }
666     }
667 }
668
669 impl Repr for ty::Region {
670     fn repr(&self, tcx: &ctxt) -> ~str {
671         match *self {
672             ty::ReEarlyBound(id, index, name) => {
673                 format!("ReEarlyBound({}, {}, {})",
674                         id, index, token::get_name(name))
675             }
676
677             ty::ReLateBound(binder_id, ref bound_region) => {
678                 format!("ReLateBound({}, {})",
679                         binder_id, bound_region.repr(tcx))
680             }
681
682             ty::ReFree(ref fr) => {
683                 format!("ReFree({}, {})",
684                         fr.scope_id,
685                         fr.bound_region.repr(tcx))
686             }
687
688             ty::ReScope(id) => {
689                 format!("ReScope({})", id)
690             }
691
692             ty::ReStatic => {
693                 format!("ReStatic")
694             }
695
696             ty::ReInfer(ReVar(ref vid)) => {
697                 format!("ReInfer({})", vid.id)
698             }
699
700             ty::ReInfer(ReSkolemized(id, ref bound_region)) => {
701                 format!("re_skolemized({}, {})",
702                         id, bound_region.repr(tcx))
703             }
704
705             ty::ReEmpty => {
706                 format!("ReEmpty")
707             }
708         }
709     }
710 }
711
712 impl Repr for ast::DefId {
713     fn repr(&self, tcx: &ctxt) -> ~str {
714         // Unfortunately, there seems to be no way to attempt to print
715         // a path for a def-id, so I'll just make a best effort for now
716         // and otherwise fallback to just printing the crate/node pair
717         if self.krate == ast::LOCAL_CRATE {
718             {
719                 match tcx.map.find(self.node) {
720                     Some(ast_map::NodeItem(..)) |
721                     Some(ast_map::NodeForeignItem(..)) |
722                     Some(ast_map::NodeMethod(..)) |
723                     Some(ast_map::NodeTraitMethod(..)) |
724                     Some(ast_map::NodeVariant(..)) |
725                     Some(ast_map::NodeStructCtor(..)) => {
726                         return format!("{:?}:{}",
727                                        *self,
728                                        ty::item_path_str(tcx, *self));
729                     }
730                     _ => {}
731                 }
732             }
733         }
734         return format!("{:?}", *self);
735     }
736 }
737
738 impl Repr for ty::ty_param_bounds_and_ty {
739     fn repr(&self, tcx: &ctxt) -> ~str {
740         format!("ty_param_bounds_and_ty \\{generics: {}, ty: {}\\}",
741              self.generics.repr(tcx),
742              self.ty.repr(tcx))
743     }
744 }
745
746 impl Repr for ty::Generics {
747     fn repr(&self, tcx: &ctxt) -> ~str {
748         format!("Generics(type_param_defs: {}, region_param_defs: {})",
749                 self.type_param_defs().repr(tcx),
750                 self.region_param_defs().repr(tcx))
751     }
752 }
753
754 impl Repr for ty::ItemVariances {
755     fn repr(&self, tcx: &ctxt) -> ~str {
756         format!("IterVariances(self_param={}, type_params={}, region_params={})",
757                 self.self_param.repr(tcx),
758                 self.type_params.repr(tcx),
759                 self.region_params.repr(tcx))
760     }
761 }
762
763 impl Repr for ty::Variance {
764     fn repr(&self, _: &ctxt) -> ~str {
765         self.to_str().to_owned()
766     }
767 }
768
769 impl Repr for ty::Method {
770     fn repr(&self, tcx: &ctxt) -> ~str {
771         format!("method(ident: {}, generics: {}, fty: {}, \
772                 explicit_self: {}, vis: {}, def_id: {})",
773                 self.ident.repr(tcx),
774                 self.generics.repr(tcx),
775                 self.fty.repr(tcx),
776                 self.explicit_self.repr(tcx),
777                 self.vis.repr(tcx),
778                 self.def_id.repr(tcx))
779     }
780 }
781
782 impl Repr for ast::Name {
783     fn repr(&self, _tcx: &ctxt) -> ~str {
784         token::get_name(*self).get().to_str()
785     }
786 }
787
788 impl Repr for ast::Ident {
789     fn repr(&self, _tcx: &ctxt) -> ~str {
790         token::get_ident(*self).get().to_str()
791     }
792 }
793
794 impl Repr for ast::ExplicitSelf_ {
795     fn repr(&self, _tcx: &ctxt) -> ~str {
796         format!("{:?}", *self)
797     }
798 }
799
800 impl Repr for ast::Visibility {
801     fn repr(&self, _tcx: &ctxt) -> ~str {
802         format!("{:?}", *self)
803     }
804 }
805
806 impl Repr for ty::BareFnTy {
807     fn repr(&self, tcx: &ctxt) -> ~str {
808         format!("BareFnTy \\{fn_style: {:?}, abi: {}, sig: {}\\}",
809              self.fn_style,
810              self.abi.to_str(),
811              self.sig.repr(tcx))
812     }
813 }
814
815 impl Repr for ty::FnSig {
816     fn repr(&self, tcx: &ctxt) -> ~str {
817         fn_sig_to_str(tcx, self)
818     }
819 }
820
821 impl Repr for typeck::MethodCallee {
822     fn repr(&self, tcx: &ctxt) -> ~str {
823         format!("MethodCallee \\{origin: {}, ty: {}, {}\\}",
824             self.origin.repr(tcx),
825             self.ty.repr(tcx),
826             self.substs.repr(tcx))
827     }
828 }
829
830 impl Repr for typeck::MethodOrigin {
831     fn repr(&self, tcx: &ctxt) -> ~str {
832         match self {
833             &typeck::MethodStatic(def_id) => {
834                 format!("MethodStatic({})", def_id.repr(tcx))
835             }
836             &typeck::MethodParam(ref p) => {
837                 p.repr(tcx)
838             }
839             &typeck::MethodObject(ref p) => {
840                 p.repr(tcx)
841             }
842         }
843     }
844 }
845
846 impl Repr for typeck::MethodParam {
847     fn repr(&self, tcx: &ctxt) -> ~str {
848         format!("MethodParam({},{:?},{:?},{:?})",
849              self.trait_id.repr(tcx),
850              self.method_num,
851              self.param_num,
852              self.bound_num)
853     }
854 }
855
856 impl Repr for typeck::MethodObject {
857     fn repr(&self, tcx: &ctxt) -> ~str {
858         format!("MethodObject({},{:?},{:?})",
859              self.trait_id.repr(tcx),
860              self.method_num,
861              self.real_index)
862     }
863 }
864
865
866 impl Repr for ty::RegionVid {
867     fn repr(&self, _tcx: &ctxt) -> ~str {
868         format!("{:?}", *self)
869     }
870 }
871
872 impl Repr for ty::TraitStore {
873     fn repr(&self, tcx: &ctxt) -> ~str {
874         trait_store_to_str(tcx, *self)
875     }
876 }
877
878 impl Repr for ty::Vstore {
879     fn repr(&self, tcx: &ctxt) -> ~str {
880         match *self {
881             ty::VstoreFixed(n) => format!("{}", n),
882             ty::VstoreUniq => ~"~",
883             ty::VstoreSlice(r, m) => {
884                 format!("{}{}", region_ptr_to_str(tcx, r), mutability_to_str(m))
885             }
886         }
887     }
888 }
889
890 impl Repr for ty::Vstore<()> {
891     fn repr(&self, tcx: &ctxt) -> ~str {
892         match *self {
893             ty::VstoreFixed(n) => format!("{}", n),
894             ty::VstoreUniq => ~"~",
895             ty::VstoreSlice(r, ()) => region_ptr_to_str(tcx, r)
896         }
897     }
898 }
899
900 impl Repr for ty::BuiltinBound {
901     fn repr(&self, _tcx: &ctxt) -> ~str {
902         format!("{:?}", *self)
903     }
904 }
905
906 impl UserString for ty::BuiltinBound {
907     fn user_string(&self, _tcx: &ctxt) -> ~str {
908         match *self {
909             ty::BoundStatic => ~"'static",
910             ty::BoundSend => ~"Send",
911             ty::BoundSized => ~"Sized",
912             ty::BoundCopy => ~"Pod",
913             ty::BoundShare => ~"Share",
914         }
915     }
916 }
917
918 impl Repr for ty::BuiltinBounds {
919     fn repr(&self, tcx: &ctxt) -> ~str {
920         self.user_string(tcx)
921     }
922 }
923
924 impl Repr for Span {
925     fn repr(&self, tcx: &ctxt) -> ~str {
926         tcx.sess.codemap().span_to_str(*self)
927     }
928 }
929
930 impl<A:UserString> UserString for @A {
931     fn user_string(&self, tcx: &ctxt) -> ~str {
932         let this: &A = &**self;
933         this.user_string(tcx)
934     }
935 }
936
937 impl UserString for ty::BuiltinBounds {
938     fn user_string(&self, tcx: &ctxt) -> ~str {
939         if self.is_empty() { ~"<no-bounds>" } else {
940             let mut result = Vec::new();
941             for bb in self.iter() {
942                 result.push(bb.user_string(tcx));
943             }
944             result.connect("+")
945         }
946     }
947 }
948
949 impl UserString for ty::TraitRef {
950     fn user_string(&self, tcx: &ctxt) -> ~str {
951         let base = ty::item_path_str(tcx, self.def_id);
952         if tcx.sess.verbose() && self.substs.self_ty.is_some() {
953             let mut all_tps = self.substs.tps.clone();
954             for &t in self.substs.self_ty.iter() { all_tps.push(t); }
955             parameterized(tcx, base, &self.substs.regions,
956                           all_tps.as_slice(), self.def_id, true)
957         } else {
958             parameterized(tcx, base, &self.substs.regions,
959                           self.substs.tps.as_slice(), self.def_id, true)
960         }
961     }
962 }
963
964 impl UserString for ty::t {
965     fn user_string(&self, tcx: &ctxt) -> ~str {
966         ty_to_str(tcx, *self)
967     }
968 }
969
970 impl UserString for ast::Ident {
971     fn user_string(&self, _tcx: &ctxt) -> ~str {
972         token::get_name(self.name).get().to_owned()
973     }
974 }
975
976 impl Repr for abi::Abi {
977     fn repr(&self, _tcx: &ctxt) -> ~str {
978         self.to_str()
979     }
980 }
981
982 impl UserString for abi::Abi {
983     fn user_string(&self, _tcx: &ctxt) -> ~str {
984         self.to_str()
985     }
986 }
987
988 impl Repr for ty::UpvarId {
989     fn repr(&self, tcx: &ctxt) -> ~str {
990         format!("UpvarId({};`{}`;{})",
991              self.var_id,
992              ty::local_var_name_str(tcx, self.var_id),
993              self.closure_expr_id)
994     }
995 }
996
997 impl Repr for ast::Mutability {
998     fn repr(&self, _tcx: &ctxt) -> ~str {
999         format!("{:?}", *self)
1000     }
1001 }
1002
1003 impl Repr for ty::BorrowKind {
1004     fn repr(&self, _tcx: &ctxt) -> ~str {
1005         format!("{:?}", *self)
1006     }
1007 }
1008
1009 impl Repr for ty::UpvarBorrow {
1010     fn repr(&self, tcx: &ctxt) -> ~str {
1011         format!("UpvarBorrow({}, {})",
1012              self.kind.repr(tcx),
1013              self.region.repr(tcx))
1014     }
1015 }