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