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