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;
31 use std::hash::{Hash, Hasher};
35 use syntax::codemap::{Span, Pos};
36 use syntax::parse::token;
37 use syntax::print::pprust;
39 use syntax::{ast, ast_util};
40 use syntax::owned_slice::OwnedSlice;
42 /// Produces a string suitable for debugging output.
43 pub trait Repr<'tcx> {
44 fn repr(&self, tcx: &ctxt<'tcx>) -> String;
47 /// Produces a string suitable for showing to the user.
48 pub trait UserString<'tcx> : Repr<'tcx> {
49 fn user_string(&self, tcx: &ctxt<'tcx>) -> String;
52 pub fn note_and_explain_region(cx: &ctxt,
55 suffix: &str) -> Option<Span> {
56 match explain_region_and_span(cx, region) {
57 (ref str, Some(span)) => {
60 &format!("{}{}{}", prefix, *str, suffix)[]);
65 &format!("{}{}{}", prefix, *str, suffix)[]);
71 /// When a free region is associated with `item`, how should we describe the item in the error
73 fn item_scope_tag(item: &ast::Item) -> &'static str {
75 ast::ItemImpl(..) => "impl",
76 ast::ItemStruct(..) => "struct",
77 ast::ItemEnum(..) => "enum",
78 ast::ItemTrait(..) => "trait",
79 ast::ItemFn(..) => "function body",
84 pub fn explain_region_and_span(cx: &ctxt, region: ty::Region)
85 -> (String, Option<Span>) {
89 let on_unknown_scope = || {
90 (format!("unknown scope: {:?}. Please report a bug.", scope), None)
92 let span = match scope.span(&cx.map) {
94 None => return on_unknown_scope(),
96 let tag = match cx.map.find(scope.node_id()) {
97 Some(ast_map::NodeBlock(_)) => "block",
98 Some(ast_map::NodeExpr(expr)) => match expr.node {
99 ast::ExprCall(..) => "call",
100 ast::ExprMethodCall(..) => "method call",
101 ast::ExprMatch(_, _, ast::MatchSource::IfLetDesugar { .. }) => "if let",
102 ast::ExprMatch(_, _, ast::MatchSource::WhileLetDesugar) => "while let",
103 ast::ExprMatch(_, _, ast::MatchSource::ForLoopDesugar) => "for",
104 ast::ExprMatch(..) => "match",
107 Some(ast_map::NodeStmt(_)) => "statement",
108 Some(ast_map::NodeItem(it)) => item_scope_tag(&*it),
110 // this really should not happen
111 return on_unknown_scope();
114 let scope_decorated_tag = match scope {
115 region::CodeExtent::Misc(_) => tag,
116 region::CodeExtent::DestructionScope(_) => {
117 new_string = format!("destruction scope surrounding {}", tag);
118 new_string.as_slice()
120 region::CodeExtent::Remainder(r) => {
121 new_string = format!("block suffix following statement {}",
122 r.first_statement_index);
126 explain_span(cx, scope_decorated_tag, span)
131 let prefix = match fr.bound_region {
133 format!("the anonymous lifetime #{} defined on", idx + 1)
135 BrFresh(_) => "an anonymous lifetime defined on".to_string(),
137 format!("the lifetime {} as defined on",
138 bound_region_ptr_to_string(cx, fr.bound_region))
142 match cx.map.find(fr.scope.node_id) {
143 Some(ast_map::NodeBlock(ref blk)) => {
144 let (msg, opt_span) = explain_span(cx, "block", blk.span);
145 (format!("{} {}", prefix, msg), opt_span)
147 Some(ast_map::NodeItem(it)) => {
148 let tag = item_scope_tag(&*it);
149 let (msg, opt_span) = explain_span(cx, tag, it.span);
150 (format!("{} {}", prefix, msg), opt_span)
153 // this really should not happen
154 (format!("{} unknown free region bounded by scope {:?}", prefix, fr.scope), None)
159 ReStatic => { ("the static lifetime".to_string(), None) }
161 ReEmpty => { ("the empty lifetime".to_string(), None) }
163 ReEarlyBound(_, _, _, name) => {
164 (format!("{}", token::get_name(name)), None)
167 // I believe these cases should not occur (except when debugging,
169 ty::ReInfer(_) | ty::ReLateBound(..) => {
170 (format!("lifetime {:?}", region), None)
174 fn explain_span(cx: &ctxt, heading: &str, span: Span)
175 -> (String, Option<Span>) {
176 let lo = cx.sess.codemap().lookup_char_pos_adj(span.lo);
177 (format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize()),
182 pub fn bound_region_ptr_to_string(cx: &ctxt, br: BoundRegion) -> String {
183 bound_region_to_string(cx, "", false, br)
186 pub fn bound_region_to_string(cx: &ctxt,
187 prefix: &str, space: bool,
188 br: BoundRegion) -> String {
189 let space_str = if space { " " } else { "" };
191 if cx.sess.verbose() {
192 return format!("{}{}{}", prefix, br.repr(cx), space_str)
196 BrNamed(_, name) => {
197 format!("{}{}{}", prefix, token::get_name(name), space_str)
199 BrAnon(_) | BrFresh(_) | BrEnv => prefix.to_string()
203 // In general, if you are giving a region error message,
204 // you should use `explain_region()` or, better yet,
205 // `note_and_explain_region()`
206 pub fn region_ptr_to_string(cx: &ctxt, region: Region) -> String {
207 region_to_string(cx, "&", true, region)
210 pub fn region_to_string(cx: &ctxt, prefix: &str, space: bool, region: Region) -> String {
211 let space_str = if space { " " } else { "" };
213 if cx.sess.verbose() {
214 return format!("{}{}{}", prefix, region.repr(cx), space_str)
217 // These printouts are concise. They do not contain all the information
218 // the user might want to diagnose an error, but there is basically no way
219 // to fit that into a short string. Hence the recommendation to use
220 // `explain_region()` or `note_and_explain_region()`.
222 ty::ReScope(_) => prefix.to_string(),
223 ty::ReEarlyBound(_, _, _, name) => {
224 token::get_name(name).to_string()
226 ty::ReLateBound(_, br) => bound_region_to_string(cx, prefix, space, br),
227 ty::ReFree(ref fr) => bound_region_to_string(cx, prefix, space, fr.bound_region),
228 ty::ReInfer(ReSkolemized(_, br)) => {
229 bound_region_to_string(cx, prefix, space, br)
231 ty::ReInfer(ReVar(_)) => prefix.to_string(),
232 ty::ReStatic => format!("{}'static{}", prefix, space_str),
233 ty::ReEmpty => format!("{}'<empty>{}", prefix, space_str),
237 pub fn mutability_to_string(m: ast::Mutability) -> String {
239 ast::MutMutable => "mut ".to_string(),
240 ast::MutImmutable => "".to_string(),
244 pub fn mt_to_string<'tcx>(cx: &ctxt<'tcx>, m: &mt<'tcx>) -> String {
246 mutability_to_string(m.mutbl),
247 ty_to_string(cx, m.ty))
250 pub fn vec_map_to_string<T, F>(ts: &[T], f: F) -> String where
251 F: FnMut(&T) -> String,
253 let tstrs = ts.iter().map(f).collect::<Vec<String>>();
254 format!("[{}]", tstrs.connect(", "))
257 pub fn ty_to_string<'tcx>(cx: &ctxt<'tcx>, typ: &ty::TyS<'tcx>) -> String {
258 fn bare_fn_to_string<'tcx>(cx: &ctxt<'tcx>,
259 opt_def_id: Option<ast::DefId>,
260 unsafety: ast::Unsafety,
262 ident: Option<ast::Ident>,
263 sig: &ty::PolyFnSig<'tcx>)
265 let mut s = String::new();
268 ast::Unsafety::Normal => {}
269 ast::Unsafety::Unsafe => {
270 s.push_str(&unsafety.to_string());
275 if abi != abi::Rust {
276 s.push_str(&format!("extern {} ", abi.to_string())[]);
284 s.push_str(&token::get_ident(i));
289 push_sig_to_string(cx, &mut s, '(', ')', sig);
294 let path_str = ty::item_path_str(cx, def_id);
295 s.push_str(&path_str[]);
304 fn closure_to_string<'tcx>(cx: &ctxt<'tcx>, cty: &ty::ClosureTy<'tcx>) -> String {
305 let mut s = String::new();
306 s.push_str("[closure");
307 push_sig_to_string(cx, &mut s, '(', ')', &cty.sig);
312 fn push_sig_to_string<'tcx>(cx: &ctxt<'tcx>,
316 sig: &ty::PolyFnSig<'tcx>) {
318 let strs = sig.0.inputs
320 .map(|a| ty_to_string(cx, *a))
321 .collect::<Vec<_>>();
322 s.push_str(&strs.connect(", "));
329 ty::FnConverging(t) => {
330 if !ty::type_is_nil(t) {
332 s.push_str(&ty_to_string(cx, t)[]);
341 fn infer_ty_to_string(cx: &ctxt, ty: ty::InferTy) -> String {
342 let print_var_ids = cx.sess.verbose();
344 ty::TyVar(ref vid) if print_var_ids => vid.repr(cx),
345 ty::IntVar(ref vid) if print_var_ids => vid.repr(cx),
346 ty::FloatVar(ref vid) if print_var_ids => vid.repr(cx),
347 ty::TyVar(_) | ty::IntVar(_) | ty::FloatVar(_) => format!("_"),
348 ty::FreshTy(v) => format!("FreshTy({})", v),
349 ty::FreshIntTy(v) => format!("FreshIntTy({})", v)
353 // pretty print the structural type representation:
355 ty_bool => "bool".to_string(),
356 ty_char => "char".to_string(),
357 ty_int(t) => ast_util::int_ty_to_string(t, None).to_string(),
358 ty_uint(t) => ast_util::uint_ty_to_string(t, None).to_string(),
359 ty_float(t) => ast_util::float_ty_to_string(t).to_string(),
360 ty_uniq(typ) => format!("Box<{}>", ty_to_string(cx, typ)),
362 format!("*{} {}", match tm.mutbl {
363 ast::MutMutable => "mut",
364 ast::MutImmutable => "const",
365 }, ty_to_string(cx, tm.ty))
367 ty_rptr(r, ref tm) => {
368 let mut buf = region_ptr_to_string(cx, *r);
369 buf.push_str(&mt_to_string(cx, tm)[]);
373 format!("opened<{}>", ty_to_string(cx, typ)),
374 ty_tup(ref elems) => {
377 .map(|elem| ty_to_string(cx, *elem))
378 .collect::<Vec<_>>();
380 [ref string] => format!("({},)", string),
381 strs => format!("({})", strs.connect(", "))
384 ty_bare_fn(opt_def_id, ref f) => {
385 bare_fn_to_string(cx, opt_def_id, f.unsafety, f.abi, None, &f.sig)
387 ty_infer(infer_ty) => infer_ty_to_string(cx, infer_ty),
388 ty_err => "[type error]".to_string(),
389 ty_param(ref param_ty) => {
390 if cx.sess.verbose() {
393 param_ty.user_string(cx)
396 ty_enum(did, substs) | ty_struct(did, substs) => {
397 let base = ty::item_path_str(cx, did);
398 parameterized(cx, &base, substs, did, &[],
399 || ty::lookup_item_type(cx, did).generics)
401 ty_trait(ref data) => {
404 ty::ty_projection(ref data) => {
405 format!("<{} as {}>::{}",
406 data.trait_ref.self_ty().user_string(cx),
407 data.trait_ref.user_string(cx),
408 data.item_name.user_string(cx))
410 ty_str => "str".to_string(),
411 ty_closure(ref did, _, substs) => {
412 let closure_tys = cx.closure_tys.borrow();
413 closure_tys.get(did).map(|closure_type| {
414 closure_to_string(cx, &closure_type.subst(cx, substs))
415 }).unwrap_or_else(|| {
416 if did.krate == ast::LOCAL_CRATE {
417 let span = cx.map.span(did.node);
418 format!("[closure {}]", span.repr(cx))
425 let inner_str = ty_to_string(cx, t);
427 Some(n) => format!("[{}; {}]", inner_str, n),
428 None => format!("[{}]", inner_str),
434 pub fn explicit_self_category_to_str(category: &ty::ExplicitSelfCategory)
437 ty::StaticExplicitSelfCategory => "static",
438 ty::ByValueExplicitSelfCategory => "self",
439 ty::ByReferenceExplicitSelfCategory(_, ast::MutMutable) => {
442 ty::ByReferenceExplicitSelfCategory(_, ast::MutImmutable) => "&self",
443 ty::ByBoxExplicitSelfCategory => "Box<self>",
447 pub fn parameterized<'tcx,GG>(cx: &ctxt<'tcx>,
449 substs: &subst::Substs<'tcx>,
451 projections: &[ty::ProjectionPredicate<'tcx>],
454 where GG : FnOnce() -> ty::Generics<'tcx>
456 if cx.sess.verbose() {
457 let mut strings = vec![];
458 match substs.regions {
459 subst::ErasedRegions => {
460 strings.push(format!(".."));
462 subst::NonerasedRegions(ref regions) => {
463 for region in regions.iter() {
464 strings.push(region.repr(cx));
468 for ty in substs.types.iter() {
469 strings.push(ty.repr(cx));
471 for projection in projections.iter() {
472 strings.push(format!("{}={}",
473 projection.projection_ty.item_name.user_string(cx),
474 projection.ty.user_string(cx)));
476 return if strings.is_empty() {
479 format!("{}<{}>", base, strings.connect(","))
483 let mut strs = Vec::new();
485 match substs.regions {
486 subst::ErasedRegions => { }
487 subst::NonerasedRegions(ref regions) => {
488 for &r in regions.iter() {
489 let s = region_to_string(cx, "", false, r);
491 // This happens when the value of the region
492 // parameter is not easily serialized. This may be
493 // because the user omitted it in the first place,
494 // or because it refers to some block in the code,
495 // etc. I'm not sure how best to serialize this.
496 strs.push(format!("'_"));
504 // It is important to execute this conditionally, only if -Z
505 // verbose is false. Otherwise, debug logs can sometimes cause
506 // ICEs trying to fetch the generics early in the pipeline. This
507 // is kind of a hacky workaround in that -Z verbose is required to
509 let generics = get_generics();
511 let tps = substs.types.get_slice(subst::TypeSpace);
512 let ty_params = generics.types.get_slice(subst::TypeSpace);
513 let has_defaults = ty_params.last().map_or(false, |def| def.default.is_some());
514 let num_defaults = if has_defaults {
515 ty_params.iter().zip(tps.iter()).rev().take_while(|&(def, &actual)| {
517 Some(default) => default.subst(cx, substs) == actual,
525 for t in &tps[..tps.len() - num_defaults] {
526 strs.push(ty_to_string(cx, *t))
529 for projection in projections {
530 strs.push(format!("{}={}",
531 projection.projection_ty.item_name.user_string(cx),
532 projection.ty.user_string(cx)));
535 if cx.lang_items.fn_trait_kind(did).is_some() && projections.len() == 1 {
536 let projection_ty = projections[0].ty;
538 if ty::type_is_nil(projection_ty) {
541 format!(" -> {}", projection_ty.user_string(cx))
545 if strs[0].starts_with("(") && strs[0].ends_with(",)") {
546 &strs[0][1 .. strs[0].len() - 2] // Remove '(' and ',)'
547 } else if strs[0].starts_with("(") && strs[0].ends_with(")") {
548 &strs[0][1 .. strs[0].len() - 1] // Remove '(' and ')'
553 } else if strs.len() > 0 {
554 format!("{}<{}>", base, strs.connect(", "))
560 pub fn ty_to_short_str<'tcx>(cx: &ctxt<'tcx>, typ: Ty<'tcx>) -> String {
561 let mut s = typ.repr(cx).to_string();
563 s = (&s[0..32]).to_string();
568 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for Option<T> {
569 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
571 &None => "None".to_string(),
572 &Some(ref t) => t.repr(tcx),
577 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for P<T> {
578 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
583 impl<'tcx,T:Repr<'tcx>,U:Repr<'tcx>> Repr<'tcx> for Result<T,U> {
584 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
586 &Ok(ref t) => t.repr(tcx),
587 &Err(ref u) => format!("Err({})", u.repr(tcx))
592 impl<'tcx> Repr<'tcx> for () {
593 fn repr(&self, _tcx: &ctxt) -> String {
598 impl<'a, 'tcx, T: ?Sized +Repr<'tcx>> Repr<'tcx> for &'a T {
599 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
600 Repr::repr(*self, tcx)
604 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for Rc<T> {
605 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
610 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for Box<T> {
611 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
616 fn repr_vec<'tcx, T:Repr<'tcx>>(tcx: &ctxt<'tcx>, v: &[T]) -> String {
617 vec_map_to_string(v, |t| t.repr(tcx))
620 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for [T] {
621 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
626 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for OwnedSlice<T> {
627 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
628 repr_vec(tcx, &self[])
632 // This is necessary to handle types like Option<~[T]>, for which
633 // autoderef cannot convert the &[T] handler
634 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for Vec<T> {
635 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
636 repr_vec(tcx, &self[])
640 impl<'tcx, T:UserString<'tcx>> UserString<'tcx> for Vec<T> {
641 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
642 let strs: Vec<String> =
643 self.iter().map(|t| t.user_string(tcx)).collect();
648 impl<'tcx> Repr<'tcx> for def::Def {
649 fn repr(&self, _tcx: &ctxt) -> String {
650 format!("{:?}", *self)
654 /// This curious type is here to help pretty-print trait objects. In
655 /// a trait object, the projections are stored separately from the
656 /// main trait bound, but in fact we want to package them together
657 /// when printing out; they also have separate binders, but we want
658 /// them to share a binder when we print them out. (And the binder
659 /// pretty-printing logic is kind of clever and we don't want to
660 /// reproduce it.) So we just repackage up the structure somewhat.
662 /// Right now there is only one trait in an object that can have
663 /// projection bounds, so we just stuff them altogether. But in
664 /// reality we should eventually sort things out better.
665 type TraitAndProjections<'tcx> =
666 (Rc<ty::TraitRef<'tcx>>, Vec<ty::ProjectionPredicate<'tcx>>);
668 impl<'tcx> UserString<'tcx> for TraitAndProjections<'tcx> {
669 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
670 let &(ref trait_ref, ref projection_bounds) = self;
671 let base = ty::item_path_str(tcx, trait_ref.def_id);
676 &projection_bounds[],
677 || ty::lookup_trait_def(tcx, trait_ref.def_id).generics.clone())
681 impl<'tcx> UserString<'tcx> for ty::TyTrait<'tcx> {
682 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
683 let &ty::TyTrait { ref principal, ref bounds } = self;
685 let mut components = vec![];
687 let tap: ty::Binder<TraitAndProjections<'tcx>> =
688 ty::Binder((principal.0.clone(),
689 bounds.projection_bounds.iter().map(|x| x.0.clone()).collect()));
691 // Generate the main trait ref, including associated types.
692 components.push(tap.user_string(tcx));
695 for bound in &bounds.builtin_bounds {
696 components.push(bound.user_string(tcx));
699 // Region, if not obviously implied by builtin bounds.
700 if bounds.region_bound != ty::ReStatic {
701 // Region bound is implied by builtin bounds:
702 components.push(bounds.region_bound.user_string(tcx));
705 components.retain(|s| !s.is_empty());
707 components.connect(" + ")
711 impl<'tcx> Repr<'tcx> for ty::TypeParameterDef<'tcx> {
712 fn repr(&self, _tcx: &ctxt<'tcx>) -> String {
713 format!("TypeParameterDef({:?}, {:?}/{})",
720 impl<'tcx> Repr<'tcx> for ty::RegionParameterDef {
721 fn repr(&self, tcx: &ctxt) -> String {
722 format!("RegionParameterDef(name={}, def_id={}, bounds={})",
723 token::get_name(self.name),
724 self.def_id.repr(tcx),
725 self.bounds.repr(tcx))
729 impl<'tcx> Repr<'tcx> for ty::TyS<'tcx> {
730 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
731 ty_to_string(tcx, self)
735 impl<'tcx> Repr<'tcx> for ty::mt<'tcx> {
736 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
737 mt_to_string(tcx, self)
741 impl<'tcx> Repr<'tcx> for subst::Substs<'tcx> {
742 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
743 format!("Substs[types={}, regions={}]",
744 self.types.repr(tcx),
745 self.regions.repr(tcx))
749 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for subst::VecPerParamSpace<T> {
750 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
751 format!("[{};{};{}]",
752 self.get_slice(subst::TypeSpace).repr(tcx),
753 self.get_slice(subst::SelfSpace).repr(tcx),
754 self.get_slice(subst::FnSpace).repr(tcx))
758 impl<'tcx> Repr<'tcx> for ty::ItemSubsts<'tcx> {
759 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
760 format!("ItemSubsts({})", self.substs.repr(tcx))
764 impl<'tcx> Repr<'tcx> for subst::RegionSubsts {
765 fn repr(&self, tcx: &ctxt) -> String {
767 subst::ErasedRegions => "erased".to_string(),
768 subst::NonerasedRegions(ref regions) => regions.repr(tcx)
773 impl<'tcx> Repr<'tcx> for ty::BuiltinBounds {
774 fn repr(&self, _tcx: &ctxt) -> String {
775 let mut res = Vec::new();
778 ty::BoundSend => "Send".to_string(),
779 ty::BoundSized => "Sized".to_string(),
780 ty::BoundCopy => "Copy".to_string(),
781 ty::BoundSync => "Sync".to_string(),
788 impl<'tcx> Repr<'tcx> for ty::ParamBounds<'tcx> {
789 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
790 let mut res = Vec::new();
791 res.push(self.builtin_bounds.repr(tcx));
792 for t in &self.trait_bounds {
793 res.push(t.repr(tcx));
799 impl<'tcx> Repr<'tcx> for ty::TraitRef<'tcx> {
800 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
801 // when printing out the debug representation, we don't need
802 // to enumerate the `for<...>` etc because the debruijn index
803 // tells you everything you need to know.
804 let base = ty::item_path_str(tcx, self.def_id);
805 parameterized(tcx, &base, self.substs, self.def_id, &[],
806 || ty::lookup_trait_def(tcx, self.def_id).generics.clone())
810 impl<'tcx> Repr<'tcx> for ty::TraitDef<'tcx> {
811 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
812 format!("TraitDef(generics={}, bounds={}, trait_ref={})",
813 self.generics.repr(tcx),
814 self.bounds.repr(tcx),
815 self.trait_ref.repr(tcx))
819 impl<'tcx> Repr<'tcx> for ast::TraitItem {
820 fn repr(&self, _tcx: &ctxt) -> String {
822 ast::RequiredMethod(ref data) => format!("RequiredMethod({}, id={})",
823 data.ident, data.id),
824 ast::ProvidedMethod(ref data) => format!("ProvidedMethod(id={})",
826 ast::TypeTraitItem(ref data) => format!("TypeTraitItem({}, id={})",
827 data.ty_param.ident, data.ty_param.id),
832 impl<'tcx> Repr<'tcx> for ast::Expr {
833 fn repr(&self, _tcx: &ctxt) -> String {
834 format!("expr({}: {})", self.id, pprust::expr_to_string(self))
838 impl<'tcx> Repr<'tcx> for ast::Path {
839 fn repr(&self, _tcx: &ctxt) -> String {
840 format!("path({})", pprust::path_to_string(self))
844 impl<'tcx> UserString<'tcx> for ast::Path {
845 fn user_string(&self, _tcx: &ctxt) -> String {
846 pprust::path_to_string(self)
850 impl<'tcx> Repr<'tcx> for ast::Ty {
851 fn repr(&self, _tcx: &ctxt) -> String {
852 format!("type({})", pprust::ty_to_string(self))
856 impl<'tcx> Repr<'tcx> for ast::Item {
857 fn repr(&self, tcx: &ctxt) -> String {
858 format!("item({})", tcx.map.node_to_string(self.id))
862 impl<'tcx> Repr<'tcx> for ast::Lifetime {
863 fn repr(&self, _tcx: &ctxt) -> String {
864 format!("lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
868 impl<'tcx> Repr<'tcx> for ast::Stmt {
869 fn repr(&self, _tcx: &ctxt) -> String {
870 format!("stmt({}: {})",
871 ast_util::stmt_id(self),
872 pprust::stmt_to_string(self))
876 impl<'tcx> Repr<'tcx> for ast::Pat {
877 fn repr(&self, _tcx: &ctxt) -> String {
878 format!("pat({}: {})", self.id, pprust::pat_to_string(self))
882 impl<'tcx> Repr<'tcx> for ty::BoundRegion {
883 fn repr(&self, tcx: &ctxt) -> String {
885 ty::BrAnon(id) => format!("BrAnon({})", id),
886 ty::BrNamed(id, name) => {
887 format!("BrNamed({}, {})", id.repr(tcx), token::get_name(name))
889 ty::BrFresh(id) => format!("BrFresh({})", id),
890 ty::BrEnv => "BrEnv".to_string()
895 impl<'tcx> Repr<'tcx> for ty::Region {
896 fn repr(&self, tcx: &ctxt) -> String {
898 ty::ReEarlyBound(id, space, index, name) => {
899 format!("ReEarlyBound({}, {:?}, {}, {})",
903 token::get_name(name))
906 ty::ReLateBound(binder_id, ref bound_region) => {
907 format!("ReLateBound({:?}, {})",
909 bound_region.repr(tcx))
912 ty::ReFree(ref fr) => fr.repr(tcx),
915 format!("ReScope({:?})", id)
919 "ReStatic".to_string()
922 ty::ReInfer(ReVar(ref vid)) => {
926 ty::ReInfer(ReSkolemized(id, ref bound_region)) => {
927 format!("re_skolemized({}, {})", id, bound_region.repr(tcx))
931 "ReEmpty".to_string()
937 impl<'tcx> UserString<'tcx> for ty::Region {
938 fn user_string(&self, tcx: &ctxt) -> String {
939 region_to_string(tcx, "", false, *self)
943 impl<'tcx> Repr<'tcx> for ty::FreeRegion {
944 fn repr(&self, tcx: &ctxt) -> String {
945 format!("ReFree({}, {})",
946 self.scope.repr(tcx),
947 self.bound_region.repr(tcx))
951 impl<'tcx> Repr<'tcx> for region::CodeExtent {
952 fn repr(&self, _tcx: &ctxt) -> String {
954 region::CodeExtent::Misc(node_id) =>
955 format!("Misc({})", node_id),
956 region::CodeExtent::DestructionScope(node_id) =>
957 format!("DestructionScope({})", node_id),
958 region::CodeExtent::Remainder(rem) =>
959 format!("Remainder({}, {})", rem.block, rem.first_statement_index),
964 impl<'tcx> Repr<'tcx> for region::DestructionScopeData {
965 fn repr(&self, _tcx: &ctxt) -> String {
967 region::DestructionScopeData{ node_id } =>
968 format!("DestructionScopeData {{ node_id: {} }}", node_id),
973 impl<'tcx> Repr<'tcx> for ast::DefId {
974 fn repr(&self, tcx: &ctxt) -> String {
975 // Unfortunately, there seems to be no way to attempt to print
976 // a path for a def-id, so I'll just make a best effort for now
977 // and otherwise fallback to just printing the crate/node pair
978 if self.krate == ast::LOCAL_CRATE {
979 match tcx.map.find(self.node) {
980 Some(ast_map::NodeItem(..)) |
981 Some(ast_map::NodeForeignItem(..)) |
982 Some(ast_map::NodeImplItem(..)) |
983 Some(ast_map::NodeTraitItem(..)) |
984 Some(ast_map::NodeVariant(..)) |
985 Some(ast_map::NodeStructCtor(..)) => {
989 ty::item_path_str(tcx, *self))
994 return format!("{:?}", *self)
998 impl<'tcx> Repr<'tcx> for ty::TypeScheme<'tcx> {
999 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1000 format!("TypeScheme {{generics: {}, ty: {}}}",
1001 self.generics.repr(tcx),
1006 impl<'tcx> Repr<'tcx> for ty::Generics<'tcx> {
1007 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1008 format!("Generics(types: {}, regions: {})",
1009 self.types.repr(tcx),
1010 self.regions.repr(tcx))
1014 impl<'tcx> Repr<'tcx> for ty::GenericPredicates<'tcx> {
1015 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1016 format!("GenericPredicates(predicates: {})",
1017 self.predicates.repr(tcx))
1021 impl<'tcx> Repr<'tcx> for ty::InstantiatedPredicates<'tcx> {
1022 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1023 format!("InstantiatedPredicates({})",
1024 self.predicates.repr(tcx))
1028 impl<'tcx> Repr<'tcx> for ty::ItemVariances {
1029 fn repr(&self, tcx: &ctxt) -> String {
1030 format!("ItemVariances(types={}, \
1032 self.types.repr(tcx),
1033 self.regions.repr(tcx))
1037 impl<'tcx> Repr<'tcx> for ty::Variance {
1038 fn repr(&self, _: &ctxt) -> String {
1039 // The first `.to_string()` returns a &'static str (it is not an implementation
1040 // of the ToString trait). Because of that, we need to call `.to_string()` again
1041 // if we want to have a `String`.
1042 let result: &'static str = (*self).to_string();
1047 impl<'tcx> Repr<'tcx> for ty::Method<'tcx> {
1048 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1049 format!("method(name: {}, generics: {}, fty: {}, \
1050 explicit_self: {}, vis: {}, def_id: {})",
1051 self.name.repr(tcx),
1052 self.generics.repr(tcx),
1054 self.explicit_self.repr(tcx),
1056 self.def_id.repr(tcx))
1060 impl<'tcx> Repr<'tcx> for ast::Name {
1061 fn repr(&self, _tcx: &ctxt) -> String {
1062 token::get_name(*self).to_string()
1066 impl<'tcx> UserString<'tcx> for ast::Name {
1067 fn user_string(&self, _tcx: &ctxt) -> String {
1068 token::get_name(*self).to_string()
1072 impl<'tcx> Repr<'tcx> for ast::Ident {
1073 fn repr(&self, _tcx: &ctxt) -> String {
1074 token::get_ident(*self).to_string()
1078 impl<'tcx> Repr<'tcx> for ast::ExplicitSelf_ {
1079 fn repr(&self, _tcx: &ctxt) -> String {
1080 format!("{:?}", *self)
1084 impl<'tcx> Repr<'tcx> for ast::Visibility {
1085 fn repr(&self, _tcx: &ctxt) -> String {
1086 format!("{:?}", *self)
1090 impl<'tcx> Repr<'tcx> for ty::BareFnTy<'tcx> {
1091 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1092 format!("BareFnTy {{unsafety: {}, abi: {}, sig: {}}}",
1094 self.abi.to_string(),
1100 impl<'tcx> Repr<'tcx> for ty::FnSig<'tcx> {
1101 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1102 format!("fn{} -> {}", self.inputs.repr(tcx), self.output.repr(tcx))
1106 impl<'tcx> Repr<'tcx> for ty::FnOutput<'tcx> {
1107 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1109 ty::FnConverging(ty) =>
1110 format!("FnConverging({0})", ty.repr(tcx)),
1112 "FnDiverging".to_string()
1117 impl<'tcx> Repr<'tcx> for ty::MethodCallee<'tcx> {
1118 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1119 format!("MethodCallee {{origin: {}, ty: {}, {}}}",
1120 self.origin.repr(tcx),
1122 self.substs.repr(tcx))
1126 impl<'tcx> Repr<'tcx> for ty::MethodOrigin<'tcx> {
1127 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1129 &ty::MethodStatic(def_id) => {
1130 format!("MethodStatic({})", def_id.repr(tcx))
1132 &ty::MethodStaticClosure(def_id) => {
1133 format!("MethodStaticClosure({})", def_id.repr(tcx))
1135 &ty::MethodTypeParam(ref p) => {
1138 &ty::MethodTraitObject(ref p) => {
1145 impl<'tcx> Repr<'tcx> for ty::MethodParam<'tcx> {
1146 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1147 format!("MethodParam({},{})",
1148 self.trait_ref.repr(tcx),
1153 impl<'tcx> Repr<'tcx> for ty::MethodObject<'tcx> {
1154 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1155 format!("MethodObject({},{},{})",
1156 self.trait_ref.repr(tcx),
1162 impl<'tcx> Repr<'tcx> for ty::BuiltinBound {
1163 fn repr(&self, _tcx: &ctxt) -> String {
1164 format!("{:?}", *self)
1168 impl<'tcx> UserString<'tcx> for ty::BuiltinBound {
1169 fn user_string(&self, _tcx: &ctxt) -> String {
1171 ty::BoundSend => "Send".to_string(),
1172 ty::BoundSized => "Sized".to_string(),
1173 ty::BoundCopy => "Copy".to_string(),
1174 ty::BoundSync => "Sync".to_string(),
1179 impl<'tcx> Repr<'tcx> for Span {
1180 fn repr(&self, tcx: &ctxt) -> String {
1181 tcx.sess.codemap().span_to_string(*self).to_string()
1185 impl<'tcx, A:UserString<'tcx>> UserString<'tcx> for Rc<A> {
1186 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1187 let this: &A = &**self;
1188 this.user_string(tcx)
1192 impl<'tcx> UserString<'tcx> for ty::ParamBounds<'tcx> {
1193 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1194 let mut result = Vec::new();
1195 let s = self.builtin_bounds.user_string(tcx);
1199 for n in &self.trait_bounds {
1200 result.push(n.user_string(tcx));
1202 result.connect(" + ")
1206 impl<'tcx> Repr<'tcx> for ty::ExistentialBounds<'tcx> {
1207 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1208 let mut res = Vec::new();
1210 let region_str = self.region_bound.user_string(tcx);
1211 if !region_str.is_empty() {
1212 res.push(region_str);
1215 for bound in &self.builtin_bounds {
1216 res.push(bound.user_string(tcx));
1219 for projection_bound in &self.projection_bounds {
1220 res.push(projection_bound.user_string(tcx));
1227 impl<'tcx> UserString<'tcx> for ty::BuiltinBounds {
1228 fn user_string(&self, tcx: &ctxt) -> String {
1230 .map(|bb| bb.user_string(tcx))
1231 .collect::<Vec<String>>()
1237 impl<'tcx, T> UserString<'tcx> for ty::Binder<T>
1238 where T : UserString<'tcx> + TypeFoldable<'tcx>
1240 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1241 // Replace any anonymous late-bound regions with named
1242 // variants, using gensym'd identifiers, so that we can
1243 // clearly differentiate between named and unnamed regions in
1244 // the output. We'll probably want to tweak this over time to
1245 // decide just how much information to give.
1246 let mut names = Vec::new();
1247 let (unbound_value, _) = ty::replace_late_bound_regions(tcx, self, |br| {
1248 ty::ReLateBound(ty::DebruijnIndex::new(1), match br {
1249 ty::BrNamed(_, name) => {
1250 names.push(token::get_name(name));
1256 let name = token::gensym("'r");
1257 names.push(token::get_name(name));
1258 ty::BrNamed(ast_util::local_def(ast::DUMMY_NODE_ID), name)
1262 let names: Vec<_> = names.iter().map(|s| &s[]).collect();
1264 let value_str = unbound_value.user_string(tcx);
1265 if names.len() == 0 {
1268 format!("for<{}> {}", names.connect(","), value_str)
1273 impl<'tcx> UserString<'tcx> for ty::TraitRef<'tcx> {
1274 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1275 let path_str = ty::item_path_str(tcx, self.def_id);
1276 parameterized(tcx, &path_str, self.substs, self.def_id, &[],
1277 || ty::lookup_trait_def(tcx, self.def_id).generics.clone())
1281 impl<'tcx> UserString<'tcx> for Ty<'tcx> {
1282 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1283 ty_to_string(tcx, *self)
1287 impl<'tcx> UserString<'tcx> for ast::Ident {
1288 fn user_string(&self, _tcx: &ctxt) -> String {
1289 token::get_name(self.name).to_string()
1293 impl<'tcx> Repr<'tcx> for abi::Abi {
1294 fn repr(&self, _tcx: &ctxt) -> String {
1299 impl<'tcx> UserString<'tcx> for abi::Abi {
1300 fn user_string(&self, _tcx: &ctxt) -> String {
1305 impl<'tcx> Repr<'tcx> for ty::UpvarId {
1306 fn repr(&self, tcx: &ctxt) -> String {
1307 format!("UpvarId({};`{}`;{})",
1309 ty::local_var_name_str(tcx, self.var_id),
1310 self.closure_expr_id)
1314 impl<'tcx> Repr<'tcx> for ast::Mutability {
1315 fn repr(&self, _tcx: &ctxt) -> String {
1316 format!("{:?}", *self)
1320 impl<'tcx> Repr<'tcx> for ty::BorrowKind {
1321 fn repr(&self, _tcx: &ctxt) -> String {
1322 format!("{:?}", *self)
1326 impl<'tcx> Repr<'tcx> for ty::UpvarBorrow {
1327 fn repr(&self, tcx: &ctxt) -> String {
1328 format!("UpvarBorrow({}, {})",
1329 self.kind.repr(tcx),
1330 self.region.repr(tcx))
1334 impl<'tcx> Repr<'tcx> for ty::UpvarCapture {
1335 fn repr(&self, tcx: &ctxt) -> String {
1337 ty::UpvarCapture::ByValue => format!("ByValue"),
1338 ty::UpvarCapture::ByRef(ref data) => format!("ByRef({})", data.repr(tcx)),
1343 impl<'tcx> Repr<'tcx> for ty::IntVid {
1344 fn repr(&self, _tcx: &ctxt) -> String {
1345 format!("{:?}", self)
1349 impl<'tcx> Repr<'tcx> for ty::FloatVid {
1350 fn repr(&self, _tcx: &ctxt) -> String {
1351 format!("{:?}", self)
1355 impl<'tcx> Repr<'tcx> for ty::RegionVid {
1356 fn repr(&self, _tcx: &ctxt) -> String {
1357 format!("{:?}", self)
1361 impl<'tcx> Repr<'tcx> for ty::TyVid {
1362 fn repr(&self, _tcx: &ctxt) -> String {
1363 format!("{:?}", self)
1367 impl<'tcx> Repr<'tcx> for ty::IntVarValue {
1368 fn repr(&self, _tcx: &ctxt) -> String {
1369 format!("{:?}", *self)
1373 impl<'tcx> Repr<'tcx> for ast::IntTy {
1374 fn repr(&self, _tcx: &ctxt) -> String {
1375 format!("{:?}", *self)
1379 impl<'tcx> Repr<'tcx> for ast::UintTy {
1380 fn repr(&self, _tcx: &ctxt) -> String {
1381 format!("{:?}", *self)
1385 impl<'tcx> Repr<'tcx> for ast::FloatTy {
1386 fn repr(&self, _tcx: &ctxt) -> String {
1387 format!("{:?}", *self)
1391 impl<'tcx> Repr<'tcx> for ty::ExplicitSelfCategory {
1392 fn repr(&self, _: &ctxt) -> String {
1393 explicit_self_category_to_str(self).to_string()
1397 impl<'tcx> UserString<'tcx> for ParamTy {
1398 fn user_string(&self, _tcx: &ctxt) -> String {
1399 format!("{}", token::get_name(self.name))
1403 impl<'tcx> Repr<'tcx> for ParamTy {
1404 fn repr(&self, tcx: &ctxt) -> String {
1405 let ident = self.user_string(tcx);
1406 format!("{}/{:?}.{}", ident, self.space, self.idx)
1410 impl<'tcx, A:Repr<'tcx>, B:Repr<'tcx>> Repr<'tcx> for (A,B) {
1411 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1412 let &(ref a, ref b) = self;
1413 format!("({},{})", a.repr(tcx), b.repr(tcx))
1417 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for ty::Binder<T> {
1418 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1419 format!("Binder({})", self.0.repr(tcx))
1423 impl<'tcx, S, K, V> Repr<'tcx> for HashMap<K, V, S>
1424 where K: Hash<<S as HashState>::Hasher> + Eq + Repr<'tcx>,
1427 <S as HashState>::Hasher: Hasher<Output=u64>,
1429 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1430 format!("HashMap({})",
1432 .map(|(k,v)| format!("{} => {}", k.repr(tcx), v.repr(tcx)))
1433 .collect::<Vec<String>>()
1438 impl<'tcx, T, U> Repr<'tcx> for ty::OutlivesPredicate<T,U>
1439 where T : Repr<'tcx> + TypeFoldable<'tcx>,
1440 U : Repr<'tcx> + TypeFoldable<'tcx>,
1442 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1443 format!("OutlivesPredicate({}, {})",
1449 impl<'tcx, T, U> UserString<'tcx> for ty::OutlivesPredicate<T,U>
1450 where T : UserString<'tcx> + TypeFoldable<'tcx>,
1451 U : UserString<'tcx> + TypeFoldable<'tcx>,
1453 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1455 self.0.user_string(tcx),
1456 self.1.user_string(tcx))
1460 impl<'tcx> Repr<'tcx> for ty::EquatePredicate<'tcx> {
1461 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1462 format!("EquatePredicate({}, {})",
1468 impl<'tcx> UserString<'tcx> for ty::EquatePredicate<'tcx> {
1469 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1471 self.0.user_string(tcx),
1472 self.1.user_string(tcx))
1476 impl<'tcx> Repr<'tcx> for ty::TraitPredicate<'tcx> {
1477 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1478 format!("TraitPredicate({})",
1479 self.trait_ref.repr(tcx))
1483 impl<'tcx> UserString<'tcx> for ty::TraitPredicate<'tcx> {
1484 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1486 self.trait_ref.self_ty().user_string(tcx),
1487 self.trait_ref.user_string(tcx))
1491 impl<'tcx> UserString<'tcx> for ty::ProjectionPredicate<'tcx> {
1492 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1494 self.projection_ty.user_string(tcx),
1495 self.ty.user_string(tcx))
1499 impl<'tcx> Repr<'tcx> for ty::ProjectionTy<'tcx> {
1500 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1501 format!("<{} as {}>::{}",
1502 self.trait_ref.substs.self_ty().repr(tcx),
1503 self.trait_ref.repr(tcx),
1504 self.item_name.repr(tcx))
1508 impl<'tcx> UserString<'tcx> for ty::ProjectionTy<'tcx> {
1509 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1510 format!("<{} as {}>::{}",
1511 self.trait_ref.self_ty().user_string(tcx),
1512 self.trait_ref.user_string(tcx),
1513 self.item_name.user_string(tcx))
1517 impl<'tcx> UserString<'tcx> for ty::Predicate<'tcx> {
1518 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1520 ty::Predicate::Trait(ref data) => data.user_string(tcx),
1521 ty::Predicate::Equate(ref predicate) => predicate.user_string(tcx),
1522 ty::Predicate::RegionOutlives(ref predicate) => predicate.user_string(tcx),
1523 ty::Predicate::TypeOutlives(ref predicate) => predicate.user_string(tcx),
1524 ty::Predicate::Projection(ref predicate) => predicate.user_string(tcx),