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.
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.
13 use middle::subst::{VecPerParamSpace,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, Ty, ParamTy};
20 use middle::ty::{ty_bool, ty_char, ty_struct, ty_enum};
21 use middle::ty::{ty_err, ty_str, ty_vec, ty_float, ty_bare_fn};
22 use middle::ty::{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};
26 use middle::ty_fold::TypeFoldable;
28 use std::collections::HashMap;
29 use std::hash::{Hash, Hasher};
33 use syntax::codemap::{Span, Pos};
34 use syntax::parse::token;
35 use syntax::print::pprust;
37 use syntax::{ast, ast_util};
38 use syntax::owned_slice::OwnedSlice;
40 /// Produces a string suitable for debugging output.
41 pub trait Repr<'tcx> {
42 fn repr(&self, tcx: &ctxt<'tcx>) -> String;
45 /// Produces a string suitable for showing to the user.
46 pub trait UserString<'tcx> : Repr<'tcx> {
47 fn user_string(&self, tcx: &ctxt<'tcx>) -> String;
50 pub fn note_and_explain_region(cx: &ctxt,
53 suffix: &str) -> Option<Span> {
54 match explain_region_and_span(cx, region) {
55 (ref str, Some(span)) => {
58 format!("{}{}{}", prefix, *str, suffix).index(&FullRange));
63 format!("{}{}{}", prefix, *str, suffix).index(&FullRange));
69 /// When a free region is associated with `item`, how should we describe the item in the error
71 fn item_scope_tag(item: &ast::Item) -> &'static str {
73 ast::ItemImpl(..) => "impl",
74 ast::ItemStruct(..) => "struct",
75 ast::ItemEnum(..) => "enum",
76 ast::ItemTrait(..) => "trait",
77 ast::ItemFn(..) => "function body",
82 pub fn explain_region_and_span(cx: &ctxt, region: ty::Region)
83 -> (String, Option<Span>) {
86 match cx.map.find(scope.node_id()) {
87 Some(ast_map::NodeBlock(ref blk)) => {
88 explain_span(cx, "block", blk.span)
90 Some(ast_map::NodeExpr(expr)) => {
92 ast::ExprCall(..) => explain_span(cx, "call", expr.span),
93 ast::ExprMethodCall(..) => {
94 explain_span(cx, "method call", expr.span)
96 ast::ExprMatch(_, _, ast::MatchSource::IfLetDesugar { .. }) =>
97 explain_span(cx, "if let", expr.span),
98 ast::ExprMatch(_, _, ast::MatchSource::WhileLetDesugar) => {
99 explain_span(cx, "while let", expr.span)
101 ast::ExprMatch(..) => explain_span(cx, "match", expr.span),
102 _ => explain_span(cx, "expression", expr.span)
105 Some(ast_map::NodeStmt(stmt)) => {
106 explain_span(cx, "statement", stmt.span)
108 Some(ast_map::NodeItem(it)) => {
109 let tag = item_scope_tag(&*it);
110 explain_span(cx, tag, it.span)
113 // this really should not happen
114 (format!("unknown scope: {:?}. Please report a bug.", scope), None)
120 let prefix = match fr.bound_region {
122 format!("the anonymous lifetime #{} defined on", idx + 1)
124 BrFresh(_) => "an anonymous lifetime defined on".to_string(),
126 format!("the lifetime {} as defined on",
127 bound_region_ptr_to_string(cx, fr.bound_region))
131 match cx.map.find(fr.scope.node_id()) {
132 Some(ast_map::NodeBlock(ref blk)) => {
133 let (msg, opt_span) = explain_span(cx, "block", blk.span);
134 (format!("{} {}", prefix, msg), opt_span)
136 Some(ast_map::NodeItem(it)) => {
137 let tag = item_scope_tag(&*it);
138 let (msg, opt_span) = explain_span(cx, tag, it.span);
139 (format!("{} {}", prefix, msg), opt_span)
142 // this really should not happen
143 (format!("{} unknown free region bounded by scope {:?}", prefix, fr.scope), None)
148 ReStatic => { ("the static lifetime".to_string(), None) }
150 ReEmpty => { ("the empty lifetime".to_string(), None) }
152 ReEarlyBound(_, _, _, name) => {
153 (format!("{}", token::get_name(name)), None)
156 // I believe these cases should not occur (except when debugging,
158 ty::ReInfer(_) | ty::ReLateBound(..) => {
159 (format!("lifetime {:?}", region), None)
163 fn explain_span(cx: &ctxt, heading: &str, span: Span)
164 -> (String, Option<Span>) {
165 let lo = cx.sess.codemap().lookup_char_pos_adj(span.lo);
166 (format!("the {} at {}:{}", heading, lo.line, lo.col.to_uint()),
171 pub fn bound_region_ptr_to_string(cx: &ctxt, br: BoundRegion) -> String {
172 bound_region_to_string(cx, "", false, br)
175 pub fn bound_region_to_string(cx: &ctxt,
176 prefix: &str, space: bool,
177 br: BoundRegion) -> String {
178 let space_str = if space { " " } else { "" };
180 if cx.sess.verbose() {
181 return format!("{}{}{}", prefix, br.repr(cx), space_str)
185 BrNamed(_, name) => {
186 format!("{}{}{}", prefix, token::get_name(name), space_str)
188 BrAnon(_) | BrFresh(_) | BrEnv => prefix.to_string()
192 // In general, if you are giving a region error message,
193 // you should use `explain_region()` or, better yet,
194 // `note_and_explain_region()`
195 pub fn region_ptr_to_string(cx: &ctxt, region: Region) -> String {
196 region_to_string(cx, "&", true, region)
199 pub fn region_to_string(cx: &ctxt, prefix: &str, space: bool, region: Region) -> String {
200 let space_str = if space { " " } else { "" };
202 if cx.sess.verbose() {
203 return format!("{}{}{}", prefix, region.repr(cx), space_str)
206 // These printouts are concise. They do not contain all the information
207 // the user might want to diagnose an error, but there is basically no way
208 // to fit that into a short string. Hence the recommendation to use
209 // `explain_region()` or `note_and_explain_region()`.
211 ty::ReScope(_) => prefix.to_string(),
212 ty::ReEarlyBound(_, _, _, name) => {
213 token::get_name(name).get().to_string()
215 ty::ReLateBound(_, br) => bound_region_to_string(cx, prefix, space, br),
216 ty::ReFree(ref fr) => bound_region_to_string(cx, prefix, space, fr.bound_region),
217 ty::ReInfer(ReSkolemized(_, br)) => {
218 bound_region_to_string(cx, prefix, space, br)
220 ty::ReInfer(ReVar(_)) => prefix.to_string(),
221 ty::ReStatic => format!("{}'static{}", prefix, space_str),
222 ty::ReEmpty => format!("{}'<empty>{}", prefix, space_str),
226 pub fn mutability_to_string(m: ast::Mutability) -> String {
228 ast::MutMutable => "mut ".to_string(),
229 ast::MutImmutable => "".to_string(),
233 pub fn mt_to_string<'tcx>(cx: &ctxt<'tcx>, m: &mt<'tcx>) -> String {
235 mutability_to_string(m.mutbl),
236 ty_to_string(cx, m.ty))
239 pub fn trait_store_to_string(cx: &ctxt, s: ty::TraitStore) -> String {
241 ty::UniqTraitStore => "Box ".to_string(),
242 ty::RegionTraitStore(r, m) => {
243 format!("{}{}", region_ptr_to_string(cx, r), mutability_to_string(m))
248 pub fn vec_map_to_string<T, F>(ts: &[T], f: F) -> String where
249 F: FnMut(&T) -> String,
251 let tstrs = ts.iter().map(f).collect::<Vec<String>>();
252 format!("[{}]", tstrs.connect(", "))
255 pub fn ty_to_string<'tcx>(cx: &ctxt<'tcx>, typ: &ty::TyS<'tcx>) -> String {
256 fn bare_fn_to_string<'tcx>(cx: &ctxt<'tcx>,
257 opt_def_id: Option<ast::DefId>,
258 unsafety: ast::Unsafety,
260 ident: Option<ast::Ident>,
261 sig: &ty::PolyFnSig<'tcx>)
263 let mut s = String::new();
266 ast::Unsafety::Normal => {}
267 ast::Unsafety::Unsafe => {
268 s.push_str(unsafety.to_string().as_slice());
273 if abi != abi::Rust {
274 s.push_str(format!("extern {} ", abi.to_string()).index(&FullRange));
282 s.push_str(token::get_ident(i).get());
287 push_sig_to_string(cx, &mut s, '(', ')', sig, "");
292 let path_str = ty::item_path_str(cx, def_id);
293 s.push_str(path_str.index(&FullRange));
302 fn closure_to_string<'tcx>(cx: &ctxt<'tcx>, cty: &ty::ClosureTy<'tcx>) -> String {
303 let mut s = String::new();
306 ty::UniqTraitStore => {}
307 ty::RegionTraitStore(region, _) => {
308 s.push_str(region_to_string(cx, "", true, region).index(&FullRange));
313 ast::Unsafety::Normal => {}
314 ast::Unsafety::Unsafe => {
315 s.push_str(cty.unsafety.to_string().as_slice());
320 let bounds_str = cty.bounds.user_string(cx);
323 ty::UniqTraitStore => {
324 assert_eq!(cty.onceness, ast::Once);
326 push_sig_to_string(cx, &mut s, '(', ')', &cty.sig,
327 bounds_str.index(&FullRange));
329 ty::RegionTraitStore(..) => {
332 ast::Once => s.push_str("once ")
334 push_sig_to_string(cx, &mut s, '|', '|', &cty.sig,
335 bounds_str.index(&FullRange));
342 fn push_sig_to_string<'tcx>(cx: &ctxt<'tcx>,
346 sig: &ty::PolyFnSig<'tcx>,
349 let strs = sig.0.inputs
351 .map(|a| ty_to_string(cx, *a))
352 .collect::<Vec<_>>();
353 s.push_str(strs.connect(", ").as_slice());
359 if !bounds.is_empty() {
365 ty::FnConverging(t) => {
366 if !ty::type_is_nil(t) {
368 s.push_str(ty_to_string(cx, t).index(&FullRange));
377 fn infer_ty_to_string(cx: &ctxt, ty: ty::InferTy) -> String {
378 let print_var_ids = cx.sess.verbose();
380 ty::TyVar(ref vid) if print_var_ids => vid.repr(cx),
381 ty::IntVar(ref vid) if print_var_ids => vid.repr(cx),
382 ty::FloatVar(ref vid) if print_var_ids => vid.repr(cx),
383 ty::TyVar(_) | ty::IntVar(_) | ty::FloatVar(_) => format!("_"),
384 ty::FreshTy(v) => format!("FreshTy({})", v),
385 ty::FreshIntTy(v) => format!("FreshIntTy({})", v)
389 // pretty print the structural type representation:
391 ty_bool => "bool".to_string(),
392 ty_char => "char".to_string(),
393 ty_int(t) => ast_util::int_ty_to_string(t, None).to_string(),
394 ty_uint(t) => ast_util::uint_ty_to_string(t, None).to_string(),
395 ty_float(t) => ast_util::float_ty_to_string(t).to_string(),
396 ty_uniq(typ) => format!("Box<{}>", ty_to_string(cx, typ)),
398 format!("*{} {}", match tm.mutbl {
399 ast::MutMutable => "mut",
400 ast::MutImmutable => "const",
401 }, ty_to_string(cx, tm.ty))
403 ty_rptr(r, ref tm) => {
404 let mut buf = region_ptr_to_string(cx, *r);
405 buf.push_str(mt_to_string(cx, tm).index(&FullRange));
409 format!("opened<{}>", ty_to_string(cx, typ)),
410 ty_tup(ref elems) => {
413 .map(|elem| ty_to_string(cx, *elem))
414 .collect::<Vec<_>>();
415 match strs.index(&FullRange) {
416 [ref string] => format!("({},)", string),
417 strs => format!("({})", strs.connect(", "))
420 ty_bare_fn(opt_def_id, ref f) => {
421 bare_fn_to_string(cx, opt_def_id, f.unsafety, f.abi, None, &f.sig)
423 ty_infer(infer_ty) => infer_ty_to_string(cx, infer_ty),
424 ty_err => "[type error]".to_string(),
425 ty_param(ref param_ty) => {
426 if cx.sess.verbose() {
429 param_ty.user_string(cx)
432 ty_enum(did, substs) | ty_struct(did, substs) => {
433 let base = ty::item_path_str(cx, did);
434 let generics = ty::lookup_item_type(cx, did).generics;
435 parameterized(cx, base.as_slice(), substs, &generics, did)
437 ty_trait(box ty::TyTrait {
438 ref principal, ref bounds
440 let principal = principal.user_string(cx);
441 let bound_str = bounds.user_string(cx);
442 let bound_sep = if bound_str.is_empty() { "" } else { " + " };
448 ty::ty_projection(ref data) => {
449 format!("<{} as {}>::{}",
450 data.trait_ref.self_ty().user_string(cx),
451 data.trait_ref.user_string(cx),
452 data.item_name.user_string(cx))
454 ty_str => "str".to_string(),
455 ty_unboxed_closure(ref did, _, substs) => {
456 let unboxed_closures = cx.unboxed_closures.borrow();
457 unboxed_closures.get(did).map(|cl| {
458 closure_to_string(cx, &cl.closure_type.subst(cx, substs))
459 }).unwrap_or_else(|| {
460 if did.krate == ast::LOCAL_CRATE {
461 let span = cx.map.span(did.node);
462 format!("closure[{}]", span.repr(cx))
469 let inner_str = ty_to_string(cx, t);
471 Some(n) => format!("[{}; {}]", inner_str, n),
472 None => format!("[{}]", inner_str),
478 pub fn explicit_self_category_to_str(category: &ty::ExplicitSelfCategory)
481 ty::StaticExplicitSelfCategory => "static",
482 ty::ByValueExplicitSelfCategory => "self",
483 ty::ByReferenceExplicitSelfCategory(_, ast::MutMutable) => {
486 ty::ByReferenceExplicitSelfCategory(_, ast::MutImmutable) => "&self",
487 ty::ByBoxExplicitSelfCategory => "Box<self>",
491 pub fn parameterized<'tcx>(cx: &ctxt<'tcx>,
493 substs: &subst::Substs<'tcx>,
494 generics: &ty::Generics<'tcx>,
498 if cx.sess.verbose() {
499 if substs.is_noop() {
500 return format!("{}", base);
502 return format!("{}<{},{}>",
504 substs.regions.repr(cx),
505 substs.types.repr(cx));
509 let mut strs = Vec::new();
511 match substs.regions {
512 subst::ErasedRegions => { }
513 subst::NonerasedRegions(ref regions) => {
514 for &r in regions.iter() {
515 let s = region_to_string(cx, "", false, r);
517 // This happens when the value of the region
518 // parameter is not easily serialized. This may be
519 // because the user omitted it in the first place,
520 // or because it refers to some block in the code,
521 // etc. I'm not sure how best to serialize this.
522 strs.push(format!("'_"));
530 let tps = substs.types.get_slice(subst::TypeSpace);
531 let ty_params = generics.types.get_slice(subst::TypeSpace);
532 let has_defaults = ty_params.last().map_or(false, |def| def.default.is_some());
533 let num_defaults = if has_defaults {
534 ty_params.iter().zip(tps.iter()).rev().take_while(|&(def, &actual)| {
536 Some(default) => default.subst(cx, substs) == actual,
544 for t in tps.index(&(0..(tps.len() - num_defaults))).iter() {
545 strs.push(ty_to_string(cx, *t))
548 if cx.lang_items.fn_trait_kind(did).is_some() {
551 if strs[0].starts_with("(") && strs[0].ends_with(",)") {
552 strs[0].index(&(1 .. (strs[0].len() - 2))) // Remove '(' and ',)'
553 } else if strs[0].starts_with("(") && strs[0].ends_with(")") {
554 strs[0].index(&(1 .. (strs[0].len() - 1))) // Remove '(' and ')'
556 strs[0].index(&FullRange)
558 if &*strs[1] == "()" { String::new() } else { format!(" -> {}", strs[1]) })
559 } else if strs.len() > 0 {
560 format!("{}<{}>", base, strs.connect(", "))
566 pub fn ty_to_short_str<'tcx>(cx: &ctxt<'tcx>, typ: Ty<'tcx>) -> String {
567 let mut s = typ.repr(cx).to_string();
569 s = s.index(&(0u..32u)).to_string();
574 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for Option<T> {
575 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
577 &None => "None".to_string(),
578 &Some(ref t) => t.repr(tcx),
583 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for P<T> {
584 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
589 impl<'tcx,T:Repr<'tcx>,U:Repr<'tcx>> Repr<'tcx> for Result<T,U> {
590 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
592 &Ok(ref t) => t.repr(tcx),
593 &Err(ref u) => format!("Err({})", u.repr(tcx))
598 impl<'tcx> Repr<'tcx> for () {
599 fn repr(&self, _tcx: &ctxt) -> String {
604 impl<'a, 'tcx, T: ?Sized +Repr<'tcx>> Repr<'tcx> for &'a T {
605 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
606 Repr::repr(*self, tcx)
610 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for Rc<T> {
611 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
616 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for Box<T> {
617 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
622 fn repr_vec<'tcx, T:Repr<'tcx>>(tcx: &ctxt<'tcx>, v: &[T]) -> String {
623 vec_map_to_string(v, |t| t.repr(tcx))
626 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for [T] {
627 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
632 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for OwnedSlice<T> {
633 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
634 repr_vec(tcx, self.index(&FullRange))
638 // This is necessary to handle types like Option<~[T]>, for which
639 // autoderef cannot convert the &[T] handler
640 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for Vec<T> {
641 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
642 repr_vec(tcx, self.index(&FullRange))
646 impl<'tcx, T:UserString<'tcx>> UserString<'tcx> for Vec<T> {
647 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
648 let strs: Vec<String> =
649 self.iter().map(|t| t.user_string(tcx)).collect();
654 impl<'tcx> Repr<'tcx> for def::Def {
655 fn repr(&self, _tcx: &ctxt) -> String {
656 format!("{:?}", *self)
660 impl<'tcx> Repr<'tcx> for ty::TypeParameterDef<'tcx> {
661 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
662 format!("TypeParameterDef({:?}, {}, {:?}/{})",
664 self.bounds.repr(tcx),
670 impl<'tcx> Repr<'tcx> for ty::RegionParameterDef {
671 fn repr(&self, tcx: &ctxt) -> String {
672 format!("RegionParameterDef(name={}, def_id={}, bounds={})",
673 token::get_name(self.name),
674 self.def_id.repr(tcx),
675 self.bounds.repr(tcx))
679 impl<'tcx> Repr<'tcx> for ty::TyS<'tcx> {
680 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
681 ty_to_string(tcx, self)
685 impl<'tcx> Repr<'tcx> for ty::mt<'tcx> {
686 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
687 mt_to_string(tcx, self)
691 impl<'tcx> Repr<'tcx> for subst::Substs<'tcx> {
692 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
693 format!("Substs[types={}, regions={}]",
694 self.types.repr(tcx),
695 self.regions.repr(tcx))
699 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for subst::VecPerParamSpace<T> {
700 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
701 format!("[{};{};{}]",
702 self.get_slice(subst::TypeSpace).repr(tcx),
703 self.get_slice(subst::SelfSpace).repr(tcx),
704 self.get_slice(subst::FnSpace).repr(tcx))
708 impl<'tcx> Repr<'tcx> for ty::ItemSubsts<'tcx> {
709 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
710 format!("ItemSubsts({})", self.substs.repr(tcx))
714 impl<'tcx> Repr<'tcx> for subst::RegionSubsts {
715 fn repr(&self, tcx: &ctxt) -> String {
717 subst::ErasedRegions => "erased".to_string(),
718 subst::NonerasedRegions(ref regions) => regions.repr(tcx)
723 impl<'tcx> Repr<'tcx> for ty::BuiltinBounds {
724 fn repr(&self, _tcx: &ctxt) -> String {
725 let mut res = Vec::new();
726 for b in self.iter() {
728 ty::BoundSend => "Send".to_string(),
729 ty::BoundSized => "Sized".to_string(),
730 ty::BoundCopy => "Copy".to_string(),
731 ty::BoundSync => "Sync".to_string(),
738 impl<'tcx> Repr<'tcx> for ty::ExistentialBounds<'tcx> {
739 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
740 self.user_string(tcx)
744 impl<'tcx> Repr<'tcx> for ty::ParamBounds<'tcx> {
745 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
746 let mut res = Vec::new();
747 res.push(self.builtin_bounds.repr(tcx));
748 for t in self.trait_bounds.iter() {
749 res.push(t.repr(tcx));
755 impl<'tcx> Repr<'tcx> for ty::TraitRef<'tcx> {
756 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
757 // when printing out the debug representation, we don't need
758 // to enumerate the `for<...>` etc because the debruijn index
759 // tells you everything you need to know.
760 let base = ty::item_path_str(tcx, self.def_id);
761 let trait_def = ty::lookup_trait_def(tcx, self.def_id);
762 format!("TraitRef({}, {})",
763 self.substs.self_ty().repr(tcx),
764 parameterized(tcx, base.as_slice(), self.substs, &trait_def.generics, self.def_id))
768 impl<'tcx> Repr<'tcx> for ty::TraitDef<'tcx> {
769 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
770 format!("TraitDef(generics={}, bounds={}, trait_ref={})",
771 self.generics.repr(tcx),
772 self.bounds.repr(tcx),
773 self.trait_ref.repr(tcx))
777 impl<'tcx> Repr<'tcx> for ast::TraitItem {
778 fn repr(&self, _tcx: &ctxt) -> String {
780 ast::RequiredMethod(ref data) => format!("RequiredMethod({}, id={})",
781 data.ident, data.id),
782 ast::ProvidedMethod(ref data) => format!("ProvidedMethod(id={})",
784 ast::TypeTraitItem(ref data) => format!("TypeTraitItem({}, id={})",
785 data.ty_param.ident, data.ty_param.id),
790 impl<'tcx> Repr<'tcx> for ast::Expr {
791 fn repr(&self, _tcx: &ctxt) -> String {
792 format!("expr({}: {})", self.id, pprust::expr_to_string(self))
796 impl<'tcx> Repr<'tcx> for ast::Path {
797 fn repr(&self, _tcx: &ctxt) -> String {
798 format!("path({})", pprust::path_to_string(self))
802 impl<'tcx> UserString<'tcx> for ast::Path {
803 fn user_string(&self, _tcx: &ctxt) -> String {
804 pprust::path_to_string(self)
808 impl<'tcx> Repr<'tcx> for ast::Ty {
809 fn repr(&self, _tcx: &ctxt) -> String {
810 format!("type({})", pprust::ty_to_string(self))
814 impl<'tcx> Repr<'tcx> for ast::Item {
815 fn repr(&self, tcx: &ctxt) -> String {
816 format!("item({})", tcx.map.node_to_string(self.id))
820 impl<'tcx> Repr<'tcx> for ast::Lifetime {
821 fn repr(&self, _tcx: &ctxt) -> String {
822 format!("lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
826 impl<'tcx> Repr<'tcx> for ast::Stmt {
827 fn repr(&self, _tcx: &ctxt) -> String {
828 format!("stmt({}: {})",
829 ast_util::stmt_id(self),
830 pprust::stmt_to_string(self))
834 impl<'tcx> Repr<'tcx> for ast::Pat {
835 fn repr(&self, _tcx: &ctxt) -> String {
836 format!("pat({}: {})", self.id, pprust::pat_to_string(self))
840 impl<'tcx> Repr<'tcx> for ty::BoundRegion {
841 fn repr(&self, tcx: &ctxt) -> String {
843 ty::BrAnon(id) => format!("BrAnon({})", id),
844 ty::BrNamed(id, name) => {
845 format!("BrNamed({}, {})", id.repr(tcx), token::get_name(name))
847 ty::BrFresh(id) => format!("BrFresh({})", id),
848 ty::BrEnv => "BrEnv".to_string()
853 impl<'tcx> Repr<'tcx> for ty::Region {
854 fn repr(&self, tcx: &ctxt) -> String {
856 ty::ReEarlyBound(id, space, index, name) => {
857 format!("ReEarlyBound({}, {:?}, {}, {})",
861 token::get_name(name))
864 ty::ReLateBound(binder_id, ref bound_region) => {
865 format!("ReLateBound({:?}, {})",
867 bound_region.repr(tcx))
870 ty::ReFree(ref fr) => fr.repr(tcx),
873 format!("ReScope({:?})", id)
877 "ReStatic".to_string()
880 ty::ReInfer(ReVar(ref vid)) => {
884 ty::ReInfer(ReSkolemized(id, ref bound_region)) => {
885 format!("re_skolemized({}, {})", id, bound_region.repr(tcx))
889 "ReEmpty".to_string()
895 impl<'tcx> UserString<'tcx> for ty::Region {
896 fn user_string(&self, tcx: &ctxt) -> String {
897 region_to_string(tcx, "", false, *self)
901 impl<'tcx> Repr<'tcx> for ty::FreeRegion {
902 fn repr(&self, tcx: &ctxt) -> String {
903 format!("ReFree({}, {})",
904 self.scope.node_id(),
905 self.bound_region.repr(tcx))
909 impl<'tcx> Repr<'tcx> for ast::DefId {
910 fn repr(&self, tcx: &ctxt) -> String {
911 // Unfortunately, there seems to be no way to attempt to print
912 // a path for a def-id, so I'll just make a best effort for now
913 // and otherwise fallback to just printing the crate/node pair
914 if self.krate == ast::LOCAL_CRATE {
915 match tcx.map.find(self.node) {
916 Some(ast_map::NodeItem(..)) |
917 Some(ast_map::NodeForeignItem(..)) |
918 Some(ast_map::NodeImplItem(..)) |
919 Some(ast_map::NodeTraitItem(..)) |
920 Some(ast_map::NodeVariant(..)) |
921 Some(ast_map::NodeStructCtor(..)) => {
925 ty::item_path_str(tcx, *self))
930 return format!("{:?}", *self)
934 impl<'tcx> Repr<'tcx> for ty::TypeScheme<'tcx> {
935 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
936 format!("TypeScheme {{generics: {}, ty: {}}}",
937 self.generics.repr(tcx),
942 impl<'tcx> Repr<'tcx> for ty::Generics<'tcx> {
943 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
944 format!("Generics(types: {}, regions: {}, predicates: {})",
945 self.types.repr(tcx),
946 self.regions.repr(tcx),
947 self.predicates.repr(tcx))
951 impl<'tcx> Repr<'tcx> for ty::GenericBounds<'tcx> {
952 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
953 format!("GenericBounds({})",
954 self.predicates.repr(tcx))
958 impl<'tcx> Repr<'tcx> for ty::ItemVariances {
959 fn repr(&self, tcx: &ctxt) -> String {
960 format!("ItemVariances(types={}, \
962 self.types.repr(tcx),
963 self.regions.repr(tcx))
967 impl<'tcx> Repr<'tcx> for ty::Variance {
968 fn repr(&self, _: &ctxt) -> String {
969 // The first `.to_string()` returns a &'static str (it is not an implementation
970 // of the ToString trait). Because of that, we need to call `.to_string()` again
971 // if we want to have a `String`.
972 let result: &'static str = (*self).to_string();
977 impl<'tcx> Repr<'tcx> for ty::Method<'tcx> {
978 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
979 format!("method(name: {}, generics: {}, fty: {}, \
980 explicit_self: {}, vis: {}, def_id: {})",
982 self.generics.repr(tcx),
984 self.explicit_self.repr(tcx),
986 self.def_id.repr(tcx))
990 impl<'tcx> Repr<'tcx> for ast::Name {
991 fn repr(&self, _tcx: &ctxt) -> String {
992 token::get_name(*self).get().to_string()
996 impl<'tcx> UserString<'tcx> for ast::Name {
997 fn user_string(&self, _tcx: &ctxt) -> String {
998 token::get_name(*self).get().to_string()
1002 impl<'tcx> Repr<'tcx> for ast::Ident {
1003 fn repr(&self, _tcx: &ctxt) -> String {
1004 token::get_ident(*self).get().to_string()
1008 impl<'tcx> Repr<'tcx> for ast::ExplicitSelf_ {
1009 fn repr(&self, _tcx: &ctxt) -> String {
1010 format!("{:?}", *self)
1014 impl<'tcx> Repr<'tcx> for ast::Visibility {
1015 fn repr(&self, _tcx: &ctxt) -> String {
1016 format!("{:?}", *self)
1020 impl<'tcx> Repr<'tcx> for ty::BareFnTy<'tcx> {
1021 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1022 format!("BareFnTy {{unsafety: {}, abi: {}, sig: {}}}",
1024 self.abi.to_string(),
1030 impl<'tcx> Repr<'tcx> for ty::FnSig<'tcx> {
1031 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1032 format!("fn{} -> {}", self.inputs.repr(tcx), self.output.repr(tcx))
1036 impl<'tcx> Repr<'tcx> for ty::FnOutput<'tcx> {
1037 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1039 ty::FnConverging(ty) =>
1040 format!("FnConverging({0})", ty.repr(tcx)),
1042 "FnDiverging".to_string()
1047 impl<'tcx> Repr<'tcx> for ty::MethodCallee<'tcx> {
1048 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1049 format!("MethodCallee {{origin: {}, ty: {}, {}}}",
1050 self.origin.repr(tcx),
1052 self.substs.repr(tcx))
1056 impl<'tcx> Repr<'tcx> for ty::MethodOrigin<'tcx> {
1057 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1059 &ty::MethodStatic(def_id) => {
1060 format!("MethodStatic({})", def_id.repr(tcx))
1062 &ty::MethodStaticUnboxedClosure(def_id) => {
1063 format!("MethodStaticUnboxedClosure({})", def_id.repr(tcx))
1065 &ty::MethodTypeParam(ref p) => {
1068 &ty::MethodTraitObject(ref p) => {
1075 impl<'tcx> Repr<'tcx> for ty::MethodParam<'tcx> {
1076 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1077 format!("MethodParam({},{})",
1078 self.trait_ref.repr(tcx),
1083 impl<'tcx> Repr<'tcx> for ty::MethodObject<'tcx> {
1084 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1085 format!("MethodObject({},{},{})",
1086 self.trait_ref.repr(tcx),
1092 impl<'tcx> Repr<'tcx> for ty::TraitStore {
1093 fn repr(&self, tcx: &ctxt) -> String {
1094 trait_store_to_string(tcx, *self)
1098 impl<'tcx> Repr<'tcx> for ty::BuiltinBound {
1099 fn repr(&self, _tcx: &ctxt) -> String {
1100 format!("{:?}", *self)
1104 impl<'tcx> UserString<'tcx> for ty::BuiltinBound {
1105 fn user_string(&self, _tcx: &ctxt) -> String {
1107 ty::BoundSend => "Send".to_string(),
1108 ty::BoundSized => "Sized".to_string(),
1109 ty::BoundCopy => "Copy".to_string(),
1110 ty::BoundSync => "Sync".to_string(),
1115 impl<'tcx> Repr<'tcx> for Span {
1116 fn repr(&self, tcx: &ctxt) -> String {
1117 tcx.sess.codemap().span_to_string(*self).to_string()
1121 impl<'tcx, A:UserString<'tcx>> UserString<'tcx> for Rc<A> {
1122 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1123 let this: &A = &**self;
1124 this.user_string(tcx)
1128 impl<'tcx> UserString<'tcx> for ty::ParamBounds<'tcx> {
1129 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1130 let mut result = Vec::new();
1131 let s = self.builtin_bounds.user_string(tcx);
1135 for n in self.trait_bounds.iter() {
1136 result.push(n.user_string(tcx));
1138 result.connect(" + ")
1142 impl<'tcx> UserString<'tcx> for ty::ExistentialBounds<'tcx> {
1143 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1144 if self.builtin_bounds.contains(&ty::BoundSend) &&
1145 self.region_bound == ty::ReStatic
1146 { // Region bound is implied by builtin bounds:
1147 return self.builtin_bounds.repr(tcx);
1150 let mut res = Vec::new();
1152 let region_str = self.region_bound.user_string(tcx);
1153 if !region_str.is_empty() {
1154 res.push(region_str);
1157 for bound in self.builtin_bounds.iter() {
1158 res.push(bound.user_string(tcx));
1165 impl<'tcx> UserString<'tcx> for ty::BuiltinBounds {
1166 fn user_string(&self, tcx: &ctxt) -> String {
1168 .map(|bb| bb.user_string(tcx))
1169 .collect::<Vec<String>>()
1175 impl<'tcx, T> UserString<'tcx> for ty::Binder<T>
1176 where T : UserString<'tcx> + TypeFoldable<'tcx>
1178 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1179 // Replace any anonymous late-bound regions with named
1180 // variants, using gensym'd identifiers, so that we can
1181 // clearly differentiate between named and unnamed regions in
1182 // the output. We'll probably want to tweak this over time to
1183 // decide just how much information to give.
1184 let mut names = Vec::new();
1185 let (unbound_value, _) = ty::replace_late_bound_regions(tcx, self, |br, debruijn| {
1186 ty::ReLateBound(debruijn, match br {
1187 ty::BrNamed(_, name) => {
1188 names.push(token::get_name(name));
1194 let name = token::gensym("'r");
1195 names.push(token::get_name(name));
1196 ty::BrNamed(ast_util::local_def(ast::DUMMY_NODE_ID), name)
1200 let names: Vec<_> = names.iter().map(|s| s.get()).collect();
1202 let value_str = unbound_value.user_string(tcx);
1203 if names.len() == 0 {
1206 format!("for<{}> {}", names.connect(","), value_str)
1211 impl<'tcx> UserString<'tcx> for ty::TraitRef<'tcx> {
1212 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1213 let path_str = ty::item_path_str(tcx, self.def_id);
1214 let trait_def = ty::lookup_trait_def(tcx, self.def_id);
1215 parameterized(tcx, path_str.as_slice(), self.substs,
1216 &trait_def.generics, self.def_id)
1220 impl<'tcx> UserString<'tcx> for Ty<'tcx> {
1221 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1222 ty_to_string(tcx, *self)
1226 impl<'tcx> UserString<'tcx> for ast::Ident {
1227 fn user_string(&self, _tcx: &ctxt) -> String {
1228 token::get_name(self.name).get().to_string()
1232 impl<'tcx> Repr<'tcx> for abi::Abi {
1233 fn repr(&self, _tcx: &ctxt) -> String {
1238 impl<'tcx> UserString<'tcx> for abi::Abi {
1239 fn user_string(&self, _tcx: &ctxt) -> String {
1244 impl<'tcx> Repr<'tcx> for ty::UpvarId {
1245 fn repr(&self, tcx: &ctxt) -> String {
1246 format!("UpvarId({};`{}`;{})",
1248 ty::local_var_name_str(tcx, self.var_id),
1249 self.closure_expr_id)
1253 impl<'tcx> Repr<'tcx> for ast::Mutability {
1254 fn repr(&self, _tcx: &ctxt) -> String {
1255 format!("{:?}", *self)
1259 impl<'tcx> Repr<'tcx> for ty::BorrowKind {
1260 fn repr(&self, _tcx: &ctxt) -> String {
1261 format!("{:?}", *self)
1265 impl<'tcx> Repr<'tcx> for ty::UpvarBorrow {
1266 fn repr(&self, tcx: &ctxt) -> String {
1267 format!("UpvarBorrow({}, {})",
1268 self.kind.repr(tcx),
1269 self.region.repr(tcx))
1273 impl<'tcx> Repr<'tcx> for ty::IntVid {
1274 fn repr(&self, _tcx: &ctxt) -> String {
1275 format!("{:?}", self)
1279 impl<'tcx> Repr<'tcx> for ty::FloatVid {
1280 fn repr(&self, _tcx: &ctxt) -> String {
1281 format!("{:?}", self)
1285 impl<'tcx> Repr<'tcx> for ty::RegionVid {
1286 fn repr(&self, _tcx: &ctxt) -> String {
1287 format!("{:?}", self)
1291 impl<'tcx> Repr<'tcx> for ty::TyVid {
1292 fn repr(&self, _tcx: &ctxt) -> String {
1293 format!("{:?}", self)
1297 impl<'tcx> Repr<'tcx> for ty::IntVarValue {
1298 fn repr(&self, _tcx: &ctxt) -> String {
1299 format!("{:?}", *self)
1303 impl<'tcx> Repr<'tcx> for ast::IntTy {
1304 fn repr(&self, _tcx: &ctxt) -> String {
1305 format!("{:?}", *self)
1309 impl<'tcx> Repr<'tcx> for ast::UintTy {
1310 fn repr(&self, _tcx: &ctxt) -> String {
1311 format!("{:?}", *self)
1315 impl<'tcx> Repr<'tcx> for ast::FloatTy {
1316 fn repr(&self, _tcx: &ctxt) -> String {
1317 format!("{:?}", *self)
1321 impl<'tcx> Repr<'tcx> for ty::ExplicitSelfCategory {
1322 fn repr(&self, _: &ctxt) -> String {
1323 explicit_self_category_to_str(self).to_string()
1327 impl<'tcx> UserString<'tcx> for ParamTy {
1328 fn user_string(&self, _tcx: &ctxt) -> String {
1329 format!("{}", token::get_name(self.name))
1333 impl<'tcx> Repr<'tcx> for ParamTy {
1334 fn repr(&self, tcx: &ctxt) -> String {
1335 let ident = self.user_string(tcx);
1336 format!("{}/{:?}.{}", ident, self.space, self.idx)
1340 impl<'tcx, A:Repr<'tcx>, B:Repr<'tcx>> Repr<'tcx> for (A,B) {
1341 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1342 let &(ref a, ref b) = self;
1343 format!("({},{})", a.repr(tcx), b.repr(tcx))
1347 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for ty::Binder<T> {
1348 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1349 format!("Binder({})", self.0.repr(tcx))
1354 impl<'tcx, S, H, K, V> Repr<'tcx> for HashMap<K,V,H>
1355 where K : Hash<S> + Eq + Repr<'tcx>,
1359 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1360 format!("HashMap({})",
1362 .map(|(k,v)| format!("{} => {}", k.repr(tcx), v.repr(tcx)))
1363 .collect::<Vec<String>>()
1368 impl<'tcx, T, U> Repr<'tcx> for ty::OutlivesPredicate<T,U>
1369 where T : Repr<'tcx> + TypeFoldable<'tcx>,
1370 U : Repr<'tcx> + TypeFoldable<'tcx>,
1372 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1373 format!("OutlivesPredicate({}, {})",
1379 impl<'tcx, T, U> UserString<'tcx> for ty::OutlivesPredicate<T,U>
1380 where T : UserString<'tcx> + TypeFoldable<'tcx>,
1381 U : UserString<'tcx> + TypeFoldable<'tcx>,
1383 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1385 self.0.user_string(tcx),
1386 self.1.user_string(tcx))
1390 impl<'tcx> Repr<'tcx> for ty::EquatePredicate<'tcx> {
1391 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1392 format!("EquatePredicate({}, {})",
1398 impl<'tcx> UserString<'tcx> for ty::EquatePredicate<'tcx> {
1399 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1401 self.0.user_string(tcx),
1402 self.1.user_string(tcx))
1406 impl<'tcx> Repr<'tcx> for ty::TraitPredicate<'tcx> {
1407 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1408 format!("TraitPredicate({})",
1409 self.trait_ref.repr(tcx))
1413 impl<'tcx> UserString<'tcx> for ty::TraitPredicate<'tcx> {
1414 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1416 self.trait_ref.self_ty().user_string(tcx),
1417 self.trait_ref.user_string(tcx))
1421 impl<'tcx> UserString<'tcx> for ty::ProjectionPredicate<'tcx> {
1422 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1424 self.projection_ty.user_string(tcx),
1425 self.ty.user_string(tcx))
1429 impl<'tcx> Repr<'tcx> for ty::ProjectionTy<'tcx> {
1430 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1431 format!("<{} as {}>::{}",
1432 self.trait_ref.self_ty().repr(tcx),
1433 self.trait_ref.repr(tcx),
1434 self.item_name.repr(tcx))
1438 impl<'tcx> UserString<'tcx> for ty::ProjectionTy<'tcx> {
1439 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1440 format!("<{} as {}>::{}",
1441 self.trait_ref.self_ty().user_string(tcx),
1442 self.trait_ref.user_string(tcx),
1443 self.item_name.user_string(tcx))
1447 impl<'tcx> UserString<'tcx> for ty::Predicate<'tcx> {
1448 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1450 ty::Predicate::Trait(ref data) => data.user_string(tcx),
1451 ty::Predicate::Equate(ref predicate) => predicate.user_string(tcx),
1452 ty::Predicate::RegionOutlives(ref predicate) => predicate.user_string(tcx),
1453 ty::Predicate::TypeOutlives(ref predicate) => predicate.user_string(tcx),
1454 ty::Predicate::Projection(ref predicate) => predicate.user_string(tcx),