]> git.lizzy.rs Git - rust.git/blob - src/librustc/util/ppaux.rs
rollup merge of #18407 : thestinger/arena
[rust.git] / src / librustc / util / ppaux.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11
12 use middle::def;
13 use middle::subst::{VecPerParamSpace,Subst};
14 use middle::subst;
15 use middle::ty::{BoundRegion, BrAnon, BrNamed};
16 use middle::ty::{ReEarlyBound, BrFresh, ctxt};
17 use middle::ty::{ReFree, ReScope, ReInfer, ReStatic, Region, ReEmpty};
18 use middle::ty::{ReSkolemized, ReVar, BrEnv};
19 use middle::ty::{mt, t, ParamTy};
20 use middle::ty::{ty_bool, ty_char, ty_struct, ty_enum};
21 use middle::ty::{ty_err, ty_str, ty_vec, ty_float, ty_bare_fn, ty_closure};
22 use middle::ty::{ty_nil, ty_param, ty_ptr, ty_rptr, ty_tup, ty_open};
23 use middle::ty::{ty_unboxed_closure};
24 use middle::ty::{ty_uniq, ty_trait, ty_int, ty_uint, ty_infer};
25 use middle::ty;
26 use middle::typeck;
27 use middle::typeck::check::regionmanip;
28
29 use std::rc::Rc;
30 use syntax::abi;
31 use syntax::ast_map;
32 use syntax::codemap::{Span, Pos};
33 use syntax::parse::token;
34 use syntax::print::pprust;
35 use syntax::{ast, ast_util};
36 use syntax::owned_slice::OwnedSlice;
37
38 /// Produces a string suitable for debugging output.
39 pub trait Repr {
40     fn repr(&self, tcx: &ctxt) -> String;
41 }
42
43 /// Produces a string suitable for showing to the user.
44 pub trait UserString {
45     fn user_string(&self, tcx: &ctxt) -> String;
46 }
47
48 pub fn note_and_explain_region(cx: &ctxt,
49                                prefix: &str,
50                                region: ty::Region,
51                                suffix: &str) {
52     match explain_region_and_span(cx, region) {
53       (ref str, Some(span)) => {
54         cx.sess.span_note(
55             span,
56             format!("{}{}{}", prefix, *str, suffix).as_slice());
57       }
58       (ref str, None) => {
59         cx.sess.note(
60             format!("{}{}{}", prefix, *str, suffix).as_slice());
61       }
62     }
63 }
64
65 fn item_scope_tag(item: &ast::Item) -> &'static str {
66     /*!
67      * When a free region is associated with `item`, how should we describe
68      * the item in the error message.
69      */
70
71     match item.node {
72         ast::ItemImpl(..) => "impl",
73         ast::ItemStruct(..) => "struct",
74         ast::ItemEnum(..) => "enum",
75         ast::ItemTrait(..) => "trait",
76         ast::ItemFn(..) => "function body",
77         _ => "item"
78     }
79 }
80
81 pub fn explain_region_and_span(cx: &ctxt, region: ty::Region)
82                             -> (String, Option<Span>) {
83     return match region {
84       ReScope(node_id) => {
85         match cx.map.find(node_id) {
86           Some(ast_map::NodeBlock(ref blk)) => {
87             explain_span(cx, "block", blk.span)
88           }
89           Some(ast_map::NodeExpr(expr)) => {
90             match expr.node {
91               ast::ExprCall(..) => explain_span(cx, "call", expr.span),
92               ast::ExprMethodCall(..) => {
93                 explain_span(cx, "method call", expr.span)
94               },
95               ast::ExprMatch(_, _, ast::MatchIfLetDesugar) => explain_span(cx, "if let", expr.span),
96               ast::ExprMatch(_, _, ast::MatchWhileLetDesugar) => {
97                   explain_span(cx, "while let", expr.span)
98               },
99               ast::ExprMatch(..) => explain_span(cx, "match", expr.span),
100               _ => explain_span(cx, "expression", expr.span)
101             }
102           }
103           Some(ast_map::NodeStmt(stmt)) => {
104               explain_span(cx, "statement", stmt.span)
105           }
106           Some(ast_map::NodeItem(it)) => {
107               let tag = item_scope_tag(&*it);
108               explain_span(cx, tag, it.span)
109           }
110           Some(_) | None => {
111             // this really should not happen
112             (format!("unknown scope: {}.  Please report a bug.", node_id), None)
113           }
114         }
115       }
116
117       ReFree(ref fr) => {
118         let prefix = match fr.bound_region {
119           BrAnon(idx) => {
120               format!("the anonymous lifetime #{} defined on", idx + 1)
121           }
122           BrFresh(_) => "an anonymous lifetime defined on".to_string(),
123           _ => {
124               format!("the lifetime {} as defined on",
125                       bound_region_ptr_to_string(cx, fr.bound_region))
126           }
127         };
128
129         match cx.map.find(fr.scope_id) {
130           Some(ast_map::NodeBlock(ref blk)) => {
131               let (msg, opt_span) = explain_span(cx, "block", blk.span);
132               (format!("{} {}", prefix, msg), opt_span)
133           }
134           Some(ast_map::NodeItem(it)) => {
135               let tag = item_scope_tag(&*it);
136               let (msg, opt_span) = explain_span(cx, tag, it.span);
137               (format!("{} {}", prefix, msg), opt_span)
138           }
139           Some(_) | None => {
140               // this really should not happen
141               (format!("{} node {}", prefix, fr.scope_id), None)
142           }
143         }
144       }
145
146       ReStatic => { ("the static lifetime".to_string(), None) }
147
148       ReEmpty => { ("the empty lifetime".to_string(), None) }
149
150       ReEarlyBound(_, _, _, name) => {
151         (format!("{}", token::get_name(name)), None)
152       }
153
154       // I believe these cases should not occur (except when debugging,
155       // perhaps)
156       ty::ReInfer(_) | ty::ReLateBound(..) => {
157         (format!("lifetime {}", region), None)
158       }
159     };
160
161     fn explain_span(cx: &ctxt, heading: &str, span: Span)
162                     -> (String, Option<Span>) {
163         let lo = cx.sess.codemap().lookup_char_pos_adj(span.lo);
164         (format!("the {} at {}:{}", heading, lo.line, lo.col.to_uint()),
165          Some(span))
166     }
167 }
168
169 pub fn bound_region_ptr_to_string(cx: &ctxt, br: BoundRegion) -> String {
170     bound_region_to_string(cx, "", false, br)
171 }
172
173 pub fn bound_region_to_string(cx: &ctxt,
174                            prefix: &str, space: bool,
175                            br: BoundRegion) -> String {
176     let space_str = if space { " " } else { "" };
177
178     if cx.sess.verbose() {
179         return format!("{}{}{}", prefix, br.repr(cx), space_str)
180     }
181
182     match br {
183         BrNamed(_, name) => {
184             format!("{}{}{}", prefix, token::get_name(name), space_str)
185         }
186         BrAnon(_) | BrFresh(_) | BrEnv => prefix.to_string()
187     }
188 }
189
190 // In general, if you are giving a region error message,
191 // you should use `explain_region()` or, better yet,
192 // `note_and_explain_region()`
193 pub fn region_ptr_to_string(cx: &ctxt, region: Region) -> String {
194     region_to_string(cx, "&", true, region)
195 }
196
197 pub fn region_to_string(cx: &ctxt, prefix: &str, space: bool, region: Region) -> String {
198     let space_str = if space { " " } else { "" };
199
200     if cx.sess.verbose() {
201         return format!("{}{}{}", prefix, region.repr(cx), space_str)
202     }
203
204     // These printouts are concise.  They do not contain all the information
205     // the user might want to diagnose an error, but there is basically no way
206     // to fit that into a short string.  Hence the recommendation to use
207     // `explain_region()` or `note_and_explain_region()`.
208     match region {
209         ty::ReScope(_) => prefix.to_string(),
210         ty::ReEarlyBound(_, _, _, name) => {
211             token::get_name(name).get().to_string()
212         }
213         ty::ReLateBound(_, br) => bound_region_to_string(cx, prefix, space, br),
214         ty::ReFree(ref fr) => bound_region_to_string(cx, prefix, space, fr.bound_region),
215         ty::ReInfer(ReSkolemized(_, br)) => {
216             bound_region_to_string(cx, prefix, space, br)
217         }
218         ty::ReInfer(ReVar(_)) => prefix.to_string(),
219         ty::ReStatic => format!("{}'static{}", prefix, space_str),
220         ty::ReEmpty => format!("{}'<empty>{}", prefix, space_str),
221     }
222 }
223
224 pub fn mutability_to_string(m: ast::Mutability) -> String {
225     match m {
226         ast::MutMutable => "mut ".to_string(),
227         ast::MutImmutable => "".to_string(),
228     }
229 }
230
231 pub fn mt_to_string(cx: &ctxt, m: &mt) -> String {
232     format!("{}{}", mutability_to_string(m.mutbl), ty_to_string(cx, m.ty))
233 }
234
235 pub fn trait_store_to_string(cx: &ctxt, s: ty::TraitStore) -> String {
236     match s {
237         ty::UniqTraitStore => "Box ".to_string(),
238         ty::RegionTraitStore(r, m) => {
239             format!("{}{}", region_ptr_to_string(cx, r), mutability_to_string(m))
240         }
241     }
242 }
243
244 pub fn vec_map_to_string<T>(ts: &[T], f: |t: &T| -> String) -> String {
245     let tstrs = ts.iter().map(f).collect::<Vec<String>>();
246     format!("[{}]", tstrs.connect(", "))
247 }
248
249 pub fn fn_sig_to_string(cx: &ctxt, typ: &ty::FnSig) -> String {
250     format!("fn{}{} -> {}", typ.binder_id, typ.inputs.repr(cx),
251             typ.output.repr(cx))
252 }
253
254 pub fn trait_ref_to_string(cx: &ctxt, trait_ref: &ty::TraitRef) -> String {
255     trait_ref.user_string(cx).to_string()
256 }
257
258 pub fn ty_to_string(cx: &ctxt, typ: t) -> String {
259     fn fn_input_to_string(cx: &ctxt, input: ty::t) -> String {
260         ty_to_string(cx, input).to_string()
261     }
262     fn bare_fn_to_string(cx: &ctxt,
263                       fn_style: ast::FnStyle,
264                       abi: abi::Abi,
265                       ident: Option<ast::Ident>,
266                       sig: &ty::FnSig)
267                       -> String {
268         let mut s = String::new();
269         match fn_style {
270             ast::NormalFn => {}
271             _ => {
272                 s.push_str(fn_style.to_string().as_slice());
273                 s.push(' ');
274             }
275         };
276
277         if abi != abi::Rust {
278             s.push_str(format!("extern {} ", abi.to_string()).as_slice());
279         };
280
281         s.push_str("fn");
282
283         match ident {
284             Some(i) => {
285                 s.push(' ');
286                 s.push_str(token::get_ident(i).get());
287             }
288             _ => { }
289         }
290
291         push_sig_to_string(cx, &mut s, '(', ')', sig, "");
292
293         s
294     }
295
296     fn closure_to_string(cx: &ctxt, cty: &ty::ClosureTy) -> String {
297         let mut s = String::new();
298
299         match cty.store {
300             ty::UniqTraitStore => {}
301             ty::RegionTraitStore(region, _) => {
302                 s.push_str(region_to_string(cx, "", true, region).as_slice());
303             }
304         }
305
306         match cty.fn_style {
307             ast::NormalFn => {}
308             _ => {
309                 s.push_str(cty.fn_style.to_string().as_slice());
310                 s.push(' ');
311             }
312         };
313
314         let bounds_str = cty.bounds.user_string(cx);
315
316         match cty.store {
317             ty::UniqTraitStore => {
318                 assert_eq!(cty.onceness, ast::Once);
319                 s.push_str("proc");
320                 push_sig_to_string(cx, &mut s, '(', ')', &cty.sig,
321                                    bounds_str.as_slice());
322             }
323             ty::RegionTraitStore(..) => {
324                 match cty.onceness {
325                     ast::Many => {}
326                     ast::Once => s.push_str("once ")
327                 }
328                 push_sig_to_string(cx, &mut s, '|', '|', &cty.sig,
329                                    bounds_str.as_slice());
330             }
331         }
332
333         s
334     }
335
336     fn push_sig_to_string(cx: &ctxt,
337                        s: &mut String,
338                        bra: char,
339                        ket: char,
340                        sig: &ty::FnSig,
341                        bounds: &str) {
342         s.push(bra);
343         let strs: Vec<String> = sig.inputs.iter().map(|a| fn_input_to_string(cx, *a)).collect();
344         s.push_str(strs.connect(", ").as_slice());
345         if sig.variadic {
346             s.push_str(", ...");
347         }
348         s.push(ket);
349
350         if !bounds.is_empty() {
351             s.push_str(":");
352             s.push_str(bounds);
353         }
354
355         match sig.output {
356             ty::FnConverging(t) => {
357                 if !ty::type_is_nil(t) {
358                     s.push_str(" -> ");
359                    s.push_str(ty_to_string(cx, t).as_slice());
360                 }
361             }
362             ty::FnDiverging => {
363                 s.push_str(" -> !");
364             }
365         }
366     }
367
368     // if there is an id, print that instead of the structural type:
369     /*for def_id in ty::type_def_id(typ).iter() {
370         // note that this typedef cannot have type parameters
371         return ty::item_path_str(cx, *def_id);
372     }*/
373
374     // pretty print the structural type representation:
375     return match ty::get(typ).sty {
376       ty_nil => "()".to_string(),
377       ty_bool => "bool".to_string(),
378       ty_char => "char".to_string(),
379       ty_int(t) => ast_util::int_ty_to_string(t, None).to_string(),
380       ty_uint(t) => ast_util::uint_ty_to_string(t, None).to_string(),
381       ty_float(t) => ast_util::float_ty_to_string(t).to_string(),
382       ty_uniq(typ) => format!("Box<{}>", ty_to_string(cx, typ)),
383       ty_ptr(ref tm) => {
384           format!("*{} {}", match tm.mutbl {
385               ast::MutMutable => "mut",
386               ast::MutImmutable => "const",
387           }, ty_to_string(cx, tm.ty))
388       }
389       ty_rptr(r, ref tm) => {
390           let mut buf = region_ptr_to_string(cx, r);
391           buf.push_str(mt_to_string(cx, tm).as_slice());
392           buf
393       }
394       ty_open(typ) => format!("opened<{}>", ty_to_string(cx, typ)),
395       ty_tup(ref elems) => {
396         let strs: Vec<String> = elems.iter().map(|elem| ty_to_string(cx, *elem)).collect();
397         format!("({})", strs.connect(","))
398       }
399       ty_closure(ref f) => {
400           closure_to_string(cx, &**f)
401       }
402       ty_bare_fn(ref f) => {
403           bare_fn_to_string(cx, f.fn_style, f.abi, None, &f.sig)
404       }
405       ty_infer(infer_ty) => infer_ty.to_string(),
406       ty_err => "[type error]".to_string(),
407       ty_param(ref param_ty) => {
408           param_ty.repr(cx)
409       }
410       ty_enum(did, ref substs) | ty_struct(did, ref substs) => {
411           let base = ty::item_path_str(cx, did);
412           let generics = ty::lookup_item_type(cx, did).generics;
413           parameterized(cx, base.as_slice(), substs, &generics)
414       }
415       ty_trait(box ty::TyTrait {
416           def_id: did, ref substs, ref bounds
417       }) => {
418           let base = ty::item_path_str(cx, did);
419           let trait_def = ty::lookup_trait_def(cx, did);
420           let ty = parameterized(cx, base.as_slice(),
421                                  substs, &trait_def.generics);
422           let bound_str = bounds.user_string(cx);
423           let bound_sep = if bound_str.is_empty() { "" } else { "+" };
424           format!("{}{}{}",
425                   ty,
426                   bound_sep,
427                   bound_str)
428       }
429       ty_str => "str".to_string(),
430       ty_unboxed_closure(ref did, _, ref substs) => {
431           let unboxed_closures = cx.unboxed_closures.borrow();
432           unboxed_closures.find(did).map(|cl| {
433               closure_to_string(cx, &cl.closure_type.subst(cx, substs))
434           }).unwrap_or_else(|| "closure".to_string())
435       }
436       ty_vec(t, sz) => {
437           match sz {
438               Some(n) => {
439                   format!("[{}, ..{}]", ty_to_string(cx, t), n)
440               }
441               None => format!("[{}]", ty_to_string(cx, t)),
442           }
443       }
444     }
445 }
446
447 pub fn explicit_self_category_to_str(category: &ty::ExplicitSelfCategory)
448                                      -> &'static str {
449     match *category {
450         ty::StaticExplicitSelfCategory => "static",
451         ty::ByValueExplicitSelfCategory => "self",
452         ty::ByReferenceExplicitSelfCategory(_, ast::MutMutable) => {
453             "&mut self"
454         }
455         ty::ByReferenceExplicitSelfCategory(_, ast::MutImmutable) => "&self",
456         ty::ByBoxExplicitSelfCategory => "Box<self>",
457     }
458 }
459
460 pub fn parameterized(cx: &ctxt,
461                      base: &str,
462                      substs: &subst::Substs,
463                      generics: &ty::Generics)
464                      -> String
465 {
466     let mut strs = Vec::new();
467
468     match substs.regions {
469         subst::ErasedRegions => { }
470         subst::NonerasedRegions(ref regions) => {
471             for &r in regions.iter() {
472                 let s = region_to_string(cx, "", false, r);
473                 if !s.is_empty() {
474                     strs.push(s)
475                 } else {
476                     // This happens when the value of the region
477                     // parameter is not easily serialized. This may be
478                     // because the user omitted it in the first place,
479                     // or because it refers to some block in the code,
480                     // etc. I'm not sure how best to serialize this.
481                     strs.push(format!("'_"));
482                 }
483             }
484         }
485     }
486
487     let tps = substs.types.get_slice(subst::TypeSpace);
488     let ty_params = generics.types.get_slice(subst::TypeSpace);
489     let has_defaults = ty_params.last().map_or(false, |def| def.default.is_some());
490     let num_defaults = if has_defaults && !cx.sess.verbose() {
491         ty_params.iter().zip(tps.iter()).rev().take_while(|&(def, &actual)| {
492             match def.default {
493                 Some(default) => default.subst(cx, substs) == actual,
494                 None => false
495             }
496         }).count()
497     } else {
498         0
499     };
500
501     for t in tps[..tps.len() - num_defaults].iter() {
502         strs.push(ty_to_string(cx, *t))
503     }
504
505     if cx.sess.verbose() {
506         for t in substs.types.get_slice(subst::SelfSpace).iter() {
507             strs.push(format!("self {}", t.repr(cx)));
508         }
509
510         // generally there shouldn't be any substs in the fn param
511         // space, but in verbose mode, print them out.
512         for t in substs.types.get_slice(subst::FnSpace).iter() {
513             strs.push(format!("fn {}", t.repr(cx)));
514         }
515     }
516
517     if strs.len() > 0u {
518         format!("{}<{}>", base, strs.connect(","))
519     } else {
520         format!("{}", base)
521     }
522 }
523
524 pub fn ty_to_short_str(cx: &ctxt, typ: t) -> String {
525     let mut s = typ.repr(cx).to_string();
526     if s.len() >= 32u {
527         s = s.as_slice().slice(0u, 32u).to_string();
528     }
529     return s;
530 }
531
532 impl<T:Repr> Repr for Option<T> {
533     fn repr(&self, tcx: &ctxt) -> String {
534         match self {
535             &None => "None".to_string(),
536             &Some(ref t) => t.repr(tcx),
537         }
538     }
539 }
540
541 impl<T:Repr,U:Repr> Repr for Result<T,U> {
542     fn repr(&self, tcx: &ctxt) -> String {
543         match self {
544             &Ok(ref t) => t.repr(tcx),
545             &Err(ref u) => format!("Err({})", u.repr(tcx))
546         }
547     }
548 }
549
550 impl Repr for () {
551     fn repr(&self, _tcx: &ctxt) -> String {
552         "()".to_string()
553     }
554 }
555
556 impl<'a,T:Repr> Repr for &'a T {
557     fn repr(&self, tcx: &ctxt) -> String {
558         (&**self).repr(tcx)
559     }
560 }
561
562 impl<T:Repr> Repr for Rc<T> {
563     fn repr(&self, tcx: &ctxt) -> String {
564         (&**self).repr(tcx)
565     }
566 }
567
568 impl<T:Repr> Repr for Box<T> {
569     fn repr(&self, tcx: &ctxt) -> String {
570         (&**self).repr(tcx)
571     }
572 }
573
574 fn repr_vec<T:Repr>(tcx: &ctxt, v: &[T]) -> String {
575     vec_map_to_string(v, |t| t.repr(tcx))
576 }
577
578 impl<'a, T:Repr> Repr for &'a [T] {
579     fn repr(&self, tcx: &ctxt) -> String {
580         repr_vec(tcx, *self)
581     }
582 }
583
584 impl<T:Repr> Repr for OwnedSlice<T> {
585     fn repr(&self, tcx: &ctxt) -> String {
586         repr_vec(tcx, self.as_slice())
587     }
588 }
589
590 // This is necessary to handle types like Option<~[T]>, for which
591 // autoderef cannot convert the &[T] handler
592 impl<T:Repr> Repr for Vec<T> {
593     fn repr(&self, tcx: &ctxt) -> String {
594         repr_vec(tcx, self.as_slice())
595     }
596 }
597
598 impl<T:UserString> UserString for Vec<T> {
599     fn user_string(&self, tcx: &ctxt) -> String {
600         let strs: Vec<String> =
601             self.iter().map(|t| t.user_string(tcx)).collect();
602         strs.connect(", ")
603     }
604 }
605
606 impl Repr for def::Def {
607     fn repr(&self, _tcx: &ctxt) -> String {
608         format!("{}", *self)
609     }
610 }
611
612 impl Repr for ty::TypeParameterDef {
613     fn repr(&self, tcx: &ctxt) -> String {
614         format!("TypeParameterDef({}, {}, {}/{})",
615                 self.def_id,
616                 self.bounds.repr(tcx),
617                 self.space,
618                 self.index)
619     }
620 }
621
622 impl Repr for ty::RegionParameterDef {
623     fn repr(&self, tcx: &ctxt) -> String {
624         format!("RegionParameterDef(name={}, def_id={}, bounds={})",
625                 token::get_name(self.name),
626                 self.def_id.repr(tcx),
627                 self.bounds.repr(tcx))
628     }
629 }
630
631 impl Repr for ty::t {
632     fn repr(&self, tcx: &ctxt) -> String {
633         ty_to_string(tcx, *self)
634     }
635 }
636
637 impl Repr for ty::mt {
638     fn repr(&self, tcx: &ctxt) -> String {
639         mt_to_string(tcx, self)
640     }
641 }
642
643 impl Repr for subst::Substs {
644     fn repr(&self, tcx: &ctxt) -> String {
645         format!("Substs[types={}, regions={}]",
646                        self.types.repr(tcx),
647                        self.regions.repr(tcx))
648     }
649 }
650
651 impl<T:Repr> Repr for subst::VecPerParamSpace<T> {
652     fn repr(&self, tcx: &ctxt) -> String {
653         format!("[{};{};{}]",
654                        self.get_slice(subst::TypeSpace).repr(tcx),
655                        self.get_slice(subst::SelfSpace).repr(tcx),
656                        self.get_slice(subst::FnSpace).repr(tcx))
657     }
658 }
659
660 impl Repr for ty::ItemSubsts {
661     fn repr(&self, tcx: &ctxt) -> String {
662         format!("ItemSubsts({})", self.substs.repr(tcx))
663     }
664 }
665
666 impl Repr for subst::RegionSubsts {
667     fn repr(&self, tcx: &ctxt) -> String {
668         match *self {
669             subst::ErasedRegions => "erased".to_string(),
670             subst::NonerasedRegions(ref regions) => regions.repr(tcx)
671         }
672     }
673 }
674
675 impl Repr for ty::BuiltinBounds {
676     fn repr(&self, _tcx: &ctxt) -> String {
677         let mut res = Vec::new();
678         for b in self.iter() {
679             res.push(match b {
680                 ty::BoundSend => "Send".to_string(),
681                 ty::BoundSized => "Sized".to_string(),
682                 ty::BoundCopy => "Copy".to_string(),
683                 ty::BoundSync => "Sync".to_string(),
684             });
685         }
686         res.connect("+")
687     }
688 }
689
690 impl Repr for ty::ExistentialBounds {
691     fn repr(&self, tcx: &ctxt) -> String {
692         self.user_string(tcx)
693     }
694 }
695
696 impl Repr for ty::ParamBounds {
697     fn repr(&self, tcx: &ctxt) -> String {
698         let mut res = Vec::new();
699         res.push(self.builtin_bounds.repr(tcx));
700         for t in self.trait_bounds.iter() {
701             res.push(t.repr(tcx));
702         }
703         res.connect("+")
704     }
705 }
706
707 impl Repr for ty::TraitRef {
708     fn repr(&self, tcx: &ctxt) -> String {
709         let base = ty::item_path_str(tcx, self.def_id);
710         let trait_def = ty::lookup_trait_def(tcx, self.def_id);
711         format!("<{} as {}>",
712                 self.substs.self_ty().repr(tcx),
713                 parameterized(tcx, base.as_slice(), &self.substs, &trait_def.generics))
714     }
715 }
716
717 impl Repr for ty::TraitDef {
718     fn repr(&self, tcx: &ctxt) -> String {
719         format!("TraitDef(generics={}, bounds={}, trait_ref={})",
720                 self.generics.repr(tcx),
721                 self.bounds.repr(tcx),
722                 self.trait_ref.repr(tcx))
723     }
724 }
725
726 impl Repr for ast::Expr {
727     fn repr(&self, _tcx: &ctxt) -> String {
728         format!("expr({}: {})", self.id, pprust::expr_to_string(self))
729     }
730 }
731
732 impl Repr for ast::Path {
733     fn repr(&self, _tcx: &ctxt) -> String {
734         format!("path({})", pprust::path_to_string(self))
735     }
736 }
737
738 impl UserString for ast::Path {
739     fn user_string(&self, _tcx: &ctxt) -> String {
740         pprust::path_to_string(self)
741     }
742 }
743
744 impl Repr for ast::Item {
745     fn repr(&self, tcx: &ctxt) -> String {
746         format!("item({})", tcx.map.node_to_string(self.id))
747     }
748 }
749
750 impl Repr for ast::Lifetime {
751     fn repr(&self, _tcx: &ctxt) -> String {
752         format!("lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
753     }
754 }
755
756 impl Repr for ast::Stmt {
757     fn repr(&self, _tcx: &ctxt) -> String {
758         format!("stmt({}: {})",
759                 ast_util::stmt_id(self),
760                 pprust::stmt_to_string(self))
761     }
762 }
763
764 impl Repr for ast::Pat {
765     fn repr(&self, _tcx: &ctxt) -> String {
766         format!("pat({}: {})", self.id, pprust::pat_to_string(self))
767     }
768 }
769
770 impl Repr for ty::BoundRegion {
771     fn repr(&self, tcx: &ctxt) -> String {
772         match *self {
773             ty::BrAnon(id) => format!("BrAnon({})", id),
774             ty::BrNamed(id, name) => {
775                 format!("BrNamed({}, {})", id.repr(tcx), token::get_name(name))
776             }
777             ty::BrFresh(id) => format!("BrFresh({})", id),
778             ty::BrEnv => "BrEnv".to_string()
779         }
780     }
781 }
782
783 impl Repr for ty::Region {
784     fn repr(&self, tcx: &ctxt) -> String {
785         match *self {
786             ty::ReEarlyBound(id, space, index, name) => {
787                 format!("ReEarlyBound({}, {}, {}, {})",
788                                id,
789                                space,
790                                index,
791                                token::get_name(name))
792             }
793
794             ty::ReLateBound(binder_id, ref bound_region) => {
795                 format!("ReLateBound({}, {})",
796                         binder_id,
797                         bound_region.repr(tcx))
798             }
799
800             ty::ReFree(ref fr) => fr.repr(tcx),
801
802             ty::ReScope(id) => {
803                 format!("ReScope({})", id)
804             }
805
806             ty::ReStatic => {
807                 "ReStatic".to_string()
808             }
809
810             ty::ReInfer(ReVar(ref vid)) => {
811                 format!("ReInfer({})", vid.index)
812             }
813
814             ty::ReInfer(ReSkolemized(id, ref bound_region)) => {
815                 format!("re_skolemized({}, {})", id, bound_region.repr(tcx))
816             }
817
818             ty::ReEmpty => {
819                 "ReEmpty".to_string()
820             }
821         }
822     }
823 }
824
825 impl UserString for ty::Region {
826     fn user_string(&self, tcx: &ctxt) -> String {
827         region_to_string(tcx, "", false, *self)
828     }
829 }
830
831 impl Repr for ty::FreeRegion {
832     fn repr(&self, tcx: &ctxt) -> String {
833         format!("ReFree({}, {})",
834                 self.scope_id,
835                 self.bound_region.repr(tcx))
836     }
837 }
838
839 impl Repr for ast::DefId {
840     fn repr(&self, tcx: &ctxt) -> String {
841         // Unfortunately, there seems to be no way to attempt to print
842         // a path for a def-id, so I'll just make a best effort for now
843         // and otherwise fallback to just printing the crate/node pair
844         if self.krate == ast::LOCAL_CRATE {
845             match tcx.map.find(self.node) {
846                 Some(ast_map::NodeItem(..)) |
847                 Some(ast_map::NodeForeignItem(..)) |
848                 Some(ast_map::NodeImplItem(..)) |
849                 Some(ast_map::NodeTraitItem(..)) |
850                 Some(ast_map::NodeVariant(..)) |
851                 Some(ast_map::NodeStructCtor(..)) => {
852                     return format!(
853                                 "{}:{}",
854                                 *self,
855                                 ty::item_path_str(tcx, *self))
856                 }
857                 _ => {}
858             }
859         }
860         return format!("{}", *self)
861     }
862 }
863
864 impl Repr for ty::Polytype {
865     fn repr(&self, tcx: &ctxt) -> String {
866         format!("Polytype {{generics: {}, ty: {}}}",
867                 self.generics.repr(tcx),
868                 self.ty.repr(tcx))
869     }
870 }
871
872 impl Repr for ty::Generics {
873     fn repr(&self, tcx: &ctxt) -> String {
874         format!("Generics(types: {}, regions: {})",
875                 self.types.repr(tcx),
876                 self.regions.repr(tcx))
877     }
878 }
879
880 impl Repr for ty::ItemVariances {
881     fn repr(&self, tcx: &ctxt) -> String {
882         format!("ItemVariances(types={}, \
883                 regions={})",
884                 self.types.repr(tcx),
885                 self.regions.repr(tcx))
886     }
887 }
888
889 impl Repr for ty::Variance {
890     fn repr(&self, _: &ctxt) -> String {
891         // The first `.to_string()` returns a &'static str (it is not an implementation
892         // of the ToString trait). Because of that, we need to call `.to_string()` again
893         // if we want to have a `String`.
894         let result: &'static str = (*self).to_string();
895         result.to_string()
896     }
897 }
898
899 impl Repr for ty::Method {
900     fn repr(&self, tcx: &ctxt) -> String {
901         format!("method(name: {}, generics: {}, fty: {}, \
902                  explicit_self: {}, vis: {}, def_id: {})",
903                 self.name.repr(tcx),
904                 self.generics.repr(tcx),
905                 self.fty.repr(tcx),
906                 self.explicit_self.repr(tcx),
907                 self.vis.repr(tcx),
908                 self.def_id.repr(tcx))
909     }
910 }
911
912 impl Repr for ast::Name {
913     fn repr(&self, _tcx: &ctxt) -> String {
914         token::get_name(*self).get().to_string()
915     }
916 }
917
918 impl UserString for ast::Name {
919     fn user_string(&self, _tcx: &ctxt) -> String {
920         token::get_name(*self).get().to_string()
921     }
922 }
923
924 impl Repr for ast::Ident {
925     fn repr(&self, _tcx: &ctxt) -> String {
926         token::get_ident(*self).get().to_string()
927     }
928 }
929
930 impl Repr for ast::ExplicitSelf_ {
931     fn repr(&self, _tcx: &ctxt) -> String {
932         format!("{}", *self)
933     }
934 }
935
936 impl Repr for ast::Visibility {
937     fn repr(&self, _tcx: &ctxt) -> String {
938         format!("{}", *self)
939     }
940 }
941
942 impl Repr for ty::BareFnTy {
943     fn repr(&self, tcx: &ctxt) -> String {
944         format!("BareFnTy {{fn_style: {}, abi: {}, sig: {}}}",
945                 self.fn_style,
946                 self.abi.to_string(),
947                 self.sig.repr(tcx))
948     }
949 }
950
951 impl Repr for ty::FnSig {
952     fn repr(&self, tcx: &ctxt) -> String {
953         fn_sig_to_string(tcx, self)
954     }
955 }
956
957 impl Repr for ty::FnOutput {
958     fn repr(&self, tcx: &ctxt) -> String {
959         match *self {
960             ty::FnConverging(ty) =>
961                 format!("FnConverging({0})", ty.repr(tcx)),
962             ty::FnDiverging =>
963                 "FnDiverging".to_string()
964         }
965     }
966 }
967
968 impl Repr for typeck::MethodCallee {
969     fn repr(&self, tcx: &ctxt) -> String {
970         format!("MethodCallee {{origin: {}, ty: {}, {}}}",
971                 self.origin.repr(tcx),
972                 self.ty.repr(tcx),
973                 self.substs.repr(tcx))
974     }
975 }
976
977 impl Repr for typeck::MethodOrigin {
978     fn repr(&self, tcx: &ctxt) -> String {
979         match self {
980             &typeck::MethodStatic(def_id) => {
981                 format!("MethodStatic({})", def_id.repr(tcx))
982             }
983             &typeck::MethodStaticUnboxedClosure(def_id) => {
984                 format!("MethodStaticUnboxedClosure({})", def_id.repr(tcx))
985             }
986             &typeck::MethodTypeParam(ref p) => {
987                 p.repr(tcx)
988             }
989             &typeck::MethodTraitObject(ref p) => {
990                 p.repr(tcx)
991             }
992         }
993     }
994 }
995
996 impl Repr for typeck::MethodParam {
997     fn repr(&self, tcx: &ctxt) -> String {
998         format!("MethodParam({},{})",
999                 self.trait_ref.repr(tcx),
1000                 self.method_num)
1001     }
1002 }
1003
1004 impl Repr for typeck::MethodObject {
1005     fn repr(&self, tcx: &ctxt) -> String {
1006         format!("MethodObject({},{},{})",
1007                 self.trait_ref.repr(tcx),
1008                 self.method_num,
1009                 self.real_index)
1010     }
1011 }
1012
1013 impl Repr for ty::TraitStore {
1014     fn repr(&self, tcx: &ctxt) -> String {
1015         trait_store_to_string(tcx, *self)
1016     }
1017 }
1018
1019 impl Repr for ty::BuiltinBound {
1020     fn repr(&self, _tcx: &ctxt) -> String {
1021         format!("{}", *self)
1022     }
1023 }
1024
1025 impl UserString for ty::BuiltinBound {
1026     fn user_string(&self, _tcx: &ctxt) -> String {
1027         match *self {
1028             ty::BoundSend => "Send".to_string(),
1029             ty::BoundSized => "Sized".to_string(),
1030             ty::BoundCopy => "Copy".to_string(),
1031             ty::BoundSync => "Sync".to_string(),
1032         }
1033     }
1034 }
1035
1036 impl Repr for Span {
1037     fn repr(&self, tcx: &ctxt) -> String {
1038         tcx.sess.codemap().span_to_string(*self).to_string()
1039     }
1040 }
1041
1042 impl<A:UserString> UserString for Rc<A> {
1043     fn user_string(&self, tcx: &ctxt) -> String {
1044         let this: &A = &**self;
1045         this.user_string(tcx)
1046     }
1047 }
1048
1049 impl UserString for ty::ParamBounds {
1050     fn user_string(&self, tcx: &ctxt) -> String {
1051         let mut result = Vec::new();
1052         let s = self.builtin_bounds.user_string(tcx);
1053         if !s.is_empty() {
1054             result.push(s);
1055         }
1056         for n in self.trait_bounds.iter() {
1057             result.push(n.user_string(tcx));
1058         }
1059         result.connect("+")
1060     }
1061 }
1062
1063 impl UserString for ty::ExistentialBounds {
1064     fn user_string(&self, tcx: &ctxt) -> String {
1065         if self.builtin_bounds.contains_elem(ty::BoundSend) &&
1066             self.region_bound == ty::ReStatic
1067         { // Region bound is implied by builtin bounds:
1068             return self.builtin_bounds.repr(tcx);
1069         }
1070
1071         let mut res = Vec::new();
1072
1073         let region_str = self.region_bound.user_string(tcx);
1074         if !region_str.is_empty() {
1075             res.push(region_str);
1076         }
1077
1078         for bound in self.builtin_bounds.iter() {
1079             res.push(bound.user_string(tcx));
1080         }
1081
1082         res.connect("+")
1083     }
1084 }
1085
1086 impl UserString for ty::BuiltinBounds {
1087     fn user_string(&self, tcx: &ctxt) -> String {
1088         self.iter()
1089             .map(|bb| bb.user_string(tcx))
1090             .collect::<Vec<String>>()
1091             .connect("+")
1092             .to_string()
1093     }
1094 }
1095
1096 impl UserString for ty::TraitRef {
1097     fn user_string(&self, tcx: &ctxt) -> String {
1098         let base = ty::item_path_str(tcx, self.def_id);
1099         let trait_def = ty::lookup_trait_def(tcx, self.def_id);
1100         parameterized(tcx, base.as_slice(), &self.substs, &trait_def.generics)
1101     }
1102 }
1103
1104 impl UserString for ty::t {
1105     fn user_string(&self, tcx: &ctxt) -> String {
1106         ty_to_string(tcx, *self)
1107     }
1108 }
1109
1110 impl UserString for ast::Ident {
1111     fn user_string(&self, _tcx: &ctxt) -> String {
1112         token::get_name(self.name).get().to_string()
1113     }
1114 }
1115
1116 impl Repr for abi::Abi {
1117     fn repr(&self, _tcx: &ctxt) -> String {
1118         self.to_string()
1119     }
1120 }
1121
1122 impl UserString for abi::Abi {
1123     fn user_string(&self, _tcx: &ctxt) -> String {
1124         self.to_string()
1125     }
1126 }
1127
1128 impl Repr for ty::UpvarId {
1129     fn repr(&self, tcx: &ctxt) -> String {
1130         format!("UpvarId({};`{}`;{})",
1131                 self.var_id,
1132                 ty::local_var_name_str(tcx, self.var_id),
1133                 self.closure_expr_id)
1134     }
1135 }
1136
1137 impl Repr for ast::Mutability {
1138     fn repr(&self, _tcx: &ctxt) -> String {
1139         format!("{}", *self)
1140     }
1141 }
1142
1143 impl Repr for ty::BorrowKind {
1144     fn repr(&self, _tcx: &ctxt) -> String {
1145         format!("{}", *self)
1146     }
1147 }
1148
1149 impl Repr for ty::UpvarBorrow {
1150     fn repr(&self, tcx: &ctxt) -> String {
1151         format!("UpvarBorrow({}, {})",
1152                 self.kind.repr(tcx),
1153                 self.region.repr(tcx))
1154     }
1155 }
1156
1157 impl Repr for ty::IntVid {
1158     fn repr(&self, _tcx: &ctxt) -> String {
1159         format!("{}", self)
1160     }
1161 }
1162
1163 impl Repr for ty::FloatVid {
1164     fn repr(&self, _tcx: &ctxt) -> String {
1165         format!("{}", self)
1166     }
1167 }
1168
1169 impl Repr for ty::RegionVid {
1170     fn repr(&self, _tcx: &ctxt) -> String {
1171         format!("{}", self)
1172     }
1173 }
1174
1175 impl Repr for ty::TyVid {
1176     fn repr(&self, _tcx: &ctxt) -> String {
1177         format!("{}", self)
1178     }
1179 }
1180
1181 impl Repr for ty::IntVarValue {
1182     fn repr(&self, _tcx: &ctxt) -> String {
1183         format!("{}", *self)
1184     }
1185 }
1186
1187 impl Repr for ast::IntTy {
1188     fn repr(&self, _tcx: &ctxt) -> String {
1189         format!("{}", *self)
1190     }
1191 }
1192
1193 impl Repr for ast::UintTy {
1194     fn repr(&self, _tcx: &ctxt) -> String {
1195         format!("{}", *self)
1196     }
1197 }
1198
1199 impl Repr for ast::FloatTy {
1200     fn repr(&self, _tcx: &ctxt) -> String {
1201         format!("{}", *self)
1202     }
1203 }
1204
1205 impl Repr for ty::ExplicitSelfCategory {
1206     fn repr(&self, _: &ctxt) -> String {
1207         explicit_self_category_to_str(self).to_string()
1208     }
1209 }
1210
1211
1212 impl Repr for regionmanip::WfConstraint {
1213     fn repr(&self, tcx: &ctxt) -> String {
1214         match *self {
1215             regionmanip::RegionSubRegionConstraint(_, r_a, r_b) => {
1216                 format!("RegionSubRegionConstraint({}, {})",
1217                         r_a.repr(tcx),
1218                         r_b.repr(tcx))
1219             }
1220
1221             regionmanip::RegionSubParamConstraint(_, r, p) => {
1222                 format!("RegionSubParamConstraint({}, {})",
1223                         r.repr(tcx),
1224                         p.repr(tcx))
1225             }
1226         }
1227     }
1228 }
1229
1230 impl UserString for ParamTy {
1231     fn user_string(&self, tcx: &ctxt) -> String {
1232         let id = self.idx;
1233         let did = self.def_id;
1234         let ident = match tcx.ty_param_defs.borrow().find(&did.node) {
1235             Some(def) => token::get_name(def.name).get().to_string(),
1236
1237             // This can only happen when a type mismatch error happens and
1238             // the actual type has more type parameters than the expected one.
1239             None => format!("<generic #{}>", id),
1240         };
1241         ident
1242     }
1243 }
1244
1245 impl Repr for ParamTy {
1246     fn repr(&self, tcx: &ctxt) -> String {
1247         self.user_string(tcx)
1248     }
1249 }
1250
1251 impl<A:Repr,B:Repr> Repr for (A,B) {
1252     fn repr(&self, tcx: &ctxt) -> String {
1253         let &(ref a, ref b) = self;
1254         format!("({},{})", a.repr(tcx), b.repr(tcx))
1255     }
1256 }
1257