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