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