]> git.lizzy.rs Git - rust.git/blob - src/librustc/util/ppaux.rs
return &mut T from the arenas, not &T
[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_bot, 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         if ty::get(sig.output).sty != ty_nil {
356             s.push_str(" -> ");
357             if ty::type_is_bot(sig.output) {
358                 s.push('!');
359             } else {
360                 s.push_str(ty_to_string(cx, sig.output).as_slice());
361             }
362         }
363     }
364
365     // if there is an id, print that instead of the structural type:
366     /*for def_id in ty::type_def_id(typ).iter() {
367         // note that this typedef cannot have type parameters
368         return ty::item_path_str(cx, *def_id);
369     }*/
370
371     // pretty print the structural type representation:
372     return match ty::get(typ).sty {
373       ty_nil => "()".to_string(),
374       ty_bot => "!".to_string(),
375       ty_bool => "bool".to_string(),
376       ty_char => "char".to_string(),
377       ty_int(t) => ast_util::int_ty_to_string(t, None).to_string(),
378       ty_uint(t) => ast_util::uint_ty_to_string(t, None).to_string(),
379       ty_float(t) => ast_util::float_ty_to_string(t).to_string(),
380       ty_uniq(typ) => format!("Box<{}>", ty_to_string(cx, typ)),
381       ty_ptr(ref tm) => {
382           format!("*{} {}", match tm.mutbl {
383               ast::MutMutable => "mut",
384               ast::MutImmutable => "const",
385           }, ty_to_string(cx, tm.ty))
386       }
387       ty_rptr(r, ref tm) => {
388           let mut buf = region_ptr_to_string(cx, r);
389           buf.push_str(mt_to_string(cx, tm).as_slice());
390           buf
391       }
392       ty_open(typ) => format!("opened<{}>", ty_to_string(cx, typ)),
393       ty_tup(ref elems) => {
394         let strs: Vec<String> = elems.iter().map(|elem| ty_to_string(cx, *elem)).collect();
395         format!("({})", strs.connect(","))
396       }
397       ty_closure(ref f) => {
398           closure_to_string(cx, &**f)
399       }
400       ty_bare_fn(ref f) => {
401           bare_fn_to_string(cx, f.fn_style, f.abi, None, &f.sig)
402       }
403       ty_infer(infer_ty) => infer_ty.to_string(),
404       ty_err => "[type error]".to_string(),
405       ty_param(ref param_ty) => {
406           param_ty.repr(cx)
407       }
408       ty_enum(did, ref substs) | ty_struct(did, ref substs) => {
409           let base = ty::item_path_str(cx, did);
410           let generics = ty::lookup_item_type(cx, did).generics;
411           parameterized(cx, base.as_slice(), substs, &generics)
412       }
413       ty_trait(box ty::TyTrait {
414           def_id: did, ref substs, ref bounds
415       }) => {
416           let base = ty::item_path_str(cx, did);
417           let trait_def = ty::lookup_trait_def(cx, did);
418           let ty = parameterized(cx, base.as_slice(),
419                                  substs, &trait_def.generics);
420           let bound_str = bounds.user_string(cx);
421           let bound_sep = if bound_str.is_empty() { "" } else { "+" };
422           format!("{}{}{}",
423                   ty,
424                   bound_sep,
425                   bound_str)
426       }
427       ty_str => "str".to_string(),
428       ty_unboxed_closure(..) => "closure".to_string(),
429       ty_vec(t, sz) => {
430           match sz {
431               Some(n) => {
432                   format!("[{}, ..{}]", ty_to_string(cx, t), n)
433               }
434               None => format!("[{}]", ty_to_string(cx, t)),
435           }
436       }
437     }
438 }
439
440 pub fn explicit_self_category_to_str(category: &ty::ExplicitSelfCategory)
441                                      -> &'static str {
442     match *category {
443         ty::StaticExplicitSelfCategory => "static",
444         ty::ByValueExplicitSelfCategory => "self",
445         ty::ByReferenceExplicitSelfCategory(_, ast::MutMutable) => {
446             "&mut self"
447         }
448         ty::ByReferenceExplicitSelfCategory(_, ast::MutImmutable) => "&self",
449         ty::ByBoxExplicitSelfCategory => "Box<self>",
450     }
451 }
452
453 pub fn parameterized(cx: &ctxt,
454                      base: &str,
455                      substs: &subst::Substs,
456                      generics: &ty::Generics)
457                      -> String
458 {
459     let mut strs = Vec::new();
460
461     match substs.regions {
462         subst::ErasedRegions => { }
463         subst::NonerasedRegions(ref regions) => {
464             for &r in regions.iter() {
465                 let s = region_to_string(cx, "", false, r);
466                 if !s.is_empty() {
467                     strs.push(s)
468                 } else {
469                     // This happens when the value of the region
470                     // parameter is not easily serialized. This may be
471                     // because the user omitted it in the first place,
472                     // or because it refers to some block in the code,
473                     // etc. I'm not sure how best to serialize this.
474                     strs.push(format!("'_"));
475                 }
476             }
477         }
478     }
479
480     let tps = substs.types.get_slice(subst::TypeSpace);
481     let ty_params = generics.types.get_slice(subst::TypeSpace);
482     let has_defaults = ty_params.last().map_or(false, |def| def.default.is_some());
483     let num_defaults = if has_defaults && !cx.sess.verbose() {
484         ty_params.iter().zip(tps.iter()).rev().take_while(|&(def, &actual)| {
485             match def.default {
486                 Some(default) => default.subst(cx, substs) == actual,
487                 None => false
488             }
489         }).count()
490     } else {
491         0
492     };
493
494     for t in tps[..tps.len() - num_defaults].iter() {
495         strs.push(ty_to_string(cx, *t))
496     }
497
498     if cx.sess.verbose() {
499         for t in substs.types.get_slice(subst::SelfSpace).iter() {
500             strs.push(format!("self {}", t.repr(cx)));
501         }
502
503         // generally there shouldn't be any substs in the fn param
504         // space, but in verbose mode, print them out.
505         for t in substs.types.get_slice(subst::FnSpace).iter() {
506             strs.push(format!("fn {}", t.repr(cx)));
507         }
508     }
509
510     if strs.len() > 0u {
511         format!("{}<{}>", base, strs.connect(","))
512     } else {
513         format!("{}", base)
514     }
515 }
516
517 pub fn ty_to_short_str(cx: &ctxt, typ: t) -> String {
518     let mut s = typ.repr(cx).to_string();
519     if s.len() >= 32u {
520         s = s.as_slice().slice(0u, 32u).to_string();
521     }
522     return s;
523 }
524
525 impl<T:Repr> Repr for Option<T> {
526     fn repr(&self, tcx: &ctxt) -> String {
527         match self {
528             &None => "None".to_string(),
529             &Some(ref t) => t.repr(tcx),
530         }
531     }
532 }
533
534 impl<T:Repr,U:Repr> Repr for Result<T,U> {
535     fn repr(&self, tcx: &ctxt) -> String {
536         match self {
537             &Ok(ref t) => t.repr(tcx),
538             &Err(ref u) => format!("Err({})", u.repr(tcx))
539         }
540     }
541 }
542
543 impl Repr for () {
544     fn repr(&self, _tcx: &ctxt) -> String {
545         "()".to_string()
546     }
547 }
548
549 impl<'a,T:Repr> Repr for &'a T {
550     fn repr(&self, tcx: &ctxt) -> String {
551         (&**self).repr(tcx)
552     }
553 }
554
555 impl<T:Repr> Repr for Rc<T> {
556     fn repr(&self, tcx: &ctxt) -> String {
557         (&**self).repr(tcx)
558     }
559 }
560
561 impl<T:Repr> Repr for Box<T> {
562     fn repr(&self, tcx: &ctxt) -> String {
563         (&**self).repr(tcx)
564     }
565 }
566
567 fn repr_vec<T:Repr>(tcx: &ctxt, v: &[T]) -> String {
568     vec_map_to_string(v, |t| t.repr(tcx))
569 }
570
571 impl<'a, T:Repr> Repr for &'a [T] {
572     fn repr(&self, tcx: &ctxt) -> String {
573         repr_vec(tcx, *self)
574     }
575 }
576
577 impl<T:Repr> Repr for OwnedSlice<T> {
578     fn repr(&self, tcx: &ctxt) -> String {
579         repr_vec(tcx, self.as_slice())
580     }
581 }
582
583 // This is necessary to handle types like Option<~[T]>, for which
584 // autoderef cannot convert the &[T] handler
585 impl<T:Repr> Repr for Vec<T> {
586     fn repr(&self, tcx: &ctxt) -> String {
587         repr_vec(tcx, self.as_slice())
588     }
589 }
590
591 impl<T:UserString> UserString for Vec<T> {
592     fn user_string(&self, tcx: &ctxt) -> String {
593         let strs: Vec<String> =
594             self.iter().map(|t| t.user_string(tcx)).collect();
595         strs.connect(", ")
596     }
597 }
598
599 impl Repr for def::Def {
600     fn repr(&self, _tcx: &ctxt) -> String {
601         format!("{}", *self)
602     }
603 }
604
605 impl Repr for ty::TypeParameterDef {
606     fn repr(&self, tcx: &ctxt) -> String {
607         format!("TypeParameterDef({}, {}, {}/{})",
608                 self.def_id,
609                 self.bounds.repr(tcx),
610                 self.space,
611                 self.index)
612     }
613 }
614
615 impl Repr for ty::RegionParameterDef {
616     fn repr(&self, tcx: &ctxt) -> String {
617         format!("RegionParameterDef(name={}, def_id={}, bounds={})",
618                 token::get_name(self.name),
619                 self.def_id.repr(tcx),
620                 self.bounds.repr(tcx))
621     }
622 }
623
624 impl Repr for ty::t {
625     fn repr(&self, tcx: &ctxt) -> String {
626         ty_to_string(tcx, *self)
627     }
628 }
629
630 impl Repr for ty::mt {
631     fn repr(&self, tcx: &ctxt) -> String {
632         mt_to_string(tcx, self)
633     }
634 }
635
636 impl Repr for subst::Substs {
637     fn repr(&self, tcx: &ctxt) -> String {
638         format!("Substs[types={}, regions={}]",
639                        self.types.repr(tcx),
640                        self.regions.repr(tcx))
641     }
642 }
643
644 impl<T:Repr> Repr for subst::VecPerParamSpace<T> {
645     fn repr(&self, tcx: &ctxt) -> String {
646         format!("[{};{};{}]",
647                        self.get_slice(subst::TypeSpace).repr(tcx),
648                        self.get_slice(subst::SelfSpace).repr(tcx),
649                        self.get_slice(subst::FnSpace).repr(tcx))
650     }
651 }
652
653 impl Repr for ty::ItemSubsts {
654     fn repr(&self, tcx: &ctxt) -> String {
655         format!("ItemSubsts({})", self.substs.repr(tcx))
656     }
657 }
658
659 impl Repr for subst::RegionSubsts {
660     fn repr(&self, tcx: &ctxt) -> String {
661         match *self {
662             subst::ErasedRegions => "erased".to_string(),
663             subst::NonerasedRegions(ref regions) => regions.repr(tcx)
664         }
665     }
666 }
667
668 impl Repr for ty::BuiltinBounds {
669     fn repr(&self, _tcx: &ctxt) -> String {
670         let mut res = Vec::new();
671         for b in self.iter() {
672             res.push(match b {
673                 ty::BoundSend => "Send".to_string(),
674                 ty::BoundSized => "Sized".to_string(),
675                 ty::BoundCopy => "Copy".to_string(),
676                 ty::BoundSync => "Sync".to_string(),
677             });
678         }
679         res.connect("+")
680     }
681 }
682
683 impl Repr for ty::ExistentialBounds {
684     fn repr(&self, tcx: &ctxt) -> String {
685         self.user_string(tcx)
686     }
687 }
688
689 impl Repr for ty::ParamBounds {
690     fn repr(&self, tcx: &ctxt) -> String {
691         let mut res = Vec::new();
692         res.push(self.builtin_bounds.repr(tcx));
693         for t in self.trait_bounds.iter() {
694             res.push(t.repr(tcx));
695         }
696         res.connect("+")
697     }
698 }
699
700 impl Repr for ty::TraitRef {
701     fn repr(&self, tcx: &ctxt) -> String {
702         let base = ty::item_path_str(tcx, self.def_id);
703         let trait_def = ty::lookup_trait_def(tcx, self.def_id);
704         format!("<{} as {}>",
705                 self.substs.self_ty().repr(tcx),
706                 parameterized(tcx, base.as_slice(), &self.substs, &trait_def.generics))
707     }
708 }
709
710 impl Repr for ty::TraitDef {
711     fn repr(&self, tcx: &ctxt) -> String {
712         format!("TraitDef(generics={}, bounds={}, trait_ref={})",
713                 self.generics.repr(tcx),
714                 self.bounds.repr(tcx),
715                 self.trait_ref.repr(tcx))
716     }
717 }
718
719 impl Repr for ast::Expr {
720     fn repr(&self, _tcx: &ctxt) -> String {
721         format!("expr({}: {})", self.id, pprust::expr_to_string(self))
722     }
723 }
724
725 impl Repr for ast::Path {
726     fn repr(&self, _tcx: &ctxt) -> String {
727         format!("path({})", pprust::path_to_string(self))
728     }
729 }
730
731 impl UserString for ast::Path {
732     fn user_string(&self, _tcx: &ctxt) -> String {
733         pprust::path_to_string(self)
734     }
735 }
736
737 impl Repr for ast::Item {
738     fn repr(&self, tcx: &ctxt) -> String {
739         format!("item({})", tcx.map.node_to_string(self.id))
740     }
741 }
742
743 impl Repr for ast::Lifetime {
744     fn repr(&self, _tcx: &ctxt) -> String {
745         format!("lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
746     }
747 }
748
749 impl Repr for ast::Stmt {
750     fn repr(&self, _tcx: &ctxt) -> String {
751         format!("stmt({}: {})",
752                 ast_util::stmt_id(self),
753                 pprust::stmt_to_string(self))
754     }
755 }
756
757 impl Repr for ast::Pat {
758     fn repr(&self, _tcx: &ctxt) -> String {
759         format!("pat({}: {})", self.id, pprust::pat_to_string(self))
760     }
761 }
762
763 impl Repr for ty::BoundRegion {
764     fn repr(&self, tcx: &ctxt) -> String {
765         match *self {
766             ty::BrAnon(id) => format!("BrAnon({})", id),
767             ty::BrNamed(id, name) => {
768                 format!("BrNamed({}, {})", id.repr(tcx), token::get_name(name))
769             }
770             ty::BrFresh(id) => format!("BrFresh({})", id),
771             ty::BrEnv => "BrEnv".to_string()
772         }
773     }
774 }
775
776 impl Repr for ty::Region {
777     fn repr(&self, tcx: &ctxt) -> String {
778         match *self {
779             ty::ReEarlyBound(id, space, index, name) => {
780                 format!("ReEarlyBound({}, {}, {}, {})",
781                                id,
782                                space,
783                                index,
784                                token::get_name(name))
785             }
786
787             ty::ReLateBound(binder_id, ref bound_region) => {
788                 format!("ReLateBound({}, {})",
789                         binder_id,
790                         bound_region.repr(tcx))
791             }
792
793             ty::ReFree(ref fr) => fr.repr(tcx),
794
795             ty::ReScope(id) => {
796                 format!("ReScope({})", id)
797             }
798
799             ty::ReStatic => {
800                 "ReStatic".to_string()
801             }
802
803             ty::ReInfer(ReVar(ref vid)) => {
804                 format!("ReInfer({})", vid.index)
805             }
806
807             ty::ReInfer(ReSkolemized(id, ref bound_region)) => {
808                 format!("re_skolemized({}, {})", id, bound_region.repr(tcx))
809             }
810
811             ty::ReEmpty => {
812                 "ReEmpty".to_string()
813             }
814         }
815     }
816 }
817
818 impl UserString for ty::Region {
819     fn user_string(&self, tcx: &ctxt) -> String {
820         region_to_string(tcx, "", false, *self)
821     }
822 }
823
824 impl Repr for ty::FreeRegion {
825     fn repr(&self, tcx: &ctxt) -> String {
826         format!("ReFree({}, {})",
827                 self.scope_id,
828                 self.bound_region.repr(tcx))
829     }
830 }
831
832 impl Repr for ast::DefId {
833     fn repr(&self, tcx: &ctxt) -> String {
834         // Unfortunately, there seems to be no way to attempt to print
835         // a path for a def-id, so I'll just make a best effort for now
836         // and otherwise fallback to just printing the crate/node pair
837         if self.krate == ast::LOCAL_CRATE {
838             match tcx.map.find(self.node) {
839                 Some(ast_map::NodeItem(..)) |
840                 Some(ast_map::NodeForeignItem(..)) |
841                 Some(ast_map::NodeImplItem(..)) |
842                 Some(ast_map::NodeTraitItem(..)) |
843                 Some(ast_map::NodeVariant(..)) |
844                 Some(ast_map::NodeStructCtor(..)) => {
845                     return format!(
846                                 "{}:{}",
847                                 *self,
848                                 ty::item_path_str(tcx, *self))
849                 }
850                 _ => {}
851             }
852         }
853         return format!("{}", *self)
854     }
855 }
856
857 impl Repr for ty::Polytype {
858     fn repr(&self, tcx: &ctxt) -> String {
859         format!("Polytype {{generics: {}, ty: {}}}",
860                 self.generics.repr(tcx),
861                 self.ty.repr(tcx))
862     }
863 }
864
865 impl Repr for ty::Generics {
866     fn repr(&self, tcx: &ctxt) -> String {
867         format!("Generics(types: {}, regions: {})",
868                 self.types.repr(tcx),
869                 self.regions.repr(tcx))
870     }
871 }
872
873 impl Repr for ty::ItemVariances {
874     fn repr(&self, tcx: &ctxt) -> String {
875         format!("ItemVariances(types={}, \
876                 regions={})",
877                 self.types.repr(tcx),
878                 self.regions.repr(tcx))
879     }
880 }
881
882 impl Repr for ty::Variance {
883     fn repr(&self, _: &ctxt) -> String {
884         // The first `.to_string()` returns a &'static str (it is not an implementation
885         // of the ToString trait). Because of that, we need to call `.to_string()` again
886         // if we want to have a `String`.
887         let result: &'static str = (*self).to_string();
888         result.to_string()
889     }
890 }
891
892 impl Repr for ty::Method {
893     fn repr(&self, tcx: &ctxt) -> String {
894         format!("method(name: {}, generics: {}, fty: {}, \
895                  explicit_self: {}, vis: {}, def_id: {})",
896                 self.name.repr(tcx),
897                 self.generics.repr(tcx),
898                 self.fty.repr(tcx),
899                 self.explicit_self.repr(tcx),
900                 self.vis.repr(tcx),
901                 self.def_id.repr(tcx))
902     }
903 }
904
905 impl Repr for ast::Name {
906     fn repr(&self, _tcx: &ctxt) -> String {
907         token::get_name(*self).get().to_string()
908     }
909 }
910
911 impl UserString for ast::Name {
912     fn user_string(&self, _tcx: &ctxt) -> String {
913         token::get_name(*self).get().to_string()
914     }
915 }
916
917 impl Repr for ast::Ident {
918     fn repr(&self, _tcx: &ctxt) -> String {
919         token::get_ident(*self).get().to_string()
920     }
921 }
922
923 impl Repr for ast::ExplicitSelf_ {
924     fn repr(&self, _tcx: &ctxt) -> String {
925         format!("{}", *self)
926     }
927 }
928
929 impl Repr for ast::Visibility {
930     fn repr(&self, _tcx: &ctxt) -> String {
931         format!("{}", *self)
932     }
933 }
934
935 impl Repr for ty::BareFnTy {
936     fn repr(&self, tcx: &ctxt) -> String {
937         format!("BareFnTy {{fn_style: {}, abi: {}, sig: {}}}",
938                 self.fn_style,
939                 self.abi.to_string(),
940                 self.sig.repr(tcx))
941     }
942 }
943
944 impl Repr for ty::FnSig {
945     fn repr(&self, tcx: &ctxt) -> String {
946         fn_sig_to_string(tcx, self)
947     }
948 }
949
950 impl Repr for typeck::MethodCallee {
951     fn repr(&self, tcx: &ctxt) -> String {
952         format!("MethodCallee {{origin: {}, ty: {}, {}}}",
953                 self.origin.repr(tcx),
954                 self.ty.repr(tcx),
955                 self.substs.repr(tcx))
956     }
957 }
958
959 impl Repr for typeck::MethodOrigin {
960     fn repr(&self, tcx: &ctxt) -> String {
961         match self {
962             &typeck::MethodStatic(def_id) => {
963                 format!("MethodStatic({})", def_id.repr(tcx))
964             }
965             &typeck::MethodStaticUnboxedClosure(def_id) => {
966                 format!("MethodStaticUnboxedClosure({})", def_id.repr(tcx))
967             }
968             &typeck::MethodTypeParam(ref p) => {
969                 p.repr(tcx)
970             }
971             &typeck::MethodTraitObject(ref p) => {
972                 p.repr(tcx)
973             }
974         }
975     }
976 }
977
978 impl Repr for typeck::MethodParam {
979     fn repr(&self, tcx: &ctxt) -> String {
980         format!("MethodParam({},{})",
981                 self.trait_ref.repr(tcx),
982                 self.method_num)
983     }
984 }
985
986 impl Repr for typeck::MethodObject {
987     fn repr(&self, tcx: &ctxt) -> String {
988         format!("MethodObject({},{},{})",
989                 self.trait_ref.repr(tcx),
990                 self.method_num,
991                 self.real_index)
992     }
993 }
994
995 impl Repr for ty::TraitStore {
996     fn repr(&self, tcx: &ctxt) -> String {
997         trait_store_to_string(tcx, *self)
998     }
999 }
1000
1001 impl Repr for ty::BuiltinBound {
1002     fn repr(&self, _tcx: &ctxt) -> String {
1003         format!("{}", *self)
1004     }
1005 }
1006
1007 impl UserString for ty::BuiltinBound {
1008     fn user_string(&self, _tcx: &ctxt) -> String {
1009         match *self {
1010             ty::BoundSend => "Send".to_string(),
1011             ty::BoundSized => "Sized".to_string(),
1012             ty::BoundCopy => "Copy".to_string(),
1013             ty::BoundSync => "Sync".to_string(),
1014         }
1015     }
1016 }
1017
1018 impl Repr for Span {
1019     fn repr(&self, tcx: &ctxt) -> String {
1020         tcx.sess.codemap().span_to_string(*self).to_string()
1021     }
1022 }
1023
1024 impl<A:UserString> UserString for Rc<A> {
1025     fn user_string(&self, tcx: &ctxt) -> String {
1026         let this: &A = &**self;
1027         this.user_string(tcx)
1028     }
1029 }
1030
1031 impl UserString for ty::ParamBounds {
1032     fn user_string(&self, tcx: &ctxt) -> String {
1033         let mut result = Vec::new();
1034         let s = self.builtin_bounds.user_string(tcx);
1035         if !s.is_empty() {
1036             result.push(s);
1037         }
1038         for n in self.trait_bounds.iter() {
1039             result.push(n.user_string(tcx));
1040         }
1041         result.connect("+")
1042     }
1043 }
1044
1045 impl UserString for ty::ExistentialBounds {
1046     fn user_string(&self, tcx: &ctxt) -> String {
1047         if self.builtin_bounds.contains_elem(ty::BoundSend) &&
1048             self.region_bound == ty::ReStatic
1049         { // Region bound is implied by builtin bounds:
1050             return self.builtin_bounds.repr(tcx);
1051         }
1052
1053         let mut res = Vec::new();
1054
1055         let region_str = self.region_bound.user_string(tcx);
1056         if !region_str.is_empty() {
1057             res.push(region_str);
1058         }
1059
1060         for bound in self.builtin_bounds.iter() {
1061             res.push(bound.user_string(tcx));
1062         }
1063
1064         res.connect("+")
1065     }
1066 }
1067
1068 impl UserString for ty::BuiltinBounds {
1069     fn user_string(&self, tcx: &ctxt) -> String {
1070         self.iter()
1071             .map(|bb| bb.user_string(tcx))
1072             .collect::<Vec<String>>()
1073             .connect("+")
1074             .to_string()
1075     }
1076 }
1077
1078 impl UserString for ty::TraitRef {
1079     fn user_string(&self, tcx: &ctxt) -> String {
1080         let base = ty::item_path_str(tcx, self.def_id);
1081         let trait_def = ty::lookup_trait_def(tcx, self.def_id);
1082         parameterized(tcx, base.as_slice(), &self.substs, &trait_def.generics)
1083     }
1084 }
1085
1086 impl UserString for ty::t {
1087     fn user_string(&self, tcx: &ctxt) -> String {
1088         ty_to_string(tcx, *self)
1089     }
1090 }
1091
1092 impl UserString for ast::Ident {
1093     fn user_string(&self, _tcx: &ctxt) -> String {
1094         token::get_name(self.name).get().to_string()
1095     }
1096 }
1097
1098 impl Repr for abi::Abi {
1099     fn repr(&self, _tcx: &ctxt) -> String {
1100         self.to_string()
1101     }
1102 }
1103
1104 impl UserString for abi::Abi {
1105     fn user_string(&self, _tcx: &ctxt) -> String {
1106         self.to_string()
1107     }
1108 }
1109
1110 impl Repr for ty::UpvarId {
1111     fn repr(&self, tcx: &ctxt) -> String {
1112         format!("UpvarId({};`{}`;{})",
1113                 self.var_id,
1114                 ty::local_var_name_str(tcx, self.var_id),
1115                 self.closure_expr_id)
1116     }
1117 }
1118
1119 impl Repr for ast::Mutability {
1120     fn repr(&self, _tcx: &ctxt) -> String {
1121         format!("{}", *self)
1122     }
1123 }
1124
1125 impl Repr for ty::BorrowKind {
1126     fn repr(&self, _tcx: &ctxt) -> String {
1127         format!("{}", *self)
1128     }
1129 }
1130
1131 impl Repr for ty::UpvarBorrow {
1132     fn repr(&self, tcx: &ctxt) -> String {
1133         format!("UpvarBorrow({}, {})",
1134                 self.kind.repr(tcx),
1135                 self.region.repr(tcx))
1136     }
1137 }
1138
1139 impl Repr for ty::IntVid {
1140     fn repr(&self, _tcx: &ctxt) -> String {
1141         format!("{}", self)
1142     }
1143 }
1144
1145 impl Repr for ty::FloatVid {
1146     fn repr(&self, _tcx: &ctxt) -> String {
1147         format!("{}", self)
1148     }
1149 }
1150
1151 impl Repr for ty::RegionVid {
1152     fn repr(&self, _tcx: &ctxt) -> String {
1153         format!("{}", self)
1154     }
1155 }
1156
1157 impl Repr for ty::TyVid {
1158     fn repr(&self, _tcx: &ctxt) -> String {
1159         format!("{}", self)
1160     }
1161 }
1162
1163 impl Repr for ty::IntVarValue {
1164     fn repr(&self, _tcx: &ctxt) -> String {
1165         format!("{}", *self)
1166     }
1167 }
1168
1169 impl Repr for ast::IntTy {
1170     fn repr(&self, _tcx: &ctxt) -> String {
1171         format!("{}", *self)
1172     }
1173 }
1174
1175 impl Repr for ast::UintTy {
1176     fn repr(&self, _tcx: &ctxt) -> String {
1177         format!("{}", *self)
1178     }
1179 }
1180
1181 impl Repr for ast::FloatTy {
1182     fn repr(&self, _tcx: &ctxt) -> String {
1183         format!("{}", *self)
1184     }
1185 }
1186
1187 impl Repr for ty::ExplicitSelfCategory {
1188     fn repr(&self, _: &ctxt) -> String {
1189         explicit_self_category_to_str(self).to_string()
1190     }
1191 }
1192
1193
1194 impl Repr for regionmanip::WfConstraint {
1195     fn repr(&self, tcx: &ctxt) -> String {
1196         match *self {
1197             regionmanip::RegionSubRegionConstraint(_, r_a, r_b) => {
1198                 format!("RegionSubRegionConstraint({}, {})",
1199                         r_a.repr(tcx),
1200                         r_b.repr(tcx))
1201             }
1202
1203             regionmanip::RegionSubParamConstraint(_, r, p) => {
1204                 format!("RegionSubParamConstraint({}, {})",
1205                         r.repr(tcx),
1206                         p.repr(tcx))
1207             }
1208         }
1209     }
1210 }
1211
1212 impl UserString for ParamTy {
1213     fn user_string(&self, tcx: &ctxt) -> String {
1214         let id = self.idx;
1215         let did = self.def_id;
1216         let ident = match tcx.ty_param_defs.borrow().find(&did.node) {
1217             Some(def) => token::get_name(def.name).get().to_string(),
1218
1219             // This can only happen when a type mismatch error happens and
1220             // the actual type has more type parameters than the expected one.
1221             None => format!("<generic #{}>", id),
1222         };
1223         ident
1224     }
1225 }
1226
1227 impl Repr for ParamTy {
1228     fn repr(&self, tcx: &ctxt) -> String {
1229         self.user_string(tcx)
1230     }
1231 }
1232
1233 impl<A:Repr,B:Repr> Repr for (A,B) {
1234     fn repr(&self, tcx: &ctxt) -> String {
1235         let &(ref a, ref b) = self;
1236         format!("({},{})", a.repr(tcx), b.repr(tcx))
1237     }
1238 }
1239