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};
27 use middle::typeck::check::regionmanip;
32 use syntax::codemap::{Span, Pos};
33 use syntax::parse::token;
34 use syntax::print::pprust;
36 use syntax::{ast, ast_util};
37 use syntax::owned_slice::OwnedSlice;
39 /// Produces a string suitable for debugging output.
40 pub trait Repr<'tcx> for Sized? {
41 fn repr(&self, tcx: &ctxt<'tcx>) -> String;
44 /// Produces a string suitable for showing to the user.
45 pub trait UserString<'tcx> {
46 fn user_string(&self, tcx: &ctxt<'tcx>) -> String;
49 pub fn note_and_explain_region(cx: &ctxt,
52 suffix: &str) -> Option<Span> {
53 match explain_region_and_span(cx, region) {
54 (ref str, Some(span)) => {
57 format!("{}{}{}", prefix, *str, suffix).as_slice());
62 format!("{}{}{}", prefix, *str, suffix).as_slice());
68 /// When a free region is associated with `item`, how should we describe the item in the error
70 fn item_scope_tag(item: &ast::Item) -> &'static str {
72 ast::ItemImpl(..) => "impl",
73 ast::ItemStruct(..) => "struct",
74 ast::ItemEnum(..) => "enum",
75 ast::ItemTrait(..) => "trait",
76 ast::ItemFn(..) => "function body",
81 pub fn explain_region_and_span(cx: &ctxt, region: ty::Region)
82 -> (String, Option<Span>) {
85 match cx.map.find(scope.node_id()) {
86 Some(ast_map::NodeBlock(ref blk)) => {
87 explain_span(cx, "block", blk.span)
89 Some(ast_map::NodeExpr(expr)) => {
91 ast::ExprCall(..) => explain_span(cx, "call", expr.span),
92 ast::ExprMethodCall(..) => {
93 explain_span(cx, "method call", expr.span)
95 ast::ExprMatch(_, _, ast::MatchIfLetDesugar) => explain_span(cx, "if let", expr.span),
96 ast::ExprMatch(_, _, ast::MatchWhileLetDesugar) => {
97 explain_span(cx, "while let", expr.span)
99 ast::ExprMatch(..) => explain_span(cx, "match", expr.span),
100 _ => explain_span(cx, "expression", expr.span)
103 Some(ast_map::NodeStmt(stmt)) => {
104 explain_span(cx, "statement", stmt.span)
106 Some(ast_map::NodeItem(it)) => {
107 let tag = item_scope_tag(&*it);
108 explain_span(cx, tag, it.span)
111 // this really should not happen
112 (format!("unknown scope: {}. Please report a bug.", scope), None)
118 let prefix = match fr.bound_region {
120 format!("the anonymous lifetime #{} defined on", idx + 1)
122 BrFresh(_) => "an anonymous lifetime defined on".to_string(),
124 format!("the lifetime {} as defined on",
125 bound_region_ptr_to_string(cx, fr.bound_region))
129 match cx.map.find(fr.scope.node_id()) {
130 Some(ast_map::NodeBlock(ref blk)) => {
131 let (msg, opt_span) = explain_span(cx, "block", blk.span);
132 (format!("{} {}", prefix, msg), opt_span)
134 Some(ast_map::NodeItem(it)) => {
135 let tag = item_scope_tag(&*it);
136 let (msg, opt_span) = explain_span(cx, tag, it.span);
137 (format!("{} {}", prefix, msg), opt_span)
140 // this really should not happen
141 (format!("{} unknown free region bounded by scope {}", prefix, fr.scope), None)
146 ReStatic => { ("the static lifetime".to_string(), None) }
148 ReEmpty => { ("the empty lifetime".to_string(), None) }
150 ReEarlyBound(_, _, _, name) => {
151 (format!("{}", token::get_name(name)), None)
154 // I believe these cases should not occur (except when debugging,
156 ty::ReInfer(_) | ty::ReLateBound(..) => {
157 (format!("lifetime {}", region), None)
161 fn explain_span(cx: &ctxt, heading: &str, span: Span)
162 -> (String, Option<Span>) {
163 let lo = cx.sess.codemap().lookup_char_pos_adj(span.lo);
164 (format!("the {} at {}:{}", heading, lo.line, lo.col.to_uint()),
169 pub fn bound_region_ptr_to_string(cx: &ctxt, br: BoundRegion) -> String {
170 bound_region_to_string(cx, "", false, br)
173 pub fn bound_region_to_string(cx: &ctxt,
174 prefix: &str, space: bool,
175 br: BoundRegion) -> String {
176 let space_str = if space { " " } else { "" };
178 if cx.sess.verbose() {
179 return format!("{}{}{}", prefix, br.repr(cx), space_str)
183 BrNamed(_, name) => {
184 format!("{}{}{}", prefix, token::get_name(name), space_str)
186 BrAnon(_) | BrFresh(_) | BrEnv => prefix.to_string()
190 // In general, if you are giving a region error message,
191 // you should use `explain_region()` or, better yet,
192 // `note_and_explain_region()`
193 pub fn region_ptr_to_string(cx: &ctxt, region: Region) -> String {
194 region_to_string(cx, "&", true, region)
197 pub fn region_to_string(cx: &ctxt, prefix: &str, space: bool, region: Region) -> String {
198 let space_str = if space { " " } else { "" };
200 if cx.sess.verbose() {
201 return format!("{}{}{}", prefix, region.repr(cx), space_str)
204 // These printouts are concise. They do not contain all the information
205 // the user might want to diagnose an error, but there is basically no way
206 // to fit that into a short string. Hence the recommendation to use
207 // `explain_region()` or `note_and_explain_region()`.
209 ty::ReScope(_) => prefix.to_string(),
210 ty::ReEarlyBound(_, _, _, name) => {
211 token::get_name(name).get().to_string()
213 ty::ReLateBound(_, br) => bound_region_to_string(cx, prefix, space, br),
214 ty::ReFree(ref fr) => bound_region_to_string(cx, prefix, space, fr.bound_region),
215 ty::ReInfer(ReSkolemized(_, br)) => {
216 bound_region_to_string(cx, prefix, space, br)
218 ty::ReInfer(ReVar(_)) => prefix.to_string(),
219 ty::ReStatic => format!("{}'static{}", prefix, space_str),
220 ty::ReEmpty => format!("{}'<empty>{}", prefix, space_str),
224 pub fn mutability_to_string(m: ast::Mutability) -> String {
226 ast::MutMutable => "mut ".to_string(),
227 ast::MutImmutable => "".to_string(),
231 pub fn mt_to_string<'tcx>(cx: &ctxt<'tcx>, m: &mt<'tcx>) -> String {
233 mutability_to_string(m.mutbl),
234 ty_to_string(cx, m.ty))
237 pub fn trait_store_to_string(cx: &ctxt, s: ty::TraitStore) -> String {
239 ty::UniqTraitStore => "Box ".to_string(),
240 ty::RegionTraitStore(r, m) => {
241 format!("{}{}", region_ptr_to_string(cx, r), mutability_to_string(m))
246 pub fn vec_map_to_string<T>(ts: &[T], f: |t: &T| -> String) -> String {
247 let tstrs = ts.iter().map(f).collect::<Vec<String>>();
248 format!("[{}]", tstrs.connect(", "))
251 pub fn fn_sig_to_string<'tcx>(cx: &ctxt<'tcx>, typ: &ty::FnSig<'tcx>) -> String {
252 format!("fn{} -> {}", typ.inputs.repr(cx), typ.output.repr(cx))
255 pub fn trait_ref_to_string<'tcx>(cx: &ctxt<'tcx>,
256 trait_ref: &ty::TraitRef<'tcx>) -> String {
257 trait_ref.user_string(cx).to_string()
260 pub fn ty_to_string<'tcx>(cx: &ctxt<'tcx>, typ: &ty::TyS<'tcx>) -> String {
261 fn bare_fn_to_string<'tcx>(cx: &ctxt<'tcx>,
262 fn_style: ast::FnStyle,
264 ident: Option<ast::Ident>,
265 sig: &ty::FnSig<'tcx>)
267 let mut s = String::new();
271 s.push_str(fn_style.to_string().as_slice());
276 if abi != abi::Rust {
277 s.push_str(format!("extern {} ", abi.to_string()).as_slice());
285 s.push_str(token::get_ident(i).get());
290 push_sig_to_string(cx, &mut s, '(', ')', sig, "");
295 fn closure_to_string<'tcx>(cx: &ctxt<'tcx>, cty: &ty::ClosureTy<'tcx>) -> String {
296 let mut s = String::new();
299 ty::UniqTraitStore => {}
300 ty::RegionTraitStore(region, _) => {
301 s.push_str(region_to_string(cx, "", true, region).as_slice());
308 s.push_str(cty.fn_style.to_string().as_slice());
313 let bounds_str = cty.bounds.user_string(cx);
316 ty::UniqTraitStore => {
317 assert_eq!(cty.onceness, ast::Once);
319 push_sig_to_string(cx, &mut s, '(', ')', &cty.sig,
320 bounds_str.as_slice());
322 ty::RegionTraitStore(..) => {
325 ast::Once => s.push_str("once ")
327 push_sig_to_string(cx, &mut s, '|', '|', &cty.sig,
328 bounds_str.as_slice());
335 fn push_sig_to_string<'tcx>(cx: &ctxt<'tcx>,
339 sig: &ty::FnSig<'tcx>,
342 let strs = sig.inputs
344 .map(|a| ty_to_string(cx, *a))
345 .collect::<Vec<_>>();
346 s.push_str(strs.connect(", ").as_slice());
352 if !bounds.is_empty() {
358 ty::FnConverging(t) => {
359 if !ty::type_is_nil(t) {
361 s.push_str(ty_to_string(cx, t).as_slice());
370 fn infer_ty_to_string(cx: &ctxt, ty: ty::InferTy) -> String {
371 let print_var_ids = cx.sess.verbose();
373 ty::TyVar(ref vid) if print_var_ids => vid.repr(cx),
374 ty::IntVar(ref vid) if print_var_ids => vid.repr(cx),
375 ty::FloatVar(ref vid) if print_var_ids => vid.repr(cx),
376 ty::TyVar(_) | ty::IntVar(_) | ty::FloatVar(_) => format!("_"),
377 ty::SkolemizedTy(v) => format!("SkolemizedTy({})", v),
378 ty::SkolemizedIntTy(v) => format!("SkolemizedIntTy({})", v)
382 // pretty print the structural type representation:
384 ty_bool => "bool".to_string(),
385 ty_char => "char".to_string(),
386 ty_int(t) => ast_util::int_ty_to_string(t, None).to_string(),
387 ty_uint(t) => ast_util::uint_ty_to_string(t, None).to_string(),
388 ty_float(t) => ast_util::float_ty_to_string(t).to_string(),
389 ty_uniq(typ) => format!("Box<{}>", ty_to_string(cx, typ)),
391 format!("*{} {}", match tm.mutbl {
392 ast::MutMutable => "mut",
393 ast::MutImmutable => "const",
394 }, ty_to_string(cx, tm.ty))
396 ty_rptr(r, ref tm) => {
397 let mut buf = region_ptr_to_string(cx, r);
398 buf.push_str(mt_to_string(cx, tm).as_slice());
402 format!("opened<{}>", ty_to_string(cx, typ)),
403 ty_tup(ref elems) => {
406 .map(|elem| ty_to_string(cx, *elem))
407 .collect::<Vec<_>>();
408 match strs.as_slice() {
409 [ref string] => format!("({},)", string),
410 strs => format!("({})", strs.connect(", "))
413 ty_closure(ref f) => {
414 closure_to_string(cx, &**f)
416 ty_bare_fn(ref f) => {
417 bare_fn_to_string(cx, f.fn_style, f.abi, None, &f.sig)
419 ty_infer(infer_ty) => infer_ty_to_string(cx, infer_ty),
420 ty_err => "[type error]".to_string(),
421 ty_param(ref param_ty) => {
422 if cx.sess.verbose() {
425 param_ty.user_string(cx)
428 ty_enum(did, ref substs) | ty_struct(did, ref substs) => {
429 let base = ty::item_path_str(cx, did);
430 let generics = ty::lookup_item_type(cx, did).generics;
431 parameterized(cx, base.as_slice(), substs, &generics)
433 ty_trait(box ty::TyTrait {
434 ref principal, ref bounds
436 let base = ty::item_path_str(cx, principal.def_id);
437 let trait_def = ty::lookup_trait_def(cx, principal.def_id);
438 let ty = parameterized(cx, base.as_slice(),
439 &principal.substs, &trait_def.generics);
440 let bound_str = bounds.user_string(cx);
441 let bound_sep = if bound_str.is_empty() { "" } else { "+" };
447 ty_str => "str".to_string(),
448 ty_unboxed_closure(ref did, _, ref substs) => {
449 let unboxed_closures = cx.unboxed_closures.borrow();
450 unboxed_closures.get(did).map(|cl| {
451 closure_to_string(cx, &cl.closure_type.subst(cx, substs))
452 }).unwrap_or_else(|| "closure".to_string())
455 let inner_str = ty_to_string(cx, t);
457 Some(n) => format!("[{}, ..{}]", inner_str, n),
458 None => format!("[{}]", inner_str),
464 pub fn explicit_self_category_to_str(category: &ty::ExplicitSelfCategory)
467 ty::StaticExplicitSelfCategory => "static",
468 ty::ByValueExplicitSelfCategory => "self",
469 ty::ByReferenceExplicitSelfCategory(_, ast::MutMutable) => {
472 ty::ByReferenceExplicitSelfCategory(_, ast::MutImmutable) => "&self",
473 ty::ByBoxExplicitSelfCategory => "Box<self>",
477 pub fn parameterized<'tcx>(cx: &ctxt<'tcx>,
479 substs: &subst::Substs<'tcx>,
480 generics: &ty::Generics<'tcx>)
483 if cx.sess.verbose() {
484 if substs.is_noop() {
485 return format!("{}", base);
487 return format!("{}<{},{}>",
489 substs.regions.repr(cx),
490 substs.types.repr(cx));
494 let mut strs = Vec::new();
496 match substs.regions {
497 subst::ErasedRegions => { }
498 subst::NonerasedRegions(ref regions) => {
499 for &r in regions.iter() {
500 let s = region_to_string(cx, "", false, r);
502 // This happens when the value of the region
503 // parameter is not easily serialized. This may be
504 // because the user omitted it in the first place,
505 // or because it refers to some block in the code,
506 // etc. I'm not sure how best to serialize this.
507 strs.push(format!("'_"));
515 let tps = substs.types.get_slice(subst::TypeSpace);
516 let ty_params = generics.types.get_slice(subst::TypeSpace);
517 let has_defaults = ty_params.last().map_or(false, |def| def.default.is_some());
518 let num_defaults = if has_defaults {
519 ty_params.iter().zip(tps.iter()).rev().take_while(|&(def, &actual)| {
521 Some(default) => default.subst(cx, substs) == actual,
529 for t in tps[..tps.len() - num_defaults].iter() {
530 strs.push(ty_to_string(cx, *t))
534 format!("{}<{}>", base, strs.connect(", "))
540 pub fn ty_to_short_str<'tcx>(cx: &ctxt<'tcx>, typ: Ty<'tcx>) -> String {
541 let mut s = typ.repr(cx).to_string();
543 s = s.as_slice().slice(0u, 32u).to_string();
548 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for Option<T> {
549 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
551 &None => "None".to_string(),
552 &Some(ref t) => t.repr(tcx),
557 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for P<T> {
558 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
563 impl<'tcx,T:Repr<'tcx>,U:Repr<'tcx>> Repr<'tcx> for Result<T,U> {
564 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
566 &Ok(ref t) => t.repr(tcx),
567 &Err(ref u) => format!("Err({})", u.repr(tcx))
572 impl<'tcx> Repr<'tcx> for () {
573 fn repr(&self, _tcx: &ctxt) -> String {
578 impl<'a, 'tcx, Sized? T:Repr<'tcx>> Repr<'tcx> for &'a T {
579 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
580 Repr::repr(*self, tcx)
584 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for Rc<T> {
585 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
590 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for Box<T> {
591 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
596 fn repr_vec<'tcx, T:Repr<'tcx>>(tcx: &ctxt<'tcx>, v: &[T]) -> String {
597 vec_map_to_string(v, |t| t.repr(tcx))
600 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for [T] {
601 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
606 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for OwnedSlice<T> {
607 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
608 repr_vec(tcx, self.as_slice())
612 // This is necessary to handle types like Option<~[T]>, for which
613 // autoderef cannot convert the &[T] handler
614 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for Vec<T> {
615 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
616 repr_vec(tcx, self.as_slice())
620 impl<'tcx, T:UserString<'tcx>> UserString<'tcx> for Vec<T> {
621 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
622 let strs: Vec<String> =
623 self.iter().map(|t| t.user_string(tcx)).collect();
628 impl<'tcx> Repr<'tcx> for def::Def {
629 fn repr(&self, _tcx: &ctxt) -> String {
634 impl<'tcx> Repr<'tcx> for ty::TypeParameterDef<'tcx> {
635 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
636 format!("TypeParameterDef({}, {}, {}/{})",
638 self.bounds.repr(tcx),
644 impl<'tcx> Repr<'tcx> for ty::RegionParameterDef {
645 fn repr(&self, tcx: &ctxt) -> String {
646 format!("RegionParameterDef(name={}, def_id={}, bounds={})",
647 token::get_name(self.name),
648 self.def_id.repr(tcx),
649 self.bounds.repr(tcx))
653 impl<'tcx> Repr<'tcx> for ty::TyS<'tcx> {
654 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
655 ty_to_string(tcx, self)
659 impl<'tcx> Repr<'tcx> for ty::mt<'tcx> {
660 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
661 mt_to_string(tcx, self)
665 impl<'tcx> Repr<'tcx> for subst::Substs<'tcx> {
666 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
667 format!("Substs[types={}, regions={}]",
668 self.types.repr(tcx),
669 self.regions.repr(tcx))
673 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for subst::VecPerParamSpace<T> {
674 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
675 format!("[{};{};{};{}]",
676 self.get_slice(subst::TypeSpace).repr(tcx),
677 self.get_slice(subst::SelfSpace).repr(tcx),
678 self.get_slice(subst::AssocSpace).repr(tcx),
679 self.get_slice(subst::FnSpace).repr(tcx))
683 impl<'tcx> Repr<'tcx> for ty::ItemSubsts<'tcx> {
684 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
685 format!("ItemSubsts({})", self.substs.repr(tcx))
689 impl<'tcx> Repr<'tcx> for subst::RegionSubsts {
690 fn repr(&self, tcx: &ctxt) -> String {
692 subst::ErasedRegions => "erased".to_string(),
693 subst::NonerasedRegions(ref regions) => regions.repr(tcx)
698 impl<'tcx> Repr<'tcx> for ty::BuiltinBounds {
699 fn repr(&self, _tcx: &ctxt) -> String {
700 let mut res = Vec::new();
701 for b in self.iter() {
703 ty::BoundSend => "Send".to_string(),
704 ty::BoundSized => "Sized".to_string(),
705 ty::BoundCopy => "Copy".to_string(),
706 ty::BoundSync => "Sync".to_string(),
713 impl<'tcx> Repr<'tcx> for ty::ExistentialBounds {
714 fn repr(&self, tcx: &ctxt) -> String {
715 self.user_string(tcx)
719 impl<'tcx> Repr<'tcx> for ty::ParamBounds<'tcx> {
720 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
721 let mut res = Vec::new();
722 res.push(self.builtin_bounds.repr(tcx));
723 for t in self.trait_bounds.iter() {
724 res.push(t.repr(tcx));
730 impl<'tcx> Repr<'tcx> for ty::TraitRef<'tcx> {
731 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
732 // when printing out the debug representation, we don't need
733 // to enumerate the `for<...>` etc because the debruijn index
734 // tells you everything you need to know.
735 let base = ty::item_path_str(tcx, self.def_id);
736 let trait_def = ty::lookup_trait_def(tcx, self.def_id);
738 self.substs.self_ty().repr(tcx),
739 parameterized(tcx, base.as_slice(), &self.substs, &trait_def.generics))
743 impl<'tcx> Repr<'tcx> for ty::TraitDef<'tcx> {
744 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
745 format!("TraitDef(generics={}, bounds={}, trait_ref={})",
746 self.generics.repr(tcx),
747 self.bounds.repr(tcx),
748 self.trait_ref.repr(tcx))
752 impl<'tcx> Repr<'tcx> for ast::TraitItem {
753 fn repr(&self, _tcx: &ctxt) -> String {
755 ast::RequiredMethod(ref data) => format!("RequiredMethod({}, id={})",
756 data.ident, data.id),
757 ast::ProvidedMethod(ref data) => format!("ProvidedMethod(id={})",
759 ast::TypeTraitItem(ref data) => format!("TypeTraitItem({}, id={})",
760 data.ty_param.ident, data.ty_param.id),
765 impl<'tcx> Repr<'tcx> for ast::Expr {
766 fn repr(&self, _tcx: &ctxt) -> String {
767 format!("expr({}: {})", self.id, pprust::expr_to_string(self))
771 impl<'tcx> Repr<'tcx> for ast::Path {
772 fn repr(&self, _tcx: &ctxt) -> String {
773 format!("path({})", pprust::path_to_string(self))
777 impl<'tcx> UserString<'tcx> for ast::Path {
778 fn user_string(&self, _tcx: &ctxt) -> String {
779 pprust::path_to_string(self)
783 impl<'tcx> Repr<'tcx> for ast::Ty {
784 fn repr(&self, _tcx: &ctxt) -> String {
785 format!("type({})", pprust::ty_to_string(self))
789 impl<'tcx> Repr<'tcx> for ast::Item {
790 fn repr(&self, tcx: &ctxt) -> String {
791 format!("item({})", tcx.map.node_to_string(self.id))
795 impl<'tcx> Repr<'tcx> for ast::Lifetime {
796 fn repr(&self, _tcx: &ctxt) -> String {
797 format!("lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
801 impl<'tcx> Repr<'tcx> for ast::Stmt {
802 fn repr(&self, _tcx: &ctxt) -> String {
803 format!("stmt({}: {})",
804 ast_util::stmt_id(self),
805 pprust::stmt_to_string(self))
809 impl<'tcx> Repr<'tcx> for ast::Pat {
810 fn repr(&self, _tcx: &ctxt) -> String {
811 format!("pat({}: {})", self.id, pprust::pat_to_string(self))
815 impl<'tcx> Repr<'tcx> for ty::BoundRegion {
816 fn repr(&self, tcx: &ctxt) -> String {
818 ty::BrAnon(id) => format!("BrAnon({})", id),
819 ty::BrNamed(id, name) => {
820 format!("BrNamed({}, {})", id.repr(tcx), token::get_name(name))
822 ty::BrFresh(id) => format!("BrFresh({})", id),
823 ty::BrEnv => "BrEnv".to_string()
828 impl<'tcx> Repr<'tcx> for ty::Region {
829 fn repr(&self, tcx: &ctxt) -> String {
831 ty::ReEarlyBound(id, space, index, name) => {
832 format!("ReEarlyBound({}, {}, {}, {})",
836 token::get_name(name))
839 ty::ReLateBound(binder_id, ref bound_region) => {
840 format!("ReLateBound({}, {})",
842 bound_region.repr(tcx))
845 ty::ReFree(ref fr) => fr.repr(tcx),
848 format!("ReScope({})", id)
852 "ReStatic".to_string()
855 ty::ReInfer(ReVar(ref vid)) => {
859 ty::ReInfer(ReSkolemized(id, ref bound_region)) => {
860 format!("re_skolemized({}, {})", id, bound_region.repr(tcx))
864 "ReEmpty".to_string()
870 impl<'tcx> UserString<'tcx> for ty::Region {
871 fn user_string(&self, tcx: &ctxt) -> String {
872 region_to_string(tcx, "", false, *self)
876 impl<'tcx> Repr<'tcx> for ty::FreeRegion {
877 fn repr(&self, tcx: &ctxt) -> String {
878 format!("ReFree({}, {})",
879 self.scope.node_id(),
880 self.bound_region.repr(tcx))
884 impl<'tcx> Repr<'tcx> for ast::DefId {
885 fn repr(&self, tcx: &ctxt) -> String {
886 // Unfortunately, there seems to be no way to attempt to print
887 // a path for a def-id, so I'll just make a best effort for now
888 // and otherwise fallback to just printing the crate/node pair
889 if self.krate == ast::LOCAL_CRATE {
890 match tcx.map.find(self.node) {
891 Some(ast_map::NodeItem(..)) |
892 Some(ast_map::NodeForeignItem(..)) |
893 Some(ast_map::NodeImplItem(..)) |
894 Some(ast_map::NodeTraitItem(..)) |
895 Some(ast_map::NodeVariant(..)) |
896 Some(ast_map::NodeStructCtor(..)) => {
900 ty::item_path_str(tcx, *self))
905 return format!("{}", *self)
909 impl<'tcx> Repr<'tcx> for ty::Polytype<'tcx> {
910 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
911 format!("Polytype {{generics: {}, ty: {}}}",
912 self.generics.repr(tcx),
917 impl<'tcx> Repr<'tcx> for ty::Generics<'tcx> {
918 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
919 format!("Generics(types: {}, regions: {})",
920 self.types.repr(tcx),
921 self.regions.repr(tcx))
925 impl<'tcx> Repr<'tcx> for ty::GenericBounds<'tcx> {
926 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
927 format!("GenericBounds(types: {}, regions: {})",
928 self.types.repr(tcx),
929 self.regions.repr(tcx))
933 impl<'tcx> Repr<'tcx> for ty::ItemVariances {
934 fn repr(&self, tcx: &ctxt) -> String {
935 format!("ItemVariances(types={}, \
937 self.types.repr(tcx),
938 self.regions.repr(tcx))
942 impl<'tcx> Repr<'tcx> for ty::Variance {
943 fn repr(&self, _: &ctxt) -> String {
944 // The first `.to_string()` returns a &'static str (it is not an implementation
945 // of the ToString trait). Because of that, we need to call `.to_string()` again
946 // if we want to have a `String`.
947 let result: &'static str = (*self).to_string();
952 impl<'tcx> Repr<'tcx> for ty::Method<'tcx> {
953 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
954 format!("method(name: {}, generics: {}, fty: {}, \
955 explicit_self: {}, vis: {}, def_id: {})",
957 self.generics.repr(tcx),
959 self.explicit_self.repr(tcx),
961 self.def_id.repr(tcx))
965 impl<'tcx> Repr<'tcx> for ast::Name {
966 fn repr(&self, _tcx: &ctxt) -> String {
967 token::get_name(*self).get().to_string()
971 impl<'tcx> UserString<'tcx> for ast::Name {
972 fn user_string(&self, _tcx: &ctxt) -> String {
973 token::get_name(*self).get().to_string()
977 impl<'tcx> Repr<'tcx> for ast::Ident {
978 fn repr(&self, _tcx: &ctxt) -> String {
979 token::get_ident(*self).get().to_string()
983 impl<'tcx> Repr<'tcx> for ast::ExplicitSelf_ {
984 fn repr(&self, _tcx: &ctxt) -> String {
989 impl<'tcx> Repr<'tcx> for ast::Visibility {
990 fn repr(&self, _tcx: &ctxt) -> String {
995 impl<'tcx> Repr<'tcx> for ty::BareFnTy<'tcx> {
996 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
997 format!("BareFnTy {{fn_style: {}, abi: {}, sig: {}}}",
999 self.abi.to_string(),
1004 impl<'tcx> Repr<'tcx> for ty::FnSig<'tcx> {
1005 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1006 fn_sig_to_string(tcx, self)
1010 impl<'tcx> Repr<'tcx> for ty::FnOutput<'tcx> {
1011 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1013 ty::FnConverging(ty) =>
1014 format!("FnConverging({0})", ty.repr(tcx)),
1016 "FnDiverging".to_string()
1021 impl<'tcx> Repr<'tcx> for typeck::MethodCallee<'tcx> {
1022 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1023 format!("MethodCallee {{origin: {}, ty: {}, {}}}",
1024 self.origin.repr(tcx),
1026 self.substs.repr(tcx))
1030 impl<'tcx> Repr<'tcx> for typeck::MethodOrigin<'tcx> {
1031 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1033 &typeck::MethodStatic(def_id) => {
1034 format!("MethodStatic({})", def_id.repr(tcx))
1036 &typeck::MethodStaticUnboxedClosure(def_id) => {
1037 format!("MethodStaticUnboxedClosure({})", def_id.repr(tcx))
1039 &typeck::MethodTypeParam(ref p) => {
1042 &typeck::MethodTraitObject(ref p) => {
1049 impl<'tcx> Repr<'tcx> for typeck::MethodParam<'tcx> {
1050 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1051 format!("MethodParam({},{})",
1052 self.trait_ref.repr(tcx),
1057 impl<'tcx> Repr<'tcx> for typeck::MethodObject<'tcx> {
1058 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1059 format!("MethodObject({},{},{})",
1060 self.trait_ref.repr(tcx),
1066 impl<'tcx> Repr<'tcx> for ty::TraitStore {
1067 fn repr(&self, tcx: &ctxt) -> String {
1068 trait_store_to_string(tcx, *self)
1072 impl<'tcx> Repr<'tcx> for ty::BuiltinBound {
1073 fn repr(&self, _tcx: &ctxt) -> String {
1074 format!("{}", *self)
1078 impl<'tcx> UserString<'tcx> for ty::BuiltinBound {
1079 fn user_string(&self, _tcx: &ctxt) -> String {
1081 ty::BoundSend => "Send".to_string(),
1082 ty::BoundSized => "Sized".to_string(),
1083 ty::BoundCopy => "Copy".to_string(),
1084 ty::BoundSync => "Sync".to_string(),
1089 impl<'tcx> Repr<'tcx> for Span {
1090 fn repr(&self, tcx: &ctxt) -> String {
1091 tcx.sess.codemap().span_to_string(*self).to_string()
1095 impl<'tcx, A:UserString<'tcx>> UserString<'tcx> for Rc<A> {
1096 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1097 let this: &A = &**self;
1098 this.user_string(tcx)
1102 impl<'tcx> UserString<'tcx> for ty::ParamBounds<'tcx> {
1103 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1104 let mut result = Vec::new();
1105 let s = self.builtin_bounds.user_string(tcx);
1109 for n in self.trait_bounds.iter() {
1110 result.push(n.user_string(tcx));
1116 impl<'tcx> UserString<'tcx> for ty::ExistentialBounds {
1117 fn user_string(&self, tcx: &ctxt) -> String {
1118 if self.builtin_bounds.contains(&ty::BoundSend) &&
1119 self.region_bound == ty::ReStatic
1120 { // Region bound is implied by builtin bounds:
1121 return self.builtin_bounds.repr(tcx);
1124 let mut res = Vec::new();
1126 let region_str = self.region_bound.user_string(tcx);
1127 if !region_str.is_empty() {
1128 res.push(region_str);
1131 for bound in self.builtin_bounds.iter() {
1132 res.push(bound.user_string(tcx));
1139 impl<'tcx> UserString<'tcx> for ty::BuiltinBounds {
1140 fn user_string(&self, tcx: &ctxt) -> String {
1142 .map(|bb| bb.user_string(tcx))
1143 .collect::<Vec<String>>()
1149 impl<'tcx> UserString<'tcx> for ty::TraitRef<'tcx> {
1150 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1151 // Replace any anonymous late-bound regions with named
1152 // variants, using gensym'd identifiers, so that we can
1153 // clearly differentiate between named and unnamed regions in
1154 // the output. We'll probably want to tweak this over time to
1155 // decide just how much information to give.
1156 let mut names = Vec::new();
1157 let (trait_ref, _) = ty::replace_late_bound_regions(tcx, self, |br, debruijn| {
1158 ty::ReLateBound(debruijn, match br {
1159 ty::BrNamed(_, name) => {
1160 names.push(token::get_name(name));
1166 let name = token::gensym("r");
1167 names.push(token::get_name(name));
1168 ty::BrNamed(ast_util::local_def(ast::DUMMY_NODE_ID), name)
1172 let names: Vec<_> = names.iter().map(|s| s.get()).collect();
1174 // Let the base string be either `SomeTrait` for `for<'a,'b> SomeTrait`,
1175 // depending on whether there are bound regions.
1176 let path_str = ty::item_path_str(tcx, self.def_id);
1178 if names.is_empty() {
1181 format!("for<{}> {}", names.connect(","), path_str)
1184 let trait_def = ty::lookup_trait_def(tcx, self.def_id);
1185 parameterized(tcx, base.as_slice(), &trait_ref.substs, &trait_def.generics)
1189 impl<'tcx> UserString<'tcx> for Ty<'tcx> {
1190 fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
1191 ty_to_string(tcx, *self)
1195 impl<'tcx> UserString<'tcx> for ast::Ident {
1196 fn user_string(&self, _tcx: &ctxt) -> String {
1197 token::get_name(self.name).get().to_string()
1201 impl<'tcx> Repr<'tcx> for abi::Abi {
1202 fn repr(&self, _tcx: &ctxt) -> String {
1207 impl<'tcx> UserString<'tcx> for abi::Abi {
1208 fn user_string(&self, _tcx: &ctxt) -> String {
1213 impl<'tcx> Repr<'tcx> for ty::UpvarId {
1214 fn repr(&self, tcx: &ctxt) -> String {
1215 format!("UpvarId({};`{}`;{})",
1217 ty::local_var_name_str(tcx, self.var_id),
1218 self.closure_expr_id)
1222 impl<'tcx> Repr<'tcx> for ast::Mutability {
1223 fn repr(&self, _tcx: &ctxt) -> String {
1224 format!("{}", *self)
1228 impl<'tcx> Repr<'tcx> for ty::BorrowKind {
1229 fn repr(&self, _tcx: &ctxt) -> String {
1230 format!("{}", *self)
1234 impl<'tcx> Repr<'tcx> for ty::UpvarBorrow {
1235 fn repr(&self, tcx: &ctxt) -> String {
1236 format!("UpvarBorrow({}, {})",
1237 self.kind.repr(tcx),
1238 self.region.repr(tcx))
1242 impl<'tcx> Repr<'tcx> for ty::IntVid {
1243 fn repr(&self, _tcx: &ctxt) -> String {
1248 impl<'tcx> Repr<'tcx> for ty::FloatVid {
1249 fn repr(&self, _tcx: &ctxt) -> String {
1254 impl<'tcx> Repr<'tcx> for ty::RegionVid {
1255 fn repr(&self, _tcx: &ctxt) -> String {
1260 impl<'tcx> Repr<'tcx> for ty::TyVid {
1261 fn repr(&self, _tcx: &ctxt) -> String {
1266 impl<'tcx> Repr<'tcx> for ty::IntVarValue {
1267 fn repr(&self, _tcx: &ctxt) -> String {
1268 format!("{}", *self)
1272 impl<'tcx> Repr<'tcx> for ast::IntTy {
1273 fn repr(&self, _tcx: &ctxt) -> String {
1274 format!("{}", *self)
1278 impl<'tcx> Repr<'tcx> for ast::UintTy {
1279 fn repr(&self, _tcx: &ctxt) -> String {
1280 format!("{}", *self)
1284 impl<'tcx> Repr<'tcx> for ast::FloatTy {
1285 fn repr(&self, _tcx: &ctxt) -> String {
1286 format!("{}", *self)
1290 impl<'tcx> Repr<'tcx> for ty::ExplicitSelfCategory {
1291 fn repr(&self, _: &ctxt) -> String {
1292 explicit_self_category_to_str(self).to_string()
1297 impl<'tcx> Repr<'tcx> for regionmanip::WfConstraint<'tcx> {
1298 fn repr(&self, tcx: &ctxt) -> String {
1300 regionmanip::RegionSubRegionConstraint(_, r_a, r_b) => {
1301 format!("RegionSubRegionConstraint({}, {})",
1306 regionmanip::RegionSubParamConstraint(_, r, p) => {
1307 format!("RegionSubParamConstraint({}, {})",
1315 impl<'tcx> UserString<'tcx> for ParamTy {
1316 fn user_string(&self, tcx: &ctxt) -> String {
1318 let did = self.def_id;
1319 let ident = match tcx.ty_param_defs.borrow().get(&did.node) {
1320 Some(def) => token::get_name(def.name).get().to_string(),
1322 // This can only happen when a type mismatch error happens and
1323 // the actual type has more type parameters than the expected one.
1324 None => format!("<generic #{}>", id),
1330 impl<'tcx> Repr<'tcx> for ParamTy {
1331 fn repr(&self, tcx: &ctxt) -> String {
1332 let ident = self.user_string(tcx);
1333 format!("{}/{}.{}", ident, self.space, self.idx)
1337 impl<'tcx, A:Repr<'tcx>, B:Repr<'tcx>> Repr<'tcx> for (A,B) {
1338 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1339 let &(ref a, ref b) = self;
1340 format!("({},{})", a.repr(tcx), b.repr(tcx))
1344 impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for ty::Binder<T> {
1345 fn repr(&self, tcx: &ctxt<'tcx>) -> String {
1346 format!("Binder({})", self.value.repr(tcx))