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.
14 use middle::subst::{VecPerParamSpace,Subst};
16 use middle::ty::{BoundRegion, BrAnon, BrNamed};
17 use middle::ty::{ReEarlyBound, BrFresh, ctxt};
18 use middle::ty::{ReFree, ReScope, ReInfer, ReStatic, Region, ReEmpty};
19 use middle::ty::{ReSkolemized, ReVar, BrEnv};
20 use middle::ty::{mt, Ty, ParamTy};
21 use middle::ty::{ty_bool, ty_char, ty_struct, ty_enum};
22 use middle::ty::{ty_err, ty_str, ty_vec, ty_float, ty_bare_fn};
23 use middle::ty::{ty_param, ty_ptr, ty_rptr, ty_tup, ty_open};
24 use middle::ty::{ty_closure};
25 use middle::ty::{ty_uniq, ty_trait, ty_int, ty_uint, ty_infer};
27 use middle::ty_fold::TypeFoldable;
29 use std::collections::HashMap;
30 use std::collections::hash_state::HashState;
32 #[cfg(stage0)] use std::hash::Hasher;
36 use syntax::codemap::{Span, Pos};
37 use syntax::parse::token;
38 use syntax::print::pprust;
40 use syntax::{ast, ast_util};
41 use syntax::owned_slice::OwnedSlice;
43 /// Produces a string suitable for debugging output.
44 pub trait Repr<'tcx> {
45 fn repr(&self, tcx: &ctxt<'tcx>) -> String;
48 /// Produces a string suitable for showing to the user.
49 pub trait UserString<'tcx> : Repr<'tcx> {
50 fn user_string(&self, tcx: &ctxt<'tcx>) -> String;
53 pub fn note_and_explain_region(cx: &ctxt,
56 suffix: &str) -> Option<Span> {
57 match explain_region_and_span(cx, region) {
58 (ref str, Some(span)) => {
61 &format!("{}{}{}", prefix, *str, suffix)[]);
66 &format!("{}{}{}", prefix, *str, suffix)[]);
72 /// When a free region is associated with `item`, how should we describe the item in the error
74 fn item_scope_tag(item: &ast::Item) -> &'static str {
76 ast::ItemImpl(..) => "impl",
77 ast::ItemStruct(..) => "struct",
78 ast::ItemEnum(..) => "enum",
79 ast::ItemTrait(..) => "trait",
80 ast::ItemFn(..) => "function body",
85 pub fn explain_region_and_span(cx: &ctxt, region: ty::Region)
86 -> (String, Option<Span>) {
90 let on_unknown_scope = || {
91 (format!("unknown scope: {:?}. Please report a bug.", scope), None)
93 let span = match scope.span(&cx.map) {
95 None => return on_unknown_scope(),
97 let tag = match cx.map.find(scope.node_id()) {
98 Some(ast_map::NodeBlock(_)) => "block",
99 Some(ast_map::NodeExpr(expr)) => match expr.node {
100 ast::ExprCall(..) => "call",
101 ast::ExprMethodCall(..) => "method call",
102 ast::ExprMatch(_, _, ast::MatchSource::IfLetDesugar { .. }) => "if let",
103 ast::ExprMatch(_, _, ast::MatchSource::WhileLetDesugar) => "while let",
104 ast::ExprMatch(_, _, ast::MatchSource::ForLoopDesugar) => "for",
105 ast::ExprMatch(..) => "match",
108 Some(ast_map::NodeStmt(_)) => "statement",
109 Some(ast_map::NodeItem(it)) => item_scope_tag(&*it),
111 // this really should not happen
112 return on_unknown_scope();
115 let scope_decorated_tag = match scope {
116 region::CodeExtent::Misc(_) => tag,
117 region::CodeExtent::DestructionScope(_) => {
118 new_string = format!("destruction scope surrounding {}", tag);
119 new_string.as_slice()
121 region::CodeExtent::Remainder(r) => {
122 new_string = format!("block suffix following statement {}",
123 r.first_statement_index);
127 explain_span(cx, scope_decorated_tag, span)
132 let prefix = match fr.bound_region {
134 format!("the anonymous lifetime #{} defined on", idx + 1)
136 BrFresh(_) => "an anonymous lifetime defined on".to_string(),
138 format!("the lifetime {} as defined on",
139 bound_region_ptr_to_string(cx, fr.bound_region))
143 match cx.map.find(fr.scope.node_id) {
144 Some(ast_map::NodeBlock(ref blk)) => {
145 let (msg, opt_span) = explain_span(cx, "block", blk.span);
146 (format!("{} {}", prefix, msg), opt_span)
148 Some(ast_map::NodeItem(it)) => {
149 let tag = item_scope_tag(&*it);
150 let (msg, opt_span) = explain_span(cx, tag, it.span);
151 (format!("{} {}", prefix, msg), opt_span)
154 // this really should not happen
155 (format!("{} unknown free region bounded by scope {:?}", prefix, fr.scope), None)
160 ReStatic => { ("the static lifetime".to_string(), None) }
162 ReEmpty => { ("the empty lifetime".to_string(), None) }
164 ReEarlyBound(_, _, _, name) => {
165 (format!("{}", token::get_name(name)), None)
168 // I believe these cases should not occur (except when debugging,
170 ty::ReInfer(_) | ty::ReLateBound(..) => {
171 (format!("lifetime {:?}", region), None)
175 fn explain_span(cx: &ctxt, heading: &str, span: Span)
176 -> (String, Option<Span>) {
177 let lo = cx.sess.codemap().lookup_char_pos_adj(span.lo);
178 (format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize()),
183 pub fn bound_region_ptr_to_string(cx: &ctxt, br: BoundRegion) -> String {
184 bound_region_to_string(cx, "", false, br)
187 pub fn bound_region_to_string(cx: &ctxt,
188 prefix: &str, space: bool,
189 br: BoundRegion) -> String {
190 let space_str = if space { " " } else { "" };
192 if cx.sess.verbose() {
193 return format!("{}{}{}", prefix, br.repr(cx), space_str)
197 BrNamed(_, name) => {
198 format!("{}{}{}", prefix, token::get_name(name), space_str)
200 BrAnon(_) | BrFresh(_) | BrEnv => prefix.to_string()
204 // In general, if you are giving a region error message,
205 // you should use `explain_region()` or, better yet,
206 // `note_and_explain_region()`
207 pub fn region_ptr_to_string(cx: &ctxt, region: Region) -> String {
208 region_to_string(cx, "&", true, region)
211 pub fn region_to_string(cx: &ctxt, prefix: &str, space: bool, region: Region) -> String {
212 let space_str = if space { " " } else { "" };
214 if cx.sess.verbose() {
215 return format!("{}{}{}", prefix, region.repr(cx), space_str)
218 // These printouts are concise. They do not contain all the information
219 // the user might want to diagnose an error, but there is basically no way
220 // to fit that into a short string. Hence the recommendation to use
221 // `explain_region()` or `note_and_explain_region()`.
223 ty::ReScope(_) => prefix.to_string(),
224 ty::ReEarlyBound(_, _, _, name) => {
225 token::get_name(name).to_string()
227 ty::ReLateBound(_, br) => bound_region_to_string(cx, prefix, space, br),
228 ty::ReFree(ref fr) => bound_region_to_string(cx, prefix, space, fr.bound_region),
229 ty::ReInfer(ReSkolemized(_, br)) => {
230 bound_region_to_string(cx, prefix, space, br)
232 ty::ReInfer(ReVar(_)) => prefix.to_string(),
233 ty::ReStatic => format!("{}'static{}", prefix, space_str),
234 ty::ReEmpty => format!("{}'<empty>{}", prefix, space_str),
238 pub fn mutability_to_string(m: ast::Mutability) -> String {
240 ast::MutMutable => "mut ".to_string(),
241 ast::MutImmutable => "".to_string(),
245 pub fn mt_to_string<'tcx>(cx: &ctxt<'tcx>, m: &mt<'tcx>) -> String {
247 mutability_to_string(m.mutbl),
248 ty_to_string(cx, m.ty))
251 pub fn vec_map_to_string<T, F>(ts: &[T], f: F) -> String where
252 F: FnMut(&T) -> String,
254 let tstrs = ts.iter().map(f).collect::<Vec<String>>();
255 format!("[{}]", tstrs.connect(", "))
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 opt_def_id: Option<ast::DefId>,
261 unsafety: ast::Unsafety,
263 ident: Option<ast::Ident>,
264 sig: &ty::PolyFnSig<'tcx>)
266 let mut s = String::new();
269 ast::Unsafety::Normal => {}
270 ast::Unsafety::Unsafe => {
271 s.push_str(&unsafety.to_string());
276 if abi != abi::Rust {
277 s.push_str(&format!("extern {} ", abi.to_string())[]);
285 s.push_str(&token::get_ident(i));
290 push_sig_to_string(cx, &mut s, '(', ')', sig);
295 let path_str = ty::item_path_str(cx, def_id);
296 s.push_str(&path_str[..]);
305 fn closure_to_string<'tcx>(cx: &ctxt<'tcx>, cty: &ty::ClosureTy<'tcx>) -> String {
306 let mut s = String::new();
307 s.push_str("[closure");
308 push_sig_to_string(cx, &mut s, '(', ')', &cty.sig);
313 fn push_sig_to_string<'tcx>(cx: &ctxt<'tcx>,
317 sig: &ty::PolyFnSig<'tcx>) {
319 let strs = sig.0.inputs
321 .map(|a| ty_to_string(cx, *a))
322 .collect::<Vec<_>>();
323 s.push_str(&strs.connect(", "));
330 ty::FnConverging(t) => {
331 if !ty::type_is_nil(t) {
333 s.push_str(&ty_to_string(cx, t)[]);
342 fn infer_ty_to_string(cx: &ctxt, ty: ty::InferTy) -> String {
343 let print_var_ids = cx.sess.verbose();
345 ty::TyVar(ref vid) if print_var_ids => vid.repr(cx),
346 ty::IntVar(ref vid) if print_var_ids => vid.repr(cx),
347 ty::FloatVar(ref vid) if print_var_ids => vid.repr(cx),
348 ty::TyVar(_) | ty::IntVar(_) | ty::FloatVar(_) => format!("_"),
349 ty::FreshTy(v) => format!("FreshTy({})", v),
350 ty::FreshIntTy(v) => format!("FreshIntTy({})", v)
354 // pretty print the structural type representation:
356 ty_bool => "bool".to_string(),
357 ty_char => "char".to_string(),
358 ty_int(t) => ast_util::int_ty_to_string(t, None).to_string(),
359 ty_uint(t) => ast_util::uint_ty_to_string(t, None).to_string(),
360 ty_float(t) => ast_util::float_ty_to_string(t).to_string(),
361 ty_uniq(typ) => format!("Box<{}>", ty_to_string(cx, typ)),
363 format!("*{} {}", match tm.mutbl {
364 ast::MutMutable => "mut",
365 ast::MutImmutable => "const",
366 }, ty_to_string(cx, tm.ty))
368 ty_rptr(r, ref tm) => {
369 let mut buf = region_ptr_to_string(cx, *r);
370 buf.push_str(&mt_to_string(cx, tm)[]);
374 format!("opened<{}>", ty_to_string(cx, typ)),
375 ty_tup(ref elems) => {
378 .map(|elem| ty_to_string(cx, *elem))
379 .collect::<Vec<_>>();
381 [ref string] => format!("({},)", string),
382 strs => format!("({})", strs.connect(", "))
385 ty_bare_fn(opt_def_id, ref f) => {
386 bare_fn_to_string(cx, opt_def_id, f.unsafety, f.abi, None, &f.sig)
388 ty_infer(infer_ty) => infer_ty_to_string(cx, infer_ty),
389 ty_err => "[type error]".to_string(),
390 ty_param(ref param_ty) => {
391 if cx.sess.verbose() {
394 param_ty.user_string(cx)
397 ty_enum(did, substs) | ty_struct(did, substs) => {
398 let base = ty::item_path_str(cx, did);
399 parameterized(cx, &base, substs, did, &[],
400 || ty::lookup_item_type(cx, did).generics)
402 ty_trait(ref data) => {
405 ty::ty_projection(ref data) => {
406 format!("<{} as {}>::{}",
407 data.trait_ref.self_ty().user_string(cx),
408 data.trait_ref.user_string(cx),
409 data.item_name.user_string(cx))
411 ty_str => "str".to_string(),
412 ty_closure(ref did, _, substs) => {
413 let closure_tys = cx.closure_tys.borrow();
414 closure_tys.get(did).map(|closure_type| {
415 closure_to_string(cx, &closure_type.subst(cx, substs))
416 }).unwrap_or_else(|| {
417 if did.krate == ast::LOCAL_CRATE {
418 let span = cx.map.span(did.node);
419 format!("[closure {}]", span.repr(cx))
426 let inner_str = ty_to_string(cx, t);
428 Some(n) => format!("[{}; {}]", inner_str, n),
429 None => format!("[{}]", inner_str),
435 pub fn explicit_self_category_to_str(category: &ty::ExplicitSelfCategory)
438 ty::StaticExplicitSelfCategory => "static",
439 ty::ByValueExplicitSelfCategory => "self",
440 ty::ByReferenceExplicitSelfCategory(_, ast::MutMutable) => {
443 ty::ByReferenceExplicitSelfCategory(_, ast::MutImmutable) => "&self",
444 ty::ByBoxExplicitSelfCategory => "Box<self>",
448 pub fn parameterized<'tcx,GG>(cx: &ctxt<'tcx>,
450 substs: &subst::Substs<'tcx>,
452 projections: &[ty::ProjectionPredicate<'tcx>],
455 where GG : FnOnce() -> ty::Generics<'tcx>
457 if cx.sess.verbose() {
458 let mut strings = vec![];
459 match substs.regions {
460 subst::ErasedRegions => {
461 strings.push(format!(".."));
463 subst::NonerasedRegions(ref regions) => {
464 for region in regions.iter() {
465 strings.push(region.repr(cx));
469 for ty in substs.types.iter() {
470 strings.push(ty.repr(cx));
472 for projection in projections.iter() {
473 strings.push(format!("{}={}",
474 projection.projection_ty.item_name.user_string(cx),
475 projection.ty.user_string(cx)));
477 return if strings.is_empty() {
480 format!("{}<{}>", base, strings.connect(","))
484 let mut strs = Vec::new();
486 match substs.regions {
487 subst::ErasedRegions => { }
488 subst::NonerasedRegions(ref regions) => {
489 for &r in regions.iter() {
490 let s = region_to_string(cx, "", false, r);
492 // This happens when the value of the region
493 // parameter is not easily serialized. This may be
494 // because the user omitted it in the first place,
495 // or because it refers to some block in the code,
496 // etc. I'm not sure how best to serialize this.
497 strs.push(format!("'_"));
505 // It is important to execute this conditionally, only if -Z
506 // verbose is false. Otherwise, debug logs can sometimes cause
507 // ICEs trying to fetch the generics early in the pipeline. This
508 // is kind of a hacky workaround in that -Z verbose is required to
510 let generics = get_generics();
512 let has_self = substs.self_ty().is_some();
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)| {
520 if !has_self && ty::type_has_self(default) {
521 // In an object type, there is no `Self`, and
522 // thus if the default value references Self,
523 // the user will be required to give an
524 // explicit value. We can't even do the
525 // substitution below to check without causing
529 default.subst(cx, substs) == actual
539 for t in &tps[..tps.len() - num_defaults] {
540 strs.push(ty_to_string(cx, *t))
543 for projection in projections {
544 strs.push(format!("{}={}",
545 projection.projection_ty.item_name.user_string(cx),
546 projection.ty.user_string(cx)));
549 if cx.lang_items.fn_trait_kind(did).is_some() && projections.len() == 1 {
550 let projection_ty = projections[0].ty;
552 if ty::type_is_nil(projection_ty) {
555 format!(" -> {}", projection_ty.user_string(cx))
559 if strs[0].starts_with("(") && strs[0].ends_with(",)") {
560 &strs[0][1 .. strs[0].len() - 2] // Remove '(' and ',)'
561 } else if strs[0].starts_with("(") && strs[0].ends_with(")") {
562 &strs[0][1 .. strs[0].len() - 1] // Remove '(' and ')'
567 } else if strs.len() > 0 {
568 format!("{}<{}>", base, strs.connect(", "))
574 pub fn ty_to_short_str<'tcx>(cx: &ctxt<'tcx>, typ: Ty<'tcx>) -> String {
575 let mut s = typ.repr(cx).to_string();
577 s = (&s[0..32]).to_string();
582 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for Option<T> {
583 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
585 &None => "None".to_string(),
586 &Some(ref t) => t.repr(tcx),
591 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for P<T> {
592 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
597 impl<'tcx,T:Repr<'tcx>,U:Repr<'tcx>> Repr<'tcx> for Result<T,U> {
598 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
600 &Ok(ref t) => t.repr(tcx),
601 &Err(ref u) => format!("Err({})", u.repr(tcx))
606 impl<'tcx> Repr<'tcx> for () {
607 fn repr(&self, _tcx: &ctxt) -> String {
612 impl<'a, 'tcx, T: ?Sized +Repr<'tcx>> Repr<'tcx> for &'a T {
613 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
614 Repr::repr(*self, tcx)
618 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for Rc<T> {
619 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
624 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for Box<T> {
625 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
630 fn repr_vec<'tcx, T:Repr<'tcx>>(tcx: &ctxt<'tcx>, v: &[T]) -> String {
631 vec_map_to_string(v, |t| t.repr(tcx))
634 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for [T] {
635 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
640 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for OwnedSlice<T> {
641 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
642 repr_vec(tcx, &self[..])
646 // This is necessary to handle types like Option<~[T]>, for which
647 // autoderef cannot convert the &[T] handler
648 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for Vec<T> {
649 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
650 repr_vec(tcx, &self[..])
654 impl<'tcx, T:UserString<'tcx>> UserString<'tcx> for Vec<T> {
655 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
656 let strs: Vec<String> =
657 self.iter().map(|t| t.user_string(tcx)).collect();
662 impl<'tcx> Repr<'tcx> for def::Def {
663 fn repr(&self, _tcx: &ctxt) -> String {
664 format!("{:?}", *self)
668 /// This curious type is here to help pretty-print trait objects. In
669 /// a trait object, the projections are stored separately from the
670 /// main trait bound, but in fact we want to package them together
671 /// when printing out; they also have separate binders, but we want
672 /// them to share a binder when we print them out. (And the binder
673 /// pretty-printing logic is kind of clever and we don't want to
674 /// reproduce it.) So we just repackage up the structure somewhat.
676 /// Right now there is only one trait in an object that can have
677 /// projection bounds, so we just stuff them altogether. But in
678 /// reality we should eventually sort things out better.
679 type TraitAndProjections<'tcx> =
680 (Rc<ty::TraitRef<'tcx>>, Vec<ty::ProjectionPredicate<'tcx>>);
682 impl<'tcx> UserString<'tcx> for TraitAndProjections<'tcx> {
683 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
684 let &(ref trait_ref, ref projection_bounds) = self;
685 let base = ty::item_path_str(tcx, trait_ref.def_id);
690 &projection_bounds[..],
691 || ty::lookup_trait_def(tcx, trait_ref.def_id).generics.clone())
695 impl<'tcx> UserString<'tcx> for ty::TyTrait<'tcx> {
696 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
697 let &ty::TyTrait { ref principal, ref bounds } = self;
699 let mut components = vec![];
701 let tap: ty::Binder<TraitAndProjections<'tcx>> =
702 ty::Binder((principal.0.clone(),
703 bounds.projection_bounds.iter().map(|x| x.0.clone()).collect()));
705 // Generate the main trait ref, including associated types.
706 components.push(tap.user_string(tcx));
709 for bound in &bounds.builtin_bounds {
710 components.push(bound.user_string(tcx));
713 // Region, if not obviously implied by builtin bounds.
714 if bounds.region_bound != ty::ReStatic {
715 // Region bound is implied by builtin bounds:
716 components.push(bounds.region_bound.user_string(tcx));
719 components.retain(|s| !s.is_empty());
721 components.connect(" + ")
725 impl<'tcx> Repr<'tcx> for ty::TypeParameterDef<'tcx> {
726 fn repr(&self, _tcx: &ctxt<'tcx>) -> String {
727 format!("TypeParameterDef({:?}, {:?}/{})",
734 impl<'tcx> Repr<'tcx> for ty::RegionParameterDef {
735 fn repr(&self, tcx: &ctxt) -> String {
736 format!("RegionParameterDef(name={}, def_id={}, bounds={})",
737 token::get_name(self.name),
738 self.def_id.repr(tcx),
739 self.bounds.repr(tcx))
743 impl<'tcx> Repr<'tcx> for ty::TyS<'tcx> {
744 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
745 ty_to_string(tcx, self)
749 impl<'tcx> Repr<'tcx> for ty::mt<'tcx> {
750 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
751 mt_to_string(tcx, self)
755 impl<'tcx> Repr<'tcx> for subst::Substs<'tcx> {
756 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
757 format!("Substs[types={}, regions={}]",
758 self.types.repr(tcx),
759 self.regions.repr(tcx))
763 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for subst::VecPerParamSpace<T> {
764 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
765 format!("[{};{};{}]",
766 self.get_slice(subst::TypeSpace).repr(tcx),
767 self.get_slice(subst::SelfSpace).repr(tcx),
768 self.get_slice(subst::FnSpace).repr(tcx))
772 impl<'tcx> Repr<'tcx> for ty::ItemSubsts<'tcx> {
773 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
774 format!("ItemSubsts({})", self.substs.repr(tcx))
778 impl<'tcx> Repr<'tcx> for subst::RegionSubsts {
779 fn repr(&self, tcx: &ctxt) -> String {
781 subst::ErasedRegions => "erased".to_string(),
782 subst::NonerasedRegions(ref regions) => regions.repr(tcx)
787 impl<'tcx> Repr<'tcx> for ty::BuiltinBounds {
788 fn repr(&self, _tcx: &ctxt) -> String {
789 let mut res = Vec::new();
792 ty::BoundSend => "Send".to_string(),
793 ty::BoundSized => "Sized".to_string(),
794 ty::BoundCopy => "Copy".to_string(),
795 ty::BoundSync => "Sync".to_string(),
802 impl<'tcx> Repr<'tcx> for ty::ParamBounds<'tcx> {
803 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
804 let mut res = Vec::new();
805 res.push(self.builtin_bounds.repr(tcx));
806 for t in &self.trait_bounds {
807 res.push(t.repr(tcx));
813 impl<'tcx> Repr<'tcx> for ty::TraitRef<'tcx> {
814 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
815 // when printing out the debug representation, we don't need
816 // to enumerate the `for<...>` etc because the debruijn index
817 // tells you everything you need to know.
818 let base = ty::item_path_str(tcx, self.def_id);
819 parameterized(tcx, &base, self.substs, self.def_id, &[],
820 || ty::lookup_trait_def(tcx, self.def_id).generics.clone())
824 impl<'tcx> Repr<'tcx> for ty::TraitDef<'tcx> {
825 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
826 format!("TraitDef(generics={}, bounds={}, trait_ref={})",
827 self.generics.repr(tcx),
828 self.bounds.repr(tcx),
829 self.trait_ref.repr(tcx))
833 impl<'tcx> Repr<'tcx> for ast::TraitItem {
834 fn repr(&self, _tcx: &ctxt) -> String {
836 ast::RequiredMethod(ref data) => format!("RequiredMethod({}, id={})",
837 data.ident, data.id),
838 ast::ProvidedMethod(ref data) => format!("ProvidedMethod(id={})",
840 ast::TypeTraitItem(ref data) => format!("TypeTraitItem({}, id={})",
841 data.ty_param.ident, data.ty_param.id),
846 impl<'tcx> Repr<'tcx> for ast::Expr {
847 fn repr(&self, _tcx: &ctxt) -> String {
848 format!("expr({}: {})", self.id, pprust::expr_to_string(self))
852 impl<'tcx> Repr<'tcx> for ast::Path {
853 fn repr(&self, _tcx: &ctxt) -> String {
854 format!("path({})", pprust::path_to_string(self))
858 impl<'tcx> UserString<'tcx> for ast::Path {
859 fn user_string(&self, _tcx: &ctxt) -> String {
860 pprust::path_to_string(self)
864 impl<'tcx> Repr<'tcx> for ast::Ty {
865 fn repr(&self, _tcx: &ctxt) -> String {
866 format!("type({})", pprust::ty_to_string(self))
870 impl<'tcx> Repr<'tcx> for ast::Item {
871 fn repr(&self, tcx: &ctxt) -> String {
872 format!("item({})", tcx.map.node_to_string(self.id))
876 impl<'tcx> Repr<'tcx> for ast::Lifetime {
877 fn repr(&self, _tcx: &ctxt) -> String {
878 format!("lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
882 impl<'tcx> Repr<'tcx> for ast::Stmt {
883 fn repr(&self, _tcx: &ctxt) -> String {
884 format!("stmt({}: {})",
885 ast_util::stmt_id(self),
886 pprust::stmt_to_string(self))
890 impl<'tcx> Repr<'tcx> for ast::Pat {
891 fn repr(&self, _tcx: &ctxt) -> String {
892 format!("pat({}: {})", self.id, pprust::pat_to_string(self))
896 impl<'tcx> Repr<'tcx> for ty::BoundRegion {
897 fn repr(&self, tcx: &ctxt) -> String {
899 ty::BrAnon(id) => format!("BrAnon({})", id),
900 ty::BrNamed(id, name) => {
901 format!("BrNamed({}, {})", id.repr(tcx), token::get_name(name))
903 ty::BrFresh(id) => format!("BrFresh({})", id),
904 ty::BrEnv => "BrEnv".to_string()
909 impl<'tcx> Repr<'tcx> for ty::Region {
910 fn repr(&self, tcx: &ctxt) -> String {
912 ty::ReEarlyBound(id, space, index, name) => {
913 format!("ReEarlyBound({}, {:?}, {}, {})",
917 token::get_name(name))
920 ty::ReLateBound(binder_id, ref bound_region) => {
921 format!("ReLateBound({:?}, {})",
923 bound_region.repr(tcx))
926 ty::ReFree(ref fr) => fr.repr(tcx),
929 format!("ReScope({:?})", id)
933 "ReStatic".to_string()
936 ty::ReInfer(ReVar(ref vid)) => {
940 ty::ReInfer(ReSkolemized(id, ref bound_region)) => {
941 format!("re_skolemized({}, {})", id, bound_region.repr(tcx))
945 "ReEmpty".to_string()
951 impl<'tcx> UserString<'tcx> for ty::Region {
952 fn user_string(&self, tcx: &ctxt) -> String {
953 region_to_string(tcx, "", false, *self)
957 impl<'tcx> Repr<'tcx> for ty::FreeRegion {
958 fn repr(&self, tcx: &ctxt) -> String {
959 format!("ReFree({}, {})",
960 self.scope.repr(tcx),
961 self.bound_region.repr(tcx))
965 impl<'tcx> Repr<'tcx> for region::CodeExtent {
966 fn repr(&self, _tcx: &ctxt) -> String {
968 region::CodeExtent::Misc(node_id) =>
969 format!("Misc({})", node_id),
970 region::CodeExtent::DestructionScope(node_id) =>
971 format!("DestructionScope({})", node_id),
972 region::CodeExtent::Remainder(rem) =>
973 format!("Remainder({}, {})", rem.block, rem.first_statement_index),
978 impl<'tcx> Repr<'tcx> for region::DestructionScopeData {
979 fn repr(&self, _tcx: &ctxt) -> String {
981 region::DestructionScopeData{ node_id } =>
982 format!("DestructionScopeData {{ node_id: {} }}", node_id),
987 impl<'tcx> Repr<'tcx> for ast::DefId {
988 fn repr(&self, tcx: &ctxt) -> String {
989 // Unfortunately, there seems to be no way to attempt to print
990 // a path for a def-id, so I'll just make a best effort for now
991 // and otherwise fallback to just printing the crate/node pair
992 if self.krate == ast::LOCAL_CRATE {
993 match tcx.map.find(self.node) {
994 Some(ast_map::NodeItem(..)) |
995 Some(ast_map::NodeForeignItem(..)) |
996 Some(ast_map::NodeImplItem(..)) |
997 Some(ast_map::NodeTraitItem(..)) |
998 Some(ast_map::NodeVariant(..)) |
999 Some(ast_map::NodeStructCtor(..)) => {
1003 ty::item_path_str(tcx, *self))
1008 return format!("{:?}", *self)
1012 impl<'tcx> Repr<'tcx> for ty::TypeScheme<'tcx> {
1013 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1014 format!("TypeScheme {{generics: {}, ty: {}}}",
1015 self.generics.repr(tcx),
1020 impl<'tcx> Repr<'tcx> for ty::Generics<'tcx> {
1021 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1022 format!("Generics(types: {}, regions: {})",
1023 self.types.repr(tcx),
1024 self.regions.repr(tcx))
1028 impl<'tcx> Repr<'tcx> for ty::GenericPredicates<'tcx> {
1029 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1030 format!("GenericPredicates(predicates: {})",
1031 self.predicates.repr(tcx))
1035 impl<'tcx> Repr<'tcx> for ty::InstantiatedPredicates<'tcx> {
1036 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1037 format!("InstantiatedPredicates({})",
1038 self.predicates.repr(tcx))
1042 impl<'tcx> Repr<'tcx> for ty::ItemVariances {
1043 fn repr(&self, tcx: &ctxt) -> String {
1044 format!("ItemVariances(types={}, \
1046 self.types.repr(tcx),
1047 self.regions.repr(tcx))
1051 impl<'tcx> Repr<'tcx> for ty::Variance {
1052 fn repr(&self, _: &ctxt) -> String {
1053 // The first `.to_string()` returns a &'static str (it is not an implementation
1054 // of the ToString trait). Because of that, we need to call `.to_string()` again
1055 // if we want to have a `String`.
1056 let result: &'static str = (*self).to_string();
1061 impl<'tcx> Repr<'tcx> for ty::Method<'tcx> {
1062 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1063 format!("method(name: {}, generics: {}, fty: {}, \
1064 explicit_self: {}, vis: {}, def_id: {})",
1065 self.name.repr(tcx),
1066 self.generics.repr(tcx),
1068 self.explicit_self.repr(tcx),
1070 self.def_id.repr(tcx))
1074 impl<'tcx> Repr<'tcx> for ast::Name {
1075 fn repr(&self, _tcx: &ctxt) -> String {
1076 token::get_name(*self).to_string()
1080 impl<'tcx> UserString<'tcx> for ast::Name {
1081 fn user_string(&self, _tcx: &ctxt) -> String {
1082 token::get_name(*self).to_string()
1086 impl<'tcx> Repr<'tcx> for ast::Ident {
1087 fn repr(&self, _tcx: &ctxt) -> String {
1088 token::get_ident(*self).to_string()
1092 impl<'tcx> Repr<'tcx> for ast::ExplicitSelf_ {
1093 fn repr(&self, _tcx: &ctxt) -> String {
1094 format!("{:?}", *self)
1098 impl<'tcx> Repr<'tcx> for ast::Visibility {
1099 fn repr(&self, _tcx: &ctxt) -> String {
1100 format!("{:?}", *self)
1104 impl<'tcx> Repr<'tcx> for ty::BareFnTy<'tcx> {
1105 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1106 format!("BareFnTy {{unsafety: {}, abi: {}, sig: {}}}",
1108 self.abi.to_string(),
1114 impl<'tcx> Repr<'tcx> for ty::FnSig<'tcx> {
1115 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1116 format!("fn{} -> {}", self.inputs.repr(tcx), self.output.repr(tcx))
1120 impl<'tcx> Repr<'tcx> for ty::FnOutput<'tcx> {
1121 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1123 ty::FnConverging(ty) =>
1124 format!("FnConverging({0})", ty.repr(tcx)),
1126 "FnDiverging".to_string()
1131 impl<'tcx> Repr<'tcx> for ty::MethodCallee<'tcx> {
1132 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1133 format!("MethodCallee {{origin: {}, ty: {}, {}}}",
1134 self.origin.repr(tcx),
1136 self.substs.repr(tcx))
1140 impl<'tcx> Repr<'tcx> for ty::MethodOrigin<'tcx> {
1141 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1143 &ty::MethodStatic(def_id) => {
1144 format!("MethodStatic({})", def_id.repr(tcx))
1146 &ty::MethodStaticClosure(def_id) => {
1147 format!("MethodStaticClosure({})", def_id.repr(tcx))
1149 &ty::MethodTypeParam(ref p) => {
1152 &ty::MethodTraitObject(ref p) => {
1159 impl<'tcx> Repr<'tcx> for ty::MethodParam<'tcx> {
1160 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1161 format!("MethodParam({},{})",
1162 self.trait_ref.repr(tcx),
1167 impl<'tcx> Repr<'tcx> for ty::MethodObject<'tcx> {
1168 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1169 format!("MethodObject({},{},{})",
1170 self.trait_ref.repr(tcx),
1176 impl<'tcx> Repr<'tcx> for ty::BuiltinBound {
1177 fn repr(&self, _tcx: &ctxt) -> String {
1178 format!("{:?}", *self)
1182 impl<'tcx> UserString<'tcx> for ty::BuiltinBound {
1183 fn user_string(&self, _tcx: &ctxt) -> String {
1185 ty::BoundSend => "Send".to_string(),
1186 ty::BoundSized => "Sized".to_string(),
1187 ty::BoundCopy => "Copy".to_string(),
1188 ty::BoundSync => "Sync".to_string(),
1193 impl<'tcx> Repr<'tcx> for Span {
1194 fn repr(&self, tcx: &ctxt) -> String {
1195 tcx.sess.codemap().span_to_string(*self).to_string()
1199 impl<'tcx, A:UserString<'tcx>> UserString<'tcx> for Rc<A> {
1200 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1201 let this: &A = &**self;
1202 this.user_string(tcx)
1206 impl<'tcx> UserString<'tcx> for ty::ParamBounds<'tcx> {
1207 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1208 let mut result = Vec::new();
1209 let s = self.builtin_bounds.user_string(tcx);
1213 for n in &self.trait_bounds {
1214 result.push(n.user_string(tcx));
1216 result.connect(" + ")
1220 impl<'tcx> Repr<'tcx> for ty::ExistentialBounds<'tcx> {
1221 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1222 let mut res = Vec::new();
1224 let region_str = self.region_bound.user_string(tcx);
1225 if !region_str.is_empty() {
1226 res.push(region_str);
1229 for bound in &self.builtin_bounds {
1230 res.push(bound.user_string(tcx));
1233 for projection_bound in &self.projection_bounds {
1234 res.push(projection_bound.user_string(tcx));
1241 impl<'tcx> UserString<'tcx> for ty::BuiltinBounds {
1242 fn user_string(&self, tcx: &ctxt) -> String {
1244 .map(|bb| bb.user_string(tcx))
1245 .collect::<Vec<String>>()
1251 impl<'tcx, T> UserString<'tcx> for ty::Binder<T>
1252 where T : UserString<'tcx> + TypeFoldable<'tcx>
1254 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1255 // Replace any anonymous late-bound regions with named
1256 // variants, using gensym'd identifiers, so that we can
1257 // clearly differentiate between named and unnamed regions in
1258 // the output. We'll probably want to tweak this over time to
1259 // decide just how much information to give.
1260 let mut names = Vec::new();
1261 let (unbound_value, _) = ty::replace_late_bound_regions(tcx, self, |br| {
1262 ty::ReLateBound(ty::DebruijnIndex::new(1), match br {
1263 ty::BrNamed(_, name) => {
1264 names.push(token::get_name(name));
1270 let name = token::gensym("'r");
1271 names.push(token::get_name(name));
1272 ty::BrNamed(ast_util::local_def(ast::DUMMY_NODE_ID), name)
1276 let names: Vec<_> = names.iter().map(|s| &s[..]).collect();
1278 let value_str = unbound_value.user_string(tcx);
1279 if names.len() == 0 {
1282 format!("for<{}> {}", names.connect(","), value_str)
1287 impl<'tcx> UserString<'tcx> for ty::TraitRef<'tcx> {
1288 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1289 let path_str = ty::item_path_str(tcx, self.def_id);
1290 parameterized(tcx, &path_str, self.substs, self.def_id, &[],
1291 || ty::lookup_trait_def(tcx, self.def_id).generics.clone())
1295 impl<'tcx> UserString<'tcx> for Ty<'tcx> {
1296 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1297 ty_to_string(tcx, *self)
1301 impl<'tcx> UserString<'tcx> for ast::Ident {
1302 fn user_string(&self, _tcx: &ctxt) -> String {
1303 token::get_name(self.name).to_string()
1307 impl<'tcx> Repr<'tcx> for abi::Abi {
1308 fn repr(&self, _tcx: &ctxt) -> String {
1313 impl<'tcx> UserString<'tcx> for abi::Abi {
1314 fn user_string(&self, _tcx: &ctxt) -> String {
1319 impl<'tcx> Repr<'tcx> for ty::UpvarId {
1320 fn repr(&self, tcx: &ctxt) -> String {
1321 format!("UpvarId({};`{}`;{})",
1323 ty::local_var_name_str(tcx, self.var_id),
1324 self.closure_expr_id)
1328 impl<'tcx> Repr<'tcx> for ast::Mutability {
1329 fn repr(&self, _tcx: &ctxt) -> String {
1330 format!("{:?}", *self)
1334 impl<'tcx> Repr<'tcx> for ty::BorrowKind {
1335 fn repr(&self, _tcx: &ctxt) -> String {
1336 format!("{:?}", *self)
1340 impl<'tcx> Repr<'tcx> for ty::UpvarBorrow {
1341 fn repr(&self, tcx: &ctxt) -> String {
1342 format!("UpvarBorrow({}, {})",
1343 self.kind.repr(tcx),
1344 self.region.repr(tcx))
1348 impl<'tcx> Repr<'tcx> for ty::UpvarCapture {
1349 fn repr(&self, tcx: &ctxt) -> String {
1351 ty::UpvarCapture::ByValue => format!("ByValue"),
1352 ty::UpvarCapture::ByRef(ref data) => format!("ByRef({})", data.repr(tcx)),
1357 impl<'tcx> Repr<'tcx> for ty::IntVid {
1358 fn repr(&self, _tcx: &ctxt) -> String {
1359 format!("{:?}", self)
1363 impl<'tcx> Repr<'tcx> for ty::FloatVid {
1364 fn repr(&self, _tcx: &ctxt) -> String {
1365 format!("{:?}", self)
1369 impl<'tcx> Repr<'tcx> for ty::RegionVid {
1370 fn repr(&self, _tcx: &ctxt) -> String {
1371 format!("{:?}", self)
1375 impl<'tcx> Repr<'tcx> for ty::TyVid {
1376 fn repr(&self, _tcx: &ctxt) -> String {
1377 format!("{:?}", self)
1381 impl<'tcx> Repr<'tcx> for ty::IntVarValue {
1382 fn repr(&self, _tcx: &ctxt) -> String {
1383 format!("{:?}", *self)
1387 impl<'tcx> Repr<'tcx> for ast::IntTy {
1388 fn repr(&self, _tcx: &ctxt) -> String {
1389 format!("{:?}", *self)
1393 impl<'tcx> Repr<'tcx> for ast::UintTy {
1394 fn repr(&self, _tcx: &ctxt) -> String {
1395 format!("{:?}", *self)
1399 impl<'tcx> Repr<'tcx> for ast::FloatTy {
1400 fn repr(&self, _tcx: &ctxt) -> String {
1401 format!("{:?}", *self)
1405 impl<'tcx> Repr<'tcx> for ty::ExplicitSelfCategory {
1406 fn repr(&self, _: &ctxt) -> String {
1407 explicit_self_category_to_str(self).to_string()
1411 impl<'tcx> UserString<'tcx> for ParamTy {
1412 fn user_string(&self, _tcx: &ctxt) -> String {
1413 format!("{}", token::get_name(self.name))
1417 impl<'tcx> Repr<'tcx> for ParamTy {
1418 fn repr(&self, tcx: &ctxt) -> String {
1419 let ident = self.user_string(tcx);
1420 format!("{}/{:?}.{}", ident, self.space, self.idx)
1424 impl<'tcx, A:Repr<'tcx>, B:Repr<'tcx>> Repr<'tcx> for (A,B) {
1425 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1426 let &(ref a, ref b) = self;
1427 format!("({},{})", a.repr(tcx), b.repr(tcx))
1431 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for ty::Binder<T> {
1432 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1433 format!("Binder({})", self.0.repr(tcx))
1438 impl<'tcx, S, K, V> Repr<'tcx> for HashMap<K, V, S>
1439 where K: Hash<<S as HashState>::Hasher> + Eq + Repr<'tcx>,
1442 <S as HashState>::Hasher: Hasher<Output=u64>,
1444 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1445 format!("HashMap({})",
1447 .map(|(k,v)| format!("{} => {}", k.repr(tcx), v.repr(tcx)))
1448 .collect::<Vec<String>>()
1454 impl<'tcx, S, K, V> Repr<'tcx> for HashMap<K, V, S>
1455 where K: Hash + Eq + Repr<'tcx>,
1459 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1460 format!("HashMap({})",
1462 .map(|(k,v)| format!("{} => {}", k.repr(tcx), v.repr(tcx)))
1463 .collect::<Vec<String>>()
1468 impl<'tcx, T, U> Repr<'tcx> for ty::OutlivesPredicate<T,U>
1469 where T : Repr<'tcx> + TypeFoldable<'tcx>,
1470 U : Repr<'tcx> + TypeFoldable<'tcx>,
1472 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1473 format!("OutlivesPredicate({}, {})",
1479 impl<'tcx, T, U> UserString<'tcx> for ty::OutlivesPredicate<T,U>
1480 where T : UserString<'tcx> + TypeFoldable<'tcx>,
1481 U : UserString<'tcx> + TypeFoldable<'tcx>,
1483 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1485 self.0.user_string(tcx),
1486 self.1.user_string(tcx))
1490 impl<'tcx> Repr<'tcx> for ty::EquatePredicate<'tcx> {
1491 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1492 format!("EquatePredicate({}, {})",
1498 impl<'tcx> UserString<'tcx> for ty::EquatePredicate<'tcx> {
1499 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1501 self.0.user_string(tcx),
1502 self.1.user_string(tcx))
1506 impl<'tcx> Repr<'tcx> for ty::TraitPredicate<'tcx> {
1507 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1508 format!("TraitPredicate({})",
1509 self.trait_ref.repr(tcx))
1513 impl<'tcx> UserString<'tcx> for ty::TraitPredicate<'tcx> {
1514 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1516 self.trait_ref.self_ty().user_string(tcx),
1517 self.trait_ref.user_string(tcx))
1521 impl<'tcx> UserString<'tcx> for ty::ProjectionPredicate<'tcx> {
1522 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1524 self.projection_ty.user_string(tcx),
1525 self.ty.user_string(tcx))
1529 impl<'tcx> Repr<'tcx> for ty::ProjectionTy<'tcx> {
1530 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1531 format!("<{} as {}>::{}",
1532 self.trait_ref.substs.self_ty().repr(tcx),
1533 self.trait_ref.repr(tcx),
1534 self.item_name.repr(tcx))
1538 impl<'tcx> UserString<'tcx> for ty::ProjectionTy<'tcx> {
1539 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1540 format!("<{} as {}>::{}",
1541 self.trait_ref.self_ty().user_string(tcx),
1542 self.trait_ref.user_string(tcx),
1543 self.item_name.user_string(tcx))
1547 impl<'tcx> UserString<'tcx> for ty::Predicate<'tcx> {
1548 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1550 ty::Predicate::Trait(ref data) => data.user_string(tcx),
1551 ty::Predicate::Equate(ref predicate) => predicate.user_string(tcx),
1552 ty::Predicate::RegionOutlives(ref predicate) => predicate.user_string(tcx),
1553 ty::Predicate::TypeOutlives(ref predicate) => predicate.user_string(tcx),
1554 ty::Predicate::Projection(ref predicate) => predicate.user_string(tcx),