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, ty_closure};
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};
30 use syntax::codemap::{Span, Pos};
31 use syntax::parse::token;
32 use syntax::print::pprust;
34 use syntax::{ast, ast_util};
35 use syntax::owned_slice::OwnedSlice;
37 /// Produces a string suitable for debugging output.
38 pub trait Repr<'tcx> for Sized? {
39 fn repr(&self, tcx: &ctxt<'tcx>) -> String;
42 /// Produces a string suitable for showing to the user.
43 pub trait UserString<'tcx> {
44 fn user_string(&self, tcx: &ctxt<'tcx>) -> String;
47 pub fn note_and_explain_region(cx: &ctxt,
50 suffix: &str) -> Option<Span> {
51 match explain_region_and_span(cx, region) {
52 (ref str, Some(span)) => {
55 format!("{}{}{}", prefix, *str, suffix).as_slice());
60 format!("{}{}{}", prefix, *str, suffix).as_slice());
66 /// When a free region is associated with `item`, how should we describe the item in the error
68 fn item_scope_tag(item: &ast::Item) -> &'static str {
70 ast::ItemImpl(..) => "impl",
71 ast::ItemStruct(..) => "struct",
72 ast::ItemEnum(..) => "enum",
73 ast::ItemTrait(..) => "trait",
74 ast::ItemFn(..) => "function body",
79 pub fn explain_region_and_span(cx: &ctxt, region: ty::Region)
80 -> (String, Option<Span>) {
83 match cx.map.find(scope.node_id()) {
84 Some(ast_map::NodeBlock(ref blk)) => {
85 explain_span(cx, "block", blk.span)
87 Some(ast_map::NodeExpr(expr)) => {
89 ast::ExprCall(..) => explain_span(cx, "call", expr.span),
90 ast::ExprMethodCall(..) => {
91 explain_span(cx, "method call", expr.span)
93 ast::ExprMatch(_, _, ast::MatchIfLetDesugar) => explain_span(cx, "if let", expr.span),
94 ast::ExprMatch(_, _, ast::MatchWhileLetDesugar) => {
95 explain_span(cx, "while let", expr.span)
97 ast::ExprMatch(..) => explain_span(cx, "match", expr.span),
98 _ => explain_span(cx, "expression", expr.span)
101 Some(ast_map::NodeStmt(stmt)) => {
102 explain_span(cx, "statement", stmt.span)
104 Some(ast_map::NodeItem(it)) => {
105 let tag = item_scope_tag(&*it);
106 explain_span(cx, tag, it.span)
109 // this really should not happen
110 (format!("unknown scope: {}. Please report a bug.", scope), None)
116 let prefix = match fr.bound_region {
118 format!("the anonymous lifetime #{} defined on", idx + 1)
120 BrFresh(_) => "an anonymous lifetime defined on".to_string(),
122 format!("the lifetime {} as defined on",
123 bound_region_ptr_to_string(cx, fr.bound_region))
127 match cx.map.find(fr.scope.node_id()) {
128 Some(ast_map::NodeBlock(ref blk)) => {
129 let (msg, opt_span) = explain_span(cx, "block", blk.span);
130 (format!("{} {}", prefix, msg), opt_span)
132 Some(ast_map::NodeItem(it)) => {
133 let tag = item_scope_tag(&*it);
134 let (msg, opt_span) = explain_span(cx, tag, it.span);
135 (format!("{} {}", prefix, msg), opt_span)
138 // this really should not happen
139 (format!("{} unknown free region bounded by scope {}", prefix, fr.scope), None)
144 ReStatic => { ("the static lifetime".to_string(), None) }
146 ReEmpty => { ("the empty lifetime".to_string(), None) }
148 ReEarlyBound(_, _, _, name) => {
149 (format!("{}", token::get_name(name)), None)
152 // I believe these cases should not occur (except when debugging,
154 ty::ReInfer(_) | ty::ReLateBound(..) => {
155 (format!("lifetime {}", region), None)
159 fn explain_span(cx: &ctxt, heading: &str, span: Span)
160 -> (String, Option<Span>) {
161 let lo = cx.sess.codemap().lookup_char_pos_adj(span.lo);
162 (format!("the {} at {}:{}", heading, lo.line, lo.col.to_uint()),
167 pub fn bound_region_ptr_to_string(cx: &ctxt, br: BoundRegion) -> String {
168 bound_region_to_string(cx, "", false, br)
171 pub fn bound_region_to_string(cx: &ctxt,
172 prefix: &str, space: bool,
173 br: BoundRegion) -> String {
174 let space_str = if space { " " } else { "" };
176 if cx.sess.verbose() {
177 return format!("{}{}{}", prefix, br.repr(cx), space_str)
181 BrNamed(_, name) => {
182 format!("{}{}{}", prefix, token::get_name(name), space_str)
184 BrAnon(_) | BrFresh(_) | BrEnv => prefix.to_string()
188 // In general, if you are giving a region error message,
189 // you should use `explain_region()` or, better yet,
190 // `note_and_explain_region()`
191 pub fn region_ptr_to_string(cx: &ctxt, region: Region) -> String {
192 region_to_string(cx, "&", true, region)
195 pub fn region_to_string(cx: &ctxt, prefix: &str, space: bool, region: Region) -> String {
196 let space_str = if space { " " } else { "" };
198 if cx.sess.verbose() {
199 return format!("{}{}{}", prefix, region.repr(cx), space_str)
202 // These printouts are concise. They do not contain all the information
203 // the user might want to diagnose an error, but there is basically no way
204 // to fit that into a short string. Hence the recommendation to use
205 // `explain_region()` or `note_and_explain_region()`.
207 ty::ReScope(_) => prefix.to_string(),
208 ty::ReEarlyBound(_, _, _, name) => {
209 token::get_name(name).get().to_string()
211 ty::ReLateBound(_, br) => bound_region_to_string(cx, prefix, space, br),
212 ty::ReFree(ref fr) => bound_region_to_string(cx, prefix, space, fr.bound_region),
213 ty::ReInfer(ReSkolemized(_, br)) => {
214 bound_region_to_string(cx, prefix, space, br)
216 ty::ReInfer(ReVar(_)) => prefix.to_string(),
217 ty::ReStatic => format!("{}'static{}", prefix, space_str),
218 ty::ReEmpty => format!("{}'<empty>{}", prefix, space_str),
222 pub fn mutability_to_string(m: ast::Mutability) -> String {
224 ast::MutMutable => "mut ".to_string(),
225 ast::MutImmutable => "".to_string(),
229 pub fn mt_to_string<'tcx>(cx: &ctxt<'tcx>, m: &mt<'tcx>) -> String {
231 mutability_to_string(m.mutbl),
232 ty_to_string(cx, m.ty))
235 pub fn trait_store_to_string(cx: &ctxt, s: ty::TraitStore) -> String {
237 ty::UniqTraitStore => "Box ".to_string(),
238 ty::RegionTraitStore(r, m) => {
239 format!("{}{}", region_ptr_to_string(cx, r), mutability_to_string(m))
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(", "))
249 pub fn fn_sig_to_string<'tcx>(cx: &ctxt<'tcx>, typ: &ty::FnSig<'tcx>) -> String {
250 format!("fn{} -> {}", typ.inputs.repr(cx), typ.output.repr(cx))
253 pub fn trait_ref_to_string<'tcx>(cx: &ctxt<'tcx>,
254 trait_ref: &ty::TraitRef<'tcx>) -> String {
255 trait_ref.user_string(cx).to_string()
258 pub fn ty_to_string<'tcx>(cx: &ctxt<'tcx>, typ: &ty::TyS<'tcx>) -> String {
259 fn bare_fn_to_string<'tcx>(cx: &ctxt<'tcx>,
260 fn_style: ast::FnStyle,
262 ident: Option<ast::Ident>,
263 sig: &ty::FnSig<'tcx>)
265 let mut s = String::new();
269 s.push_str(fn_style.to_string().as_slice());
274 if abi != abi::Rust {
275 s.push_str(format!("extern {} ", abi.to_string()).as_slice());
283 s.push_str(token::get_ident(i).get());
288 push_sig_to_string(cx, &mut s, '(', ')', sig, "");
293 fn closure_to_string<'tcx>(cx: &ctxt<'tcx>, cty: &ty::ClosureTy<'tcx>) -> String {
294 let mut s = String::new();
297 ty::UniqTraitStore => {}
298 ty::RegionTraitStore(region, _) => {
299 s.push_str(region_to_string(cx, "", true, region).as_slice());
306 s.push_str(cty.fn_style.to_string().as_slice());
311 let bounds_str = cty.bounds.user_string(cx);
314 ty::UniqTraitStore => {
315 assert_eq!(cty.onceness, ast::Once);
317 push_sig_to_string(cx, &mut s, '(', ')', &cty.sig,
318 bounds_str.as_slice());
320 ty::RegionTraitStore(..) => {
323 ast::Once => s.push_str("once ")
325 push_sig_to_string(cx, &mut s, '|', '|', &cty.sig,
326 bounds_str.as_slice());
333 fn push_sig_to_string<'tcx>(cx: &ctxt<'tcx>,
337 sig: &ty::FnSig<'tcx>,
340 let strs = sig.inputs
342 .map(|a| ty_to_string(cx, *a))
343 .collect::<Vec<_>>();
344 s.push_str(strs.connect(", ").as_slice());
350 if !bounds.is_empty() {
356 ty::FnConverging(t) => {
357 if !ty::type_is_nil(t) {
359 s.push_str(ty_to_string(cx, t).as_slice());
368 fn infer_ty_to_string(cx: &ctxt, ty: ty::InferTy) -> String {
369 let print_var_ids = cx.sess.verbose();
371 ty::TyVar(ref vid) if print_var_ids => vid.repr(cx),
372 ty::IntVar(ref vid) if print_var_ids => vid.repr(cx),
373 ty::FloatVar(ref vid) if print_var_ids => vid.repr(cx),
374 ty::TyVar(_) | ty::IntVar(_) | ty::FloatVar(_) => format!("_"),
375 ty::SkolemizedTy(v) => format!("SkolemizedTy({})", v),
376 ty::SkolemizedIntTy(v) => format!("SkolemizedIntTy({})", v)
380 // pretty print the structural type representation:
382 ty_bool => "bool".to_string(),
383 ty_char => "char".to_string(),
384 ty_int(t) => ast_util::int_ty_to_string(t, None).to_string(),
385 ty_uint(t) => ast_util::uint_ty_to_string(t, None).to_string(),
386 ty_float(t) => ast_util::float_ty_to_string(t).to_string(),
387 ty_uniq(typ) => format!("Box<{}>", ty_to_string(cx, typ)),
389 format!("*{} {}", match tm.mutbl {
390 ast::MutMutable => "mut",
391 ast::MutImmutable => "const",
392 }, ty_to_string(cx, tm.ty))
394 ty_rptr(r, ref tm) => {
395 let mut buf = region_ptr_to_string(cx, r);
396 buf.push_str(mt_to_string(cx, tm).as_slice());
400 format!("opened<{}>", ty_to_string(cx, typ)),
401 ty_tup(ref elems) => {
404 .map(|elem| ty_to_string(cx, *elem))
405 .collect::<Vec<_>>();
406 match strs.as_slice() {
407 [ref string] => format!("({},)", string),
408 strs => format!("({})", strs.connect(", "))
411 ty_closure(ref f) => {
412 closure_to_string(cx, &**f)
414 ty_bare_fn(ref f) => {
415 bare_fn_to_string(cx, f.fn_style, f.abi, None, &f.sig)
417 ty_infer(infer_ty) => infer_ty_to_string(cx, infer_ty),
418 ty_err => "[type error]".to_string(),
419 ty_param(ref param_ty) => {
420 if cx.sess.verbose() {
423 param_ty.user_string(cx)
426 ty_enum(did, ref substs) | ty_struct(did, ref substs) => {
427 let base = ty::item_path_str(cx, did);
428 let generics = ty::lookup_item_type(cx, did).generics;
429 parameterized(cx, base.as_slice(), substs, &generics)
431 ty_trait(box ty::TyTrait {
432 ref principal, ref bounds
434 let base = ty::item_path_str(cx, principal.def_id);
435 let trait_def = ty::lookup_trait_def(cx, principal.def_id);
436 let ty = parameterized(cx, base.as_slice(),
437 &principal.substs, &trait_def.generics);
438 let bound_str = bounds.user_string(cx);
439 let bound_sep = if bound_str.is_empty() { "" } else { "+" };
445 ty_str => "str".to_string(),
446 ty_unboxed_closure(ref did, _, ref substs) => {
447 let unboxed_closures = cx.unboxed_closures.borrow();
448 unboxed_closures.get(did).map(|cl| {
449 closure_to_string(cx, &cl.closure_type.subst(cx, substs))
450 }).unwrap_or_else(|| "closure".to_string())
453 let inner_str = ty_to_string(cx, t);
455 Some(n) => format!("[{}, ..{}]", inner_str, n),
456 None => format!("[{}]", inner_str),
462 pub fn explicit_self_category_to_str(category: &ty::ExplicitSelfCategory)
465 ty::StaticExplicitSelfCategory => "static",
466 ty::ByValueExplicitSelfCategory => "self",
467 ty::ByReferenceExplicitSelfCategory(_, ast::MutMutable) => {
470 ty::ByReferenceExplicitSelfCategory(_, ast::MutImmutable) => "&self",
471 ty::ByBoxExplicitSelfCategory => "Box<self>",
475 pub fn parameterized<'tcx>(cx: &ctxt<'tcx>,
477 substs: &subst::Substs<'tcx>,
478 generics: &ty::Generics<'tcx>)
481 if cx.sess.verbose() {
482 if substs.is_noop() {
483 return format!("{}", base);
485 return format!("{}<{},{}>",
487 substs.regions.repr(cx),
488 substs.types.repr(cx));
492 let mut strs = Vec::new();
494 match substs.regions {
495 subst::ErasedRegions => { }
496 subst::NonerasedRegions(ref regions) => {
497 for &r in regions.iter() {
498 let s = region_to_string(cx, "", false, r);
500 // This happens when the value of the region
501 // parameter is not easily serialized. This may be
502 // because the user omitted it in the first place,
503 // or because it refers to some block in the code,
504 // etc. I'm not sure how best to serialize this.
505 strs.push(format!("'_"));
513 let tps = substs.types.get_slice(subst::TypeSpace);
514 let ty_params = generics.types.get_slice(subst::TypeSpace);
515 let has_defaults = ty_params.last().map_or(false, |def| def.default.is_some());
516 let num_defaults = if has_defaults {
517 ty_params.iter().zip(tps.iter()).rev().take_while(|&(def, &actual)| {
519 Some(default) => default.subst(cx, substs) == actual,
527 for t in tps[..tps.len() - num_defaults].iter() {
528 strs.push(ty_to_string(cx, *t))
532 format!("{}<{}>", base, strs.connect(", "))
538 pub fn ty_to_short_str<'tcx>(cx: &ctxt<'tcx>, typ: Ty<'tcx>) -> String {
539 let mut s = typ.repr(cx).to_string();
541 s = s.as_slice().slice(0u, 32u).to_string();
546 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for Option<T> {
547 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
549 &None => "None".to_string(),
550 &Some(ref t) => t.repr(tcx),
555 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for P<T> {
556 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
561 impl<'tcx,T:Repr<'tcx>,U:Repr<'tcx>> Repr<'tcx> for Result<T,U> {
562 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
564 &Ok(ref t) => t.repr(tcx),
565 &Err(ref u) => format!("Err({})", u.repr(tcx))
570 impl<'tcx> Repr<'tcx> for () {
571 fn repr(&self, _tcx: &ctxt) -> String {
576 impl<'a, 'tcx, Sized? T:Repr<'tcx>> Repr<'tcx> for &'a T {
577 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
578 Repr::repr(*self, tcx)
582 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for Rc<T> {
583 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
588 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for Box<T> {
589 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
594 fn repr_vec<'tcx, T:Repr<'tcx>>(tcx: &ctxt<'tcx>, v: &[T]) -> String {
595 vec_map_to_string(v, |t| t.repr(tcx))
598 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for [T] {
599 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
604 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for OwnedSlice<T> {
605 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
606 repr_vec(tcx, self.as_slice())
610 // This is necessary to handle types like Option<~[T]>, for which
611 // autoderef cannot convert the &[T] handler
612 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for Vec<T> {
613 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
614 repr_vec(tcx, self.as_slice())
618 impl<'tcx, T:UserString<'tcx>> UserString<'tcx> for Vec<T> {
619 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
620 let strs: Vec<String> =
621 self.iter().map(|t| t.user_string(tcx)).collect();
626 impl<'tcx> Repr<'tcx> for def::Def {
627 fn repr(&self, _tcx: &ctxt) -> String {
632 impl<'tcx> Repr<'tcx> for ty::TypeParameterDef<'tcx> {
633 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
634 format!("TypeParameterDef({}, {}, {}/{})",
636 self.bounds.repr(tcx),
642 impl<'tcx> Repr<'tcx> for ty::RegionParameterDef {
643 fn repr(&self, tcx: &ctxt) -> String {
644 format!("RegionParameterDef(name={}, def_id={}, bounds={})",
645 token::get_name(self.name),
646 self.def_id.repr(tcx),
647 self.bounds.repr(tcx))
651 impl<'tcx> Repr<'tcx> for ty::TyS<'tcx> {
652 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
653 ty_to_string(tcx, self)
657 impl<'tcx> Repr<'tcx> for ty::mt<'tcx> {
658 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
659 mt_to_string(tcx, self)
663 impl<'tcx> Repr<'tcx> for subst::Substs<'tcx> {
664 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
665 format!("Substs[types={}, regions={}]",
666 self.types.repr(tcx),
667 self.regions.repr(tcx))
671 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for subst::VecPerParamSpace<T> {
672 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
673 format!("[{};{};{};{}]",
674 self.get_slice(subst::TypeSpace).repr(tcx),
675 self.get_slice(subst::SelfSpace).repr(tcx),
676 self.get_slice(subst::AssocSpace).repr(tcx),
677 self.get_slice(subst::FnSpace).repr(tcx))
681 impl<'tcx> Repr<'tcx> for ty::ItemSubsts<'tcx> {
682 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
683 format!("ItemSubsts({})", self.substs.repr(tcx))
687 impl<'tcx> Repr<'tcx> for subst::RegionSubsts {
688 fn repr(&self, tcx: &ctxt) -> String {
690 subst::ErasedRegions => "erased".to_string(),
691 subst::NonerasedRegions(ref regions) => regions.repr(tcx)
696 impl<'tcx> Repr<'tcx> for ty::BuiltinBounds {
697 fn repr(&self, _tcx: &ctxt) -> String {
698 let mut res = Vec::new();
699 for b in self.iter() {
701 ty::BoundSend => "Send".to_string(),
702 ty::BoundSized => "Sized".to_string(),
703 ty::BoundCopy => "Copy".to_string(),
704 ty::BoundSync => "Sync".to_string(),
711 impl<'tcx> Repr<'tcx> for ty::ExistentialBounds {
712 fn repr(&self, tcx: &ctxt) -> String {
713 self.user_string(tcx)
717 impl<'tcx> Repr<'tcx> for ty::ParamBounds<'tcx> {
718 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
719 let mut res = Vec::new();
720 res.push(self.builtin_bounds.repr(tcx));
721 for t in self.trait_bounds.iter() {
722 res.push(t.repr(tcx));
728 impl<'tcx> Repr<'tcx> for ty::TraitRef<'tcx> {
729 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
730 // when printing out the debug representation, we don't need
731 // to enumerate the `for<...>` etc because the debruijn index
732 // tells you everything you need to know.
733 let base = ty::item_path_str(tcx, self.def_id);
734 let trait_def = ty::lookup_trait_def(tcx, self.def_id);
736 self.substs.self_ty().repr(tcx),
737 parameterized(tcx, base.as_slice(), &self.substs, &trait_def.generics))
741 impl<'tcx> Repr<'tcx> for ty::TraitDef<'tcx> {
742 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
743 format!("TraitDef(generics={}, bounds={}, trait_ref={})",
744 self.generics.repr(tcx),
745 self.bounds.repr(tcx),
746 self.trait_ref.repr(tcx))
750 impl<'tcx> Repr<'tcx> for ast::TraitItem {
751 fn repr(&self, _tcx: &ctxt) -> String {
753 ast::RequiredMethod(ref data) => format!("RequiredMethod({}, id={})",
754 data.ident, data.id),
755 ast::ProvidedMethod(ref data) => format!("ProvidedMethod(id={})",
757 ast::TypeTraitItem(ref data) => format!("TypeTraitItem({}, id={})",
758 data.ty_param.ident, data.ty_param.id),
763 impl<'tcx> Repr<'tcx> for ast::Expr {
764 fn repr(&self, _tcx: &ctxt) -> String {
765 format!("expr({}: {})", self.id, pprust::expr_to_string(self))
769 impl<'tcx> Repr<'tcx> for ast::Path {
770 fn repr(&self, _tcx: &ctxt) -> String {
771 format!("path({})", pprust::path_to_string(self))
775 impl<'tcx> UserString<'tcx> for ast::Path {
776 fn user_string(&self, _tcx: &ctxt) -> String {
777 pprust::path_to_string(self)
781 impl<'tcx> Repr<'tcx> for ast::Ty {
782 fn repr(&self, _tcx: &ctxt) -> String {
783 format!("type({})", pprust::ty_to_string(self))
787 impl<'tcx> Repr<'tcx> for ast::Item {
788 fn repr(&self, tcx: &ctxt) -> String {
789 format!("item({})", tcx.map.node_to_string(self.id))
793 impl<'tcx> Repr<'tcx> for ast::Lifetime {
794 fn repr(&self, _tcx: &ctxt) -> String {
795 format!("lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
799 impl<'tcx> Repr<'tcx> for ast::Stmt {
800 fn repr(&self, _tcx: &ctxt) -> String {
801 format!("stmt({}: {})",
802 ast_util::stmt_id(self),
803 pprust::stmt_to_string(self))
807 impl<'tcx> Repr<'tcx> for ast::Pat {
808 fn repr(&self, _tcx: &ctxt) -> String {
809 format!("pat({}: {})", self.id, pprust::pat_to_string(self))
813 impl<'tcx> Repr<'tcx> for ty::BoundRegion {
814 fn repr(&self, tcx: &ctxt) -> String {
816 ty::BrAnon(id) => format!("BrAnon({})", id),
817 ty::BrNamed(id, name) => {
818 format!("BrNamed({}, {})", id.repr(tcx), token::get_name(name))
820 ty::BrFresh(id) => format!("BrFresh({})", id),
821 ty::BrEnv => "BrEnv".to_string()
826 impl<'tcx> Repr<'tcx> for ty::Region {
827 fn repr(&self, tcx: &ctxt) -> String {
829 ty::ReEarlyBound(id, space, index, name) => {
830 format!("ReEarlyBound({}, {}, {}, {})",
834 token::get_name(name))
837 ty::ReLateBound(binder_id, ref bound_region) => {
838 format!("ReLateBound({}, {})",
840 bound_region.repr(tcx))
843 ty::ReFree(ref fr) => fr.repr(tcx),
846 format!("ReScope({})", id)
850 "ReStatic".to_string()
853 ty::ReInfer(ReVar(ref vid)) => {
857 ty::ReInfer(ReSkolemized(id, ref bound_region)) => {
858 format!("re_skolemized({}, {})", id, bound_region.repr(tcx))
862 "ReEmpty".to_string()
868 impl<'tcx> UserString<'tcx> for ty::Region {
869 fn user_string(&self, tcx: &ctxt) -> String {
870 region_to_string(tcx, "", false, *self)
874 impl<'tcx> Repr<'tcx> for ty::FreeRegion {
875 fn repr(&self, tcx: &ctxt) -> String {
876 format!("ReFree({}, {})",
877 self.scope.node_id(),
878 self.bound_region.repr(tcx))
882 impl<'tcx> Repr<'tcx> for ast::DefId {
883 fn repr(&self, tcx: &ctxt) -> String {
884 // Unfortunately, there seems to be no way to attempt to print
885 // a path for a def-id, so I'll just make a best effort for now
886 // and otherwise fallback to just printing the crate/node pair
887 if self.krate == ast::LOCAL_CRATE {
888 match tcx.map.find(self.node) {
889 Some(ast_map::NodeItem(..)) |
890 Some(ast_map::NodeForeignItem(..)) |
891 Some(ast_map::NodeImplItem(..)) |
892 Some(ast_map::NodeTraitItem(..)) |
893 Some(ast_map::NodeVariant(..)) |
894 Some(ast_map::NodeStructCtor(..)) => {
898 ty::item_path_str(tcx, *self))
903 return format!("{}", *self)
907 impl<'tcx> Repr<'tcx> for ty::Polytype<'tcx> {
908 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
909 format!("Polytype {{generics: {}, ty: {}}}",
910 self.generics.repr(tcx),
915 impl<'tcx> Repr<'tcx> for ty::Generics<'tcx> {
916 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
917 format!("Generics(types: {}, regions: {})",
918 self.types.repr(tcx),
919 self.regions.repr(tcx))
923 impl<'tcx> Repr<'tcx> for ty::GenericBounds<'tcx> {
924 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
925 format!("GenericBounds(types: {}, regions: {})",
926 self.types.repr(tcx),
927 self.regions.repr(tcx))
931 impl<'tcx> Repr<'tcx> for ty::ItemVariances {
932 fn repr(&self, tcx: &ctxt) -> String {
933 format!("ItemVariances(types={}, \
935 self.types.repr(tcx),
936 self.regions.repr(tcx))
940 impl<'tcx> Repr<'tcx> for ty::Variance {
941 fn repr(&self, _: &ctxt) -> String {
942 // The first `.to_string()` returns a &'static str (it is not an implementation
943 // of the ToString trait). Because of that, we need to call `.to_string()` again
944 // if we want to have a `String`.
945 let result: &'static str = (*self).to_string();
950 impl<'tcx> Repr<'tcx> for ty::Method<'tcx> {
951 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
952 format!("method(name: {}, generics: {}, fty: {}, \
953 explicit_self: {}, vis: {}, def_id: {})",
955 self.generics.repr(tcx),
957 self.explicit_self.repr(tcx),
959 self.def_id.repr(tcx))
963 impl<'tcx> Repr<'tcx> for ast::Name {
964 fn repr(&self, _tcx: &ctxt) -> String {
965 token::get_name(*self).get().to_string()
969 impl<'tcx> UserString<'tcx> for ast::Name {
970 fn user_string(&self, _tcx: &ctxt) -> String {
971 token::get_name(*self).get().to_string()
975 impl<'tcx> Repr<'tcx> for ast::Ident {
976 fn repr(&self, _tcx: &ctxt) -> String {
977 token::get_ident(*self).get().to_string()
981 impl<'tcx> Repr<'tcx> for ast::ExplicitSelf_ {
982 fn repr(&self, _tcx: &ctxt) -> String {
987 impl<'tcx> Repr<'tcx> for ast::Visibility {
988 fn repr(&self, _tcx: &ctxt) -> String {
993 impl<'tcx> Repr<'tcx> for ty::BareFnTy<'tcx> {
994 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
995 format!("BareFnTy {{fn_style: {}, abi: {}, sig: {}}}",
997 self.abi.to_string(),
1002 impl<'tcx> Repr<'tcx> for ty::FnSig<'tcx> {
1003 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1004 fn_sig_to_string(tcx, self)
1008 impl<'tcx> Repr<'tcx> for ty::FnOutput<'tcx> {
1009 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1011 ty::FnConverging(ty) =>
1012 format!("FnConverging({0})", ty.repr(tcx)),
1014 "FnDiverging".to_string()
1019 impl<'tcx> Repr<'tcx> for ty::MethodCallee<'tcx> {
1020 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1021 format!("MethodCallee {{origin: {}, ty: {}, {}}}",
1022 self.origin.repr(tcx),
1024 self.substs.repr(tcx))
1028 impl<'tcx> Repr<'tcx> for ty::MethodOrigin<'tcx> {
1029 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1031 &ty::MethodStatic(def_id) => {
1032 format!("MethodStatic({})", def_id.repr(tcx))
1034 &ty::MethodStaticUnboxedClosure(def_id) => {
1035 format!("MethodStaticUnboxedClosure({})", def_id.repr(tcx))
1037 &ty::MethodTypeParam(ref p) => {
1040 &ty::MethodTraitObject(ref p) => {
1047 impl<'tcx> Repr<'tcx> for ty::MethodParam<'tcx> {
1048 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1049 format!("MethodParam({},{})",
1050 self.trait_ref.repr(tcx),
1055 impl<'tcx> Repr<'tcx> for ty::MethodObject<'tcx> {
1056 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1057 format!("MethodObject({},{},{})",
1058 self.trait_ref.repr(tcx),
1064 impl<'tcx> Repr<'tcx> for ty::TraitStore {
1065 fn repr(&self, tcx: &ctxt) -> String {
1066 trait_store_to_string(tcx, *self)
1070 impl<'tcx> Repr<'tcx> for ty::BuiltinBound {
1071 fn repr(&self, _tcx: &ctxt) -> String {
1072 format!("{}", *self)
1076 impl<'tcx> UserString<'tcx> for ty::BuiltinBound {
1077 fn user_string(&self, _tcx: &ctxt) -> String {
1079 ty::BoundSend => "Send".to_string(),
1080 ty::BoundSized => "Sized".to_string(),
1081 ty::BoundCopy => "Copy".to_string(),
1082 ty::BoundSync => "Sync".to_string(),
1087 impl<'tcx> Repr<'tcx> for Span {
1088 fn repr(&self, tcx: &ctxt) -> String {
1089 tcx.sess.codemap().span_to_string(*self).to_string()
1093 impl<'tcx, A:UserString<'tcx>> UserString<'tcx> for Rc<A> {
1094 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1095 let this: &A = &**self;
1096 this.user_string(tcx)
1100 impl<'tcx> UserString<'tcx> for ty::ParamBounds<'tcx> {
1101 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1102 let mut result = Vec::new();
1103 let s = self.builtin_bounds.user_string(tcx);
1107 for n in self.trait_bounds.iter() {
1108 result.push(n.user_string(tcx));
1114 impl<'tcx> UserString<'tcx> for ty::ExistentialBounds {
1115 fn user_string(&self, tcx: &ctxt) -> String {
1116 if self.builtin_bounds.contains(&ty::BoundSend) &&
1117 self.region_bound == ty::ReStatic
1118 { // Region bound is implied by builtin bounds:
1119 return self.builtin_bounds.repr(tcx);
1122 let mut res = Vec::new();
1124 let region_str = self.region_bound.user_string(tcx);
1125 if !region_str.is_empty() {
1126 res.push(region_str);
1129 for bound in self.builtin_bounds.iter() {
1130 res.push(bound.user_string(tcx));
1137 impl<'tcx> UserString<'tcx> for ty::BuiltinBounds {
1138 fn user_string(&self, tcx: &ctxt) -> String {
1140 .map(|bb| bb.user_string(tcx))
1141 .collect::<Vec<String>>()
1147 impl<'tcx> UserString<'tcx> for ty::TraitRef<'tcx> {
1148 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1149 // Replace any anonymous late-bound regions with named
1150 // variants, using gensym'd identifiers, so that we can
1151 // clearly differentiate between named and unnamed regions in
1152 // the output. We'll probably want to tweak this over time to
1153 // decide just how much information to give.
1154 let mut names = Vec::new();
1155 let (trait_ref, _) = ty::replace_late_bound_regions(tcx, self, |br, debruijn| {
1156 ty::ReLateBound(debruijn, match br {
1157 ty::BrNamed(_, name) => {
1158 names.push(token::get_name(name));
1164 let name = token::gensym("r");
1165 names.push(token::get_name(name));
1166 ty::BrNamed(ast_util::local_def(ast::DUMMY_NODE_ID), name)
1170 let names: Vec<_> = names.iter().map(|s| s.get()).collect();
1172 // Let the base string be either `SomeTrait` for `for<'a,'b> SomeTrait`,
1173 // depending on whether there are bound regions.
1174 let path_str = ty::item_path_str(tcx, self.def_id);
1176 if names.is_empty() {
1179 format!("for<{}> {}", names.connect(","), path_str)
1182 let trait_def = ty::lookup_trait_def(tcx, self.def_id);
1183 parameterized(tcx, base.as_slice(), &trait_ref.substs, &trait_def.generics)
1187 impl<'tcx> UserString<'tcx> for Ty<'tcx> {
1188 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1189 ty_to_string(tcx, *self)
1193 impl<'tcx> UserString<'tcx> for ast::Ident {
1194 fn user_string(&self, _tcx: &ctxt) -> String {
1195 token::get_name(self.name).get().to_string()
1199 impl<'tcx> Repr<'tcx> for abi::Abi {
1200 fn repr(&self, _tcx: &ctxt) -> String {
1205 impl<'tcx> UserString<'tcx> for abi::Abi {
1206 fn user_string(&self, _tcx: &ctxt) -> String {
1211 impl<'tcx> Repr<'tcx> for ty::UpvarId {
1212 fn repr(&self, tcx: &ctxt) -> String {
1213 format!("UpvarId({};`{}`;{})",
1215 ty::local_var_name_str(tcx, self.var_id),
1216 self.closure_expr_id)
1220 impl<'tcx> Repr<'tcx> for ast::Mutability {
1221 fn repr(&self, _tcx: &ctxt) -> String {
1222 format!("{}", *self)
1226 impl<'tcx> Repr<'tcx> for ty::BorrowKind {
1227 fn repr(&self, _tcx: &ctxt) -> String {
1228 format!("{}", *self)
1232 impl<'tcx> Repr<'tcx> for ty::UpvarBorrow {
1233 fn repr(&self, tcx: &ctxt) -> String {
1234 format!("UpvarBorrow({}, {})",
1235 self.kind.repr(tcx),
1236 self.region.repr(tcx))
1240 impl<'tcx> Repr<'tcx> for ty::IntVid {
1241 fn repr(&self, _tcx: &ctxt) -> String {
1246 impl<'tcx> Repr<'tcx> for ty::FloatVid {
1247 fn repr(&self, _tcx: &ctxt) -> String {
1252 impl<'tcx> Repr<'tcx> for ty::RegionVid {
1253 fn repr(&self, _tcx: &ctxt) -> String {
1258 impl<'tcx> Repr<'tcx> for ty::TyVid {
1259 fn repr(&self, _tcx: &ctxt) -> String {
1264 impl<'tcx> Repr<'tcx> for ty::IntVarValue {
1265 fn repr(&self, _tcx: &ctxt) -> String {
1266 format!("{}", *self)
1270 impl<'tcx> Repr<'tcx> for ast::IntTy {
1271 fn repr(&self, _tcx: &ctxt) -> String {
1272 format!("{}", *self)
1276 impl<'tcx> Repr<'tcx> for ast::UintTy {
1277 fn repr(&self, _tcx: &ctxt) -> String {
1278 format!("{}", *self)
1282 impl<'tcx> Repr<'tcx> for ast::FloatTy {
1283 fn repr(&self, _tcx: &ctxt) -> String {
1284 format!("{}", *self)
1288 impl<'tcx> Repr<'tcx> for ty::ExplicitSelfCategory {
1289 fn repr(&self, _: &ctxt) -> String {
1290 explicit_self_category_to_str(self).to_string()
1294 impl<'tcx> UserString<'tcx> for ParamTy {
1295 fn user_string(&self, tcx: &ctxt) -> String {
1297 let did = self.def_id;
1298 let ident = match tcx.ty_param_defs.borrow().get(&did.node) {
1299 Some(def) => token::get_name(def.name).get().to_string(),
1301 // This can only happen when a type mismatch error happens and
1302 // the actual type has more type parameters than the expected one.
1303 None => format!("<generic #{}>", id),
1309 impl<'tcx> Repr<'tcx> for ParamTy {
1310 fn repr(&self, tcx: &ctxt) -> String {
1311 let ident = self.user_string(tcx);
1312 format!("{}/{}.{}", ident, self.space, self.idx)
1316 impl<'tcx, A:Repr<'tcx>, B:Repr<'tcx>> Repr<'tcx> for (A,B) {
1317 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1318 let &(ref a, ref b) = self;
1319 format!("({},{})", a.repr(tcx), b.repr(tcx))
1323 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for ty::Binder<T> {
1324 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1325 format!("Binder({})", self.value.repr(tcx))