From dfbc9608ce5c9655a36b63f6cc9694f5e4ad9890 Mon Sep 17 00:00:00 2001 From: Eduard Burtescu Date: Thu, 18 Jun 2015 08:51:23 +0300 Subject: [PATCH] rustc: replace Repr/UserString impls with Debug/Display ones. --- src/librustc/metadata/tydecode.rs | 2 +- src/librustc/middle/implicator.rs | 34 +- src/librustc/middle/infer/error_reporting.rs | 2 +- .../middle/infer/higher_ranked/mod.rs | 4 +- src/librustc/middle/infer/mod.rs | 148 +- .../middle/infer/region_inference/mod.rs | 74 +- src/librustc/middle/intrinsicck.rs | 18 +- src/librustc/middle/mem_categorization.rs | 97 +- src/librustc/middle/subst.rs | 16 +- src/librustc/middle/traits/error_reporting.rs | 8 +- src/librustc/middle/traits/fulfill.rs | 13 +- src/librustc/middle/traits/mod.rs | 8 +- src/librustc/middle/traits/object_safety.rs | 14 +- src/librustc/middle/traits/project.rs | 49 +- src/librustc/middle/traits/select.rs | 37 +- src/librustc/middle/traits/util.rs | 138 +- src/librustc/middle/ty.rs | 512 +++--- src/librustc/middle/ty_fold.rs | 14 +- src/librustc/util/ppaux.rs | 1490 ++++++----------- src/librustc_borrowck/borrowck/mod.rs | 64 +- src/librustc_driver/test.rs | 11 +- src/librustc_trans/trans/_match.rs | 9 +- src/librustc_trans/trans/common.rs | 12 +- src/librustc_trans/trans/glue.rs | 13 - src/librustc_trans/trans/monomorphize.rs | 4 +- src/librustc_typeck/astconv.rs | 2 +- src/librustc_typeck/check/assoc.rs | 2 +- src/librustc_typeck/check/callee.rs | 14 +- src/librustc_typeck/check/compare_method.rs | 4 +- src/librustc_typeck/check/method/confirm.rs | 2 +- src/librustc_typeck/check/method/probe.rs | 62 +- src/librustc_typeck/check/mod.rs | 26 +- src/librustc_typeck/check/wf.rs | 2 +- src/librustc_typeck/collect.rs | 2 +- src/librustc_typeck/lib.rs | 6 +- src/librustdoc/clean/mod.rs | 2 +- .../compile-fail/object-lifetime-default.rs | 2 +- 37 files changed, 999 insertions(+), 1918 deletions(-) diff --git a/src/librustc/metadata/tydecode.rs b/src/librustc/metadata/tydecode.rs index ad650fcfb114..693ccc13f1e4 100644 --- a/src/librustc/metadata/tydecode.rs +++ b/src/librustc/metadata/tydecode.rs @@ -898,7 +898,7 @@ fn parse_builtin_bounds(st: &mut PState, mut _conv: F) -> ty::BuiltinBounds w fn parse_builtin_bounds_(st: &mut PState, _conv: &mut F) -> ty::BuiltinBounds where F: FnMut(DefIdSource, ast::DefId) -> ast::DefId, { - let mut builtin_bounds = ty::empty_builtin_bounds(); + let mut builtin_bounds = ty::BuiltinBounds::empty(); loop { match next(st) { diff --git a/src/librustc/middle/implicator.rs b/src/librustc/middle/implicator.rs index 599ecc6e7a97..abdaa9f38c0e 100644 --- a/src/librustc/middle/implicator.rs +++ b/src/librustc/middle/implicator.rs @@ -25,6 +25,7 @@ use util::ppaux::Repr; // Helper functions related to manipulating region types. +#[derive(Debug)] pub enum Implication<'tcx> { RegionSubRegion(Option>, ty::Region, ty::Region), RegionSubGeneric(Option>, ty::Region, GenericKind<'tcx>), @@ -400,7 +401,7 @@ impl<'a, 'tcx> Implicator<'a, 'tcx> { } fn fully_normalize(&self, value: &T) -> Result - where T : TypeFoldable<'tcx> + ty::HasProjectionTypes + Clone + Repr + where T : TypeFoldable<'tcx> + ty::HasProjectionTypes { let value = traits::fully_normalize(self.infcx, @@ -454,34 +455,3 @@ pub fn object_region_bounds<'tcx>( let predicates = ty::predicates(tcx, open_ty, ¶m_bounds); ty::required_region_bounds(tcx, open_ty, predicates) } - -impl<'tcx> Repr for Implication<'tcx> { - fn repr(&self) -> String { - match *self { - Implication::RegionSubRegion(_, ref r_a, ref r_b) => { - format!("RegionSubRegion({}, {})", - r_a.repr(), - r_b.repr()) - } - - Implication::RegionSubGeneric(_, ref r, ref p) => { - format!("RegionSubGeneric({}, {})", - r.repr(), - p.repr()) - } - - Implication::RegionSubClosure(_, ref a, ref b, ref c) => { - format!("RegionSubClosure({}, {}, {})", - a.repr(), - b.repr(), - c.repr()) - } - - Implication::Predicate(ref def_id, ref p) => { - format!("Predicate({}, {})", - def_id.repr(), - p.repr()) - } - } - } -} diff --git a/src/librustc/middle/infer/error_reporting.rs b/src/librustc/middle/infer/error_reporting.rs index fa324c57bcd0..9f3dd0a4b736 100644 --- a/src/librustc/middle/infer/error_reporting.rs +++ b/src/librustc/middle/infer/error_reporting.rs @@ -480,7 +480,7 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { "{}: {} ({})", trace.origin, expected_found_str, - ty::type_err_to_str(self.tcx, terr)); + terr); match trace.origin { infer::MatchExpressionArm(_, arm_span) => diff --git a/src/librustc/middle/infer/higher_ranked/mod.rs b/src/librustc/middle/infer/higher_ranked/mod.rs index d6001270d1c7..37f3a12b05f6 100644 --- a/src/librustc/middle/infer/higher_ranked/mod.rs +++ b/src/librustc/middle/infer/higher_ranked/mod.rs @@ -518,7 +518,7 @@ pub fn skolemize_late_bound_regions<'a,'tcx,T>(infcx: &InferCtxt<'a,'tcx>, binder: &ty::Binder, snapshot: &CombinedSnapshot) -> (T, SkolemizationMap) - where T : TypeFoldable<'tcx> + Repr + where T : TypeFoldable<'tcx> { /*! * Replace all regions bound by `binder` with skolemized regions and @@ -616,7 +616,7 @@ pub fn plug_leaks<'a,'tcx,T>(infcx: &InferCtxt<'a,'tcx>, snapshot: &CombinedSnapshot, value: &T) -> T - where T : TypeFoldable<'tcx> + Repr + where T : TypeFoldable<'tcx> { debug_assert!(leak_check(infcx, &skol_map, snapshot).is_ok()); diff --git a/src/librustc/middle/infer/mod.rs b/src/librustc/middle/infer/mod.rs index 02a73cfb7705..71febd981e04 100644 --- a/src/librustc/middle/infer/mod.rs +++ b/src/librustc/middle/infer/mod.rs @@ -160,7 +160,7 @@ pub enum ValuePairs<'tcx> { /// encounter an error or subtyping constraint. /// /// See `error_reporting.rs` for more details. -#[derive(Clone, Debug)] +#[derive(Clone)] pub struct TypeTrace<'tcx> { origin: TypeOrigin, values: ValuePairs<'tcx>, @@ -708,7 +708,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { value: &ty::Binder, snapshot: &CombinedSnapshot) -> (T, SkolemizationMap) - where T : TypeFoldable<'tcx> + Repr + where T : TypeFoldable<'tcx> { /*! See `higher_ranked::skolemize_late_bound_regions` */ @@ -733,7 +733,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { snapshot: &CombinedSnapshot, value: &T) -> T - where T : TypeFoldable<'tcx> + Repr + where T : TypeFoldable<'tcx> { /*! See `higher_ranked::plug_leaks` */ @@ -979,7 +979,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { Some(t) if ty::type_is_error(t) => (), _ => { let error_str = err.map_or("".to_string(), |t_err| { - format!(" ({})", ty::type_err_to_str(self.tcx, t_err)) + format!(" ({})", t_err) }); self.tcx.sess.span_err(sp, &format!("{}{}", @@ -1033,7 +1033,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { lbrct: LateBoundRegionConversionTime, value: &ty::Binder) -> (T, FnvHashMap) - where T : TypeFoldable<'tcx> + Repr + where T : TypeFoldable<'tcx> { ty_fold::replace_late_bound_regions( self.tcx, @@ -1099,9 +1099,9 @@ impl<'tcx> TypeTrace<'tcx> { } } -impl<'tcx> Repr for TypeTrace<'tcx> { - fn repr(&self) -> String { - format!("TypeTrace({})", self.origin.repr()) +impl<'tcx> fmt::Debug for TypeTrace<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "TypeTrace({:?})", self.origin) } } @@ -1123,44 +1123,6 @@ impl TypeOrigin { } } -impl<'tcx> Repr for TypeOrigin { - fn repr(&self) -> String { - match *self { - MethodCompatCheck(a) => { - format!("MethodCompatCheck({})", a.repr()) - } - ExprAssignable(a) => { - format!("ExprAssignable({})", a.repr()) - } - Misc(a) => format!("Misc({})", a.repr()), - RelateTraitRefs(a) => { - format!("RelateTraitRefs({})", a.repr()) - } - RelateSelfType(a) => { - format!("RelateSelfType({})", a.repr()) - } - RelateOutputImplTypes(a) => { - format!("RelateOutputImplTypes({})", a.repr()) - } - MatchExpressionArm(a, b) => { - format!("MatchExpressionArm({}, {})", a.repr(), b.repr()) - } - IfExpression(a) => { - format!("IfExpression({})", a.repr()) - } - IfExpressionWithNoElse(a) => { - format!("IfExpressionWithNoElse({})", a.repr()) - } - RangeExpression(a) => { - format!("RangeExpression({})", a.repr()) - } - EquatePredicate(a) => { - format!("EquatePredicate({})", a.repr()) - } - } - } -} - impl<'tcx> SubregionOrigin<'tcx> { pub fn span(&self) -> Span { match *self { @@ -1190,70 +1152,6 @@ impl<'tcx> SubregionOrigin<'tcx> { } } -impl<'tcx> Repr for SubregionOrigin<'tcx> { - fn repr(&self) -> String { - match *self { - Subtype(ref a) => { - format!("Subtype({})", a.repr()) - } - InfStackClosure(a) => { - format!("InfStackClosure({})", a.repr()) - } - InvokeClosure(a) => { - format!("InvokeClosure({})", a.repr()) - } - DerefPointer(a) => { - format!("DerefPointer({})", a.repr()) - } - FreeVariable(a, b) => { - format!("FreeVariable({}, {})", a.repr(), b) - } - IndexSlice(a) => { - format!("IndexSlice({})", a.repr()) - } - RelateObjectBound(a) => { - format!("RelateObjectBound({})", a.repr()) - } - RelateParamBound(a, b) => { - format!("RelateParamBound({},{})", - a.repr(), - b.repr()) - } - RelateRegionParamBound(a) => { - format!("RelateRegionParamBound({})", - a.repr()) - } - RelateDefaultParamBound(a, b) => { - format!("RelateDefaultParamBound({},{})", - a.repr(), - b.repr()) - } - Reborrow(a) => format!("Reborrow({})", a.repr()), - ReborrowUpvar(a, b) => { - format!("ReborrowUpvar({},{:?})", a.repr(), b) - } - ReferenceOutlivesReferent(_, a) => { - format!("ReferenceOutlivesReferent({})", a.repr()) - } - ExprTypeIsNotInScope(a, b) => { - format!("ExprTypeIsNotInScope({}, {})", - a.repr(), - b.repr()) - } - BindingTypeIsNotValidAtDecl(a) => { - format!("BindingTypeIsNotValidAtDecl({})", a.repr()) - } - CallRcvr(a) => format!("CallRcvr({})", a.repr()), - CallArg(a) => format!("CallArg({})", a.repr()), - CallReturn(a) => format!("CallReturn({})", a.repr()), - Operand(a) => format!("Operand({})", a.repr()), - AddrOf(a) => format!("AddrOf({})", a.repr()), - AutoBorrow(a) => format!("AutoBorrow({})", a.repr()), - SafeDestructor(a) => format!("SafeDestructor({})", a.repr()), - } - } -} - impl RegionVariableOrigin { pub fn span(&self) -> Span { match *self { @@ -1269,33 +1167,3 @@ impl RegionVariableOrigin { } } } - -impl<'tcx> Repr for RegionVariableOrigin { - fn repr(&self) -> String { - match *self { - MiscVariable(a) => { - format!("MiscVariable({})", a.repr()) - } - PatternRegion(a) => { - format!("PatternRegion({})", a.repr()) - } - AddrOfRegion(a) => { - format!("AddrOfRegion({})", a.repr()) - } - Autoref(a) => format!("Autoref({})", a.repr()), - Coercion(a) => format!("Coercion({})", a.repr()), - EarlyBoundRegion(a, b) => { - format!("EarlyBoundRegion({},{})", a.repr(), b.repr()) - } - LateBoundRegion(a, b, c) => { - format!("LateBoundRegion({},{},{:?})", a.repr(), b.repr(), c) - } - BoundRegionInCoherence(a) => { - format!("bound_regionInCoherence({})", a.repr()) - } - UpvarRegion(a, b) => { - format!("UpvarRegion({}, {})", a.repr(), b.repr()) - } - } - } -} diff --git a/src/librustc/middle/infer/region_inference/mod.rs b/src/librustc/middle/infer/region_inference/mod.rs index 066083d27c73..024889d08290 100644 --- a/src/librustc/middle/infer/region_inference/mod.rs +++ b/src/librustc/middle/infer/region_inference/mod.rs @@ -30,10 +30,11 @@ use middle::ty::{ReLateBound, ReScope, ReVar, ReSkolemized, BrFresh}; use middle::ty_relate::RelateResult; use util::common::indenter; use util::nodemap::{FnvHashMap, FnvHashSet}; -use util::ppaux::{Repr, UserString}; +use util::ppaux::Repr; use std::cell::{Cell, RefCell}; use std::cmp::Ordering::{self, Less, Greater, Equal}; +use std::fmt; use std::iter::repeat; use std::u32; use syntax::ast; @@ -68,7 +69,7 @@ pub enum Verify<'tcx> { VerifyGenericBound(GenericKind<'tcx>, SubregionOrigin<'tcx>, Region, Vec), } -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] pub enum GenericKind<'tcx> { Param(ty::ParamTy), Projection(ty::ProjectionTy<'tcx>), @@ -959,7 +960,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { #[derive(Copy, Clone, PartialEq, Debug)] enum Classification { Expanding, Contracting } -#[derive(Copy, Clone)] +#[derive(Copy, Clone, Debug)] pub enum VarValue { NoValue, Value(Region), ErrorValue } struct VarData { @@ -1589,31 +1590,14 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { } -impl Repr for Constraint { - fn repr(&self) -> String { - match *self { - ConstrainVarSubVar(a, b) => { - format!("ConstrainVarSubVar({}, {})", a.repr(), b.repr()) - } - ConstrainRegSubVar(a, b) => { - format!("ConstrainRegSubVar({}, {})", a.repr(), b.repr()) - } - ConstrainVarSubReg(a, b) => { - format!("ConstrainVarSubReg({}, {})", a.repr(), b.repr()) - } - } - } -} - -impl<'tcx> Repr for Verify<'tcx> { - fn repr(&self) -> String { +impl<'tcx> fmt::Debug for Verify<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { VerifyRegSubReg(_, ref a, ref b) => { - format!("VerifyRegSubReg({}, {})", a.repr(), b.repr()) + write!(f, "VerifyRegSubReg({:?}, {:?})", a, b) } VerifyGenericBound(_, ref p, ref a, ref bs) => { - format!("VerifyGenericBound({}, {}, {})", - p.repr(), a.repr(), bs.repr()) + write!(f, "VerifyGenericBound({:?}, {:?}, {:?})", p, a, bs) } } } @@ -1634,38 +1618,28 @@ fn lookup(values: &Vec, rid: ty::RegionVid) -> ty::Region { } } -impl Repr for VarValue { - fn repr(&self) -> String { +impl<'tcx> fmt::Debug for RegionAndOrigin<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "RegionAndOrigin({},{})", + self.region.repr(), + self.origin.repr()) + } +} + +impl<'tcx> fmt::Debug for GenericKind<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - NoValue => format!("NoValue"), - Value(r) => format!("Value({})", r.repr()), - ErrorValue => format!("ErrorValue"), + GenericKind::Param(ref p) => write!(f, "{:?}", p), + GenericKind::Projection(ref p) => write!(f, "{:?}", p), } } } -impl<'tcx> Repr for RegionAndOrigin<'tcx> { - fn repr(&self) -> String { - format!("RegionAndOrigin({},{})", - self.region.repr(), - self.origin.repr()) - } -} - -impl<'tcx> Repr for GenericKind<'tcx> { - fn repr(&self) -> String { +impl<'tcx> fmt::Display for GenericKind<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - GenericKind::Param(ref p) => p.repr(), - GenericKind::Projection(ref p) => p.repr(), - } - } -} - -impl<'tcx> UserString for GenericKind<'tcx> { - fn user_string(&self) -> String { - match *self { - GenericKind::Param(ref p) => p.user_string(), - GenericKind::Projection(ref p) => p.user_string(), + GenericKind::Param(ref p) => write!(f, "{}", p), + GenericKind::Projection(ref p) => write!(f, "{}", p), } } } diff --git a/src/librustc/middle/intrinsicck.rs b/src/librustc/middle/intrinsicck.rs index a3ea726f0f2f..6ff774b4bb01 100644 --- a/src/librustc/middle/intrinsicck.rs +++ b/src/librustc/middle/intrinsicck.rs @@ -16,6 +16,8 @@ use middle::ty::{TransmuteRestriction, ctxt, TyBareFn}; use middle::ty::{self, Ty}; use util::ppaux::Repr; +use std::fmt; + use syntax::abi::RustIntrinsic; use syntax::ast::DefId; use syntax::ast; @@ -277,13 +279,13 @@ impl<'a, 'tcx, 'v> Visitor<'v> for IntrinsicCheckingVisitor<'a, 'tcx> { } } -impl<'tcx> Repr for TransmuteRestriction<'tcx> { - fn repr(&self) -> String { - format!("TransmuteRestriction(id={}, original=({},{}), substituted=({},{}))", - self.id, - self.original_from.repr(), - self.original_to.repr(), - self.substituted_from.repr(), - self.substituted_to.repr()) +impl<'tcx> fmt::Debug for TransmuteRestriction<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "TransmuteRestriction(id={}, original=({:?},{:?}), substituted=({:?},{:?}))", + self.id, + self.original_from, + self.original_to, + self.substituted_from, + self.substituted_to) } } diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index 3dbb3dfae2f0..935c077b6338 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -84,12 +84,12 @@ use syntax::ast::{MutImmutable, MutMutable}; use syntax::ast; use syntax::codemap::Span; use syntax::print::pprust; -use syntax::parse::token; use std::cell::RefCell; +use std::fmt; use std::rc::Rc; -#[derive(Clone, PartialEq, Debug)] +#[derive(Clone, PartialEq)] pub enum categorization<'tcx> { cat_rvalue(ty::Region), // temporary val, argument is its scope cat_static_item, @@ -103,14 +103,14 @@ pub enum categorization<'tcx> { } // Represents any kind of upvar -#[derive(Clone, Copy, PartialEq, Debug)] +#[derive(Clone, Copy, PartialEq)] pub struct Upvar { pub id: ty::UpvarId, pub kind: ty::ClosureKind } // different kinds of pointers: -#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Copy, PartialEq, Eq, Hash)] pub enum PointerKind { /// `Box` Unique, @@ -127,7 +127,7 @@ pub enum PointerKind { // We use the term "interior" to mean "something reachable from the // base without a pointer dereference", e.g. a field -#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Copy, PartialEq, Eq, Hash)] pub enum InteriorKind { InteriorField(FieldName), InteriorElement(InteriorOffsetKind, ElementKind), @@ -184,7 +184,7 @@ pub enum Note { // dereference, but its type is the type *before* the dereference // (`@T`). So use `cmt.ty` to find the type of the value in a consistent // fashion. For more details, see the method `cat_pattern` -#[derive(Clone, PartialEq, Debug)] +#[derive(Clone, PartialEq)] pub struct cmt_<'tcx> { pub id: ast::NodeId, // id of expr/pat producing this value pub span: Span, // span of same expr/pat @@ -1569,33 +1569,36 @@ impl<'tcx> cmt_<'tcx> { } } -impl<'tcx> Repr for cmt_<'tcx> { - fn repr(&self) -> String { - format!("{{{} id:{} m:{:?} ty:{}}}", - self.cat.repr(), - self.id, - self.mutbl, - self.ty.repr()) +impl<'tcx> fmt::Debug for cmt_<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{{{:?} id:{} m:{:?} ty:{:?}}}", + self.cat, + self.id, + self.mutbl, + self.ty) } } -impl<'tcx> Repr for categorization<'tcx> { - fn repr(&self) -> String { +impl<'tcx> fmt::Debug for categorization<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - cat_static_item | - cat_rvalue(..) | - cat_local(..) | - cat_upvar(..) => { - format!("{:?}", *self) + cat_static_item => write!(f, "static"), + cat_rvalue(r) => write!(f, "rvalue({:?})", r), + cat_local(id) => { + let name = ty::tls::with(|tcx| ty::local_var_name_str(tcx, id)); + write!(f, "local({})", name) + } + cat_upvar(upvar) => { + write!(f, "upvar({:?})", upvar) } cat_deref(ref cmt, derefs, ptr) => { - format!("{}-{}{}->", cmt.cat.repr(), ptr.repr(), derefs) + write!(f, "{:?}-{:?}{}->", cmt.cat, ptr, derefs) } cat_interior(ref cmt, interior) => { - format!("{}.{}", cmt.cat.repr(), interior.repr()) + write!(f, "{:?}.{:?}", cmt.cat, interior) } cat_downcast(ref cmt, _) => { - format!("{}->(enum)", cmt.cat.repr()) + write!(f, "{:?}->(enum)", cmt.cat) } } } @@ -1614,39 +1617,33 @@ pub fn ptr_sigil(ptr: PointerKind) -> &'static str { } } -impl Repr for PointerKind { - fn repr(&self) -> String { +impl fmt::Debug for PointerKind { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - Unique => { - format!("Box") - } + Unique => write!(f, "Box"), BorrowedPtr(ty::ImmBorrow, ref r) | Implicit(ty::ImmBorrow, ref r) => { - format!("&{}", r.repr()) + write!(f, "&{:?}", r) } BorrowedPtr(ty::MutBorrow, ref r) | Implicit(ty::MutBorrow, ref r) => { - format!("&{} mut", r.repr()) + write!(f, "&{:?} mut", r) } BorrowedPtr(ty::UniqueImmBorrow, ref r) | Implicit(ty::UniqueImmBorrow, ref r) => { - format!("&{} uniq", r.repr()) - } - UnsafePtr(_) => { - format!("*") + write!(f, "&{:?} uniq", r) } + UnsafePtr(_) => write!(f, "*") } } } -impl Repr for InteriorKind { - fn repr(&self) -> String { +impl fmt::Debug for InteriorKind { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - InteriorField(NamedField(fld)) => { - token::get_name(fld).to_string() - } - InteriorField(PositionalField(i)) => format!("#{}", i), - InteriorElement(..) => "[]".to_string(), + InteriorField(NamedField(fld)) => write!(f, "{}", fld), + InteriorField(PositionalField(i)) => write!(f, "#{}", i), + InteriorElement(..) => write!(f, "[]"), } } } @@ -1663,25 +1660,19 @@ fn element_kind(t: Ty) -> ElementKind { } } -impl Repr for ty::ClosureKind { - fn repr(&self) -> String { - format!("Upvar({:?})", self) +impl fmt::Debug for Upvar { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{:?}/{:?}", self.id, self.kind) } } -impl Repr for Upvar { - fn repr(&self) -> String { - format!("Upvar({})", self.kind.repr()) - } -} - -impl UserString for Upvar { - fn user_string(&self) -> String { +impl fmt::Display for Upvar { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let kind = match self.kind { ty::FnClosureKind => "Fn", ty::FnMutClosureKind => "FnMut", ty::FnOnceClosureKind => "FnOnce", }; - format!("captured outer variable in an `{}` closure", kind) + write!(f, "captured outer variable in an `{}` closure", kind) } } diff --git a/src/librustc/middle/subst.rs b/src/librustc/middle/subst.rs index 8f6e85a17b12..957bd76bb942 100644 --- a/src/librustc/middle/subst.rs +++ b/src/librustc/middle/subst.rs @@ -29,7 +29,7 @@ use syntax::codemap::{Span, DUMMY_SP}; /// identify each in-scope parameter by an *index* and a *parameter /// space* (which indices where the parameter is defined; see /// `ParamSpace`). -#[derive(Clone, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, PartialEq, Eq, Hash)] pub struct Substs<'tcx> { pub types: VecPerParamSpace>, pub regions: RegionSubsts, @@ -38,7 +38,7 @@ pub struct Substs<'tcx> { /// Represents the values to use when substituting lifetime parameters. /// If the value is `ErasedRegions`, then this subst is occurring during /// trans, and all region parameters will be replaced with `ty::ReStatic`. -#[derive(Clone, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, PartialEq, Eq, Hash)] pub enum RegionSubsts { ErasedRegions, NonerasedRegions(VecPerParamSpace) @@ -240,13 +240,11 @@ pub struct SeparateVecsPerParamSpace { } impl fmt::Debug for VecPerParamSpace { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - try!(write!(fmt, "VecPerParamSpace {{")); - for space in &ParamSpace::all() { - try!(write!(fmt, "{:?}: {:?}, ", *space, self.get_slice(*space))); - } - try!(write!(fmt, "}}")); - Ok(()) + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "[{:?};{:?};{:?}]", + self.get_slice(TypeSpace), + self.get_slice(SelfSpace), + self.get_slice(FnSpace)) } } diff --git a/src/librustc/middle/traits/error_reporting.rs b/src/librustc/middle/traits/error_reporting.rs index 72f162638929..7d4bbb5d7f03 100644 --- a/src/librustc/middle/traits/error_reporting.rs +++ b/src/librustc/middle/traits/error_reporting.rs @@ -69,7 +69,7 @@ pub fn report_projection_error<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>, span_err!(infcx.tcx.sess, obligation.cause.span, E0271, "type mismatch resolving `{}`: {}", predicate.user_string(), - ty::type_err_to_str(infcx.tcx, &error.err)); + error.err); note_obligation_cause(infcx, obligation); } } @@ -217,7 +217,7 @@ pub fn report_selection_error<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>, span_err!(infcx.tcx.sess, obligation.cause.span, E0278, "the requirement `{}` is not satisfied (`{}`)", predicate.user_string(), - ty::type_err_to_str(infcx.tcx, &err)); + err); } ty::Predicate::RegionOutlives(ref predicate) => { @@ -227,7 +227,7 @@ pub fn report_selection_error<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>, span_err!(infcx.tcx.sess, obligation.cause.span, E0279, "the requirement `{}` is not satisfied (`{}`)", predicate.user_string(), - ty::type_err_to_str(infcx.tcx, &err)); + err); } ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => { @@ -252,7 +252,7 @@ pub fn report_selection_error<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>, expected_trait_ref.self_ty().user_string(), expected_trait_ref.user_string(), actual_trait_ref.user_string(), - ty::type_err_to_str(infcx.tcx, e)); + e); note_obligation_cause(infcx, obligation); } } diff --git a/src/librustc/middle/traits/fulfill.rs b/src/librustc/middle/traits/fulfill.rs index 418c4522cd9b..0828a67c6c67 100644 --- a/src/librustc/middle/traits/fulfill.rs +++ b/src/librustc/middle/traits/fulfill.rs @@ -10,8 +10,9 @@ use middle::infer::InferCtxt; use middle::ty::{self, RegionEscape, Ty}; + use std::collections::HashSet; -use std::default::Default; +use std::fmt; use syntax::ast; use util::common::ErrorReported; use util::ppaux::Repr; @@ -461,11 +462,11 @@ fn process_predicate<'a,'tcx>(selcx: &mut SelectionContext<'a,'tcx>, } } -impl<'tcx> Repr for RegionObligation<'tcx> { - fn repr(&self) -> String { - format!("RegionObligation(sub_region={}, sup_type={})", - self.sub_region.repr(), - self.sup_type.repr()) +impl<'tcx> fmt::Debug for RegionObligation<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "RegionObligation(sub_region={:?}, sup_type={:?})", + self.sub_region, + self.sup_type) } } diff --git a/src/librustc/middle/traits/mod.rs b/src/librustc/middle/traits/mod.rs index 551bafc57161..35855767e609 100644 --- a/src/librustc/middle/traits/mod.rs +++ b/src/librustc/middle/traits/mod.rs @@ -219,7 +219,7 @@ pub type SelectionResult<'tcx, T> = Result, SelectionError<'tcx>>; /// ### The type parameter `N` /// /// See explanation on `VtableImplData`. -#[derive(Debug,Clone)] +#[derive(Clone)] pub enum Vtable<'tcx, N> { /// Vtable identifying a particular impl. VtableImpl(VtableImplData<'tcx, N>), @@ -277,13 +277,13 @@ pub struct VtableClosureData<'tcx, N> { pub nested: Vec } -#[derive(Debug, Clone)] +#[derive(Clone)] pub struct VtableDefaultImplData { pub trait_def_id: ast::DefId, pub nested: Vec } -#[derive(Debug,Clone)] +#[derive(Clone)] pub struct VtableBuiltinData { pub nested: Vec } @@ -433,7 +433,7 @@ pub fn fully_normalize<'a,'tcx,T>(infcx: &InferCtxt<'a,'tcx>, cause: ObligationCause<'tcx>, value: &T) -> Result>> - where T : TypeFoldable<'tcx> + HasProjectionTypes + Clone + Repr + where T : TypeFoldable<'tcx> + HasProjectionTypes { debug!("normalize_param_env(value={})", value.repr()); diff --git a/src/librustc/middle/traits/object_safety.rs b/src/librustc/middle/traits/object_safety.rs index 9be973c70189..daa03c5160c0 100644 --- a/src/librustc/middle/traits/object_safety.rs +++ b/src/librustc/middle/traits/object_safety.rs @@ -27,6 +27,7 @@ use std::rc::Rc; use syntax::ast; use util::ppaux::Repr; +#[derive(Debug)] pub enum ObjectSafetyViolation<'tcx> { /// Self : Sized declared on the trait SizedSelf, @@ -352,19 +353,6 @@ fn contains_illegal_self_type_reference<'tcx>(tcx: &ty::ctxt<'tcx>, error } -impl<'tcx> Repr for ObjectSafetyViolation<'tcx> { - fn repr(&self) -> String { - match *self { - ObjectSafetyViolation::SizedSelf => - format!("SizedSelf"), - ObjectSafetyViolation::SupertraitSelf => - format!("SupertraitSelf"), - ObjectSafetyViolation::Method(ref m, code) => - format!("Method({},{:?})", m.repr(), code), - } - } -} - fn is_self<'tcx>(ty: Ty<'tcx>) -> bool { match ty.sty { ty::TyParam(ref data) => data.space == subst::SelfSpace, diff --git a/src/librustc/middle/traits/project.rs b/src/librustc/middle/traits/project.rs index 1b5f79452c0f..967edabc0b9c 100644 --- a/src/librustc/middle/traits/project.rs +++ b/src/librustc/middle/traits/project.rs @@ -30,6 +30,8 @@ use syntax::parse::token; use util::common::FN_OUTPUT_NAME; use util::ppaux::Repr; +use std::fmt; + pub type PolyProjectionObligation<'tcx> = Obligation<'tcx, ty::PolyProjectionPredicate<'tcx>>; @@ -40,6 +42,7 @@ pub type ProjectionTyObligation<'tcx> = Obligation<'tcx, ty::ProjectionTy<'tcx>>; /// When attempting to resolve `::Name` ... +#[derive(Debug)] pub enum ProjectionTyError<'tcx> { /// ...we found multiple sources of information and couldn't resolve the ambiguity. TooManyCandidates, @@ -53,7 +56,7 @@ pub struct MismatchedProjectionTypes<'tcx> { pub err: ty::type_err<'tcx> } -#[derive(PartialEq, Eq)] +#[derive(PartialEq, Eq, Debug)] enum ProjectionTyCandidate<'tcx> { ParamEnv(ty::PolyProjectionPredicate<'tcx>), Impl(VtableImplData<'tcx, PredicateObligation<'tcx>>), @@ -193,7 +196,7 @@ pub fn normalize<'a,'b,'tcx,T>(selcx: &'a mut SelectionContext<'b,'tcx>, cause: ObligationCause<'tcx>, value: &T) -> Normalized<'tcx, T> - where T : TypeFoldable<'tcx> + HasProjectionTypes + Clone + Repr + where T : TypeFoldable<'tcx> + HasProjectionTypes { normalize_with_depth(selcx, cause, 0, value) } @@ -204,7 +207,7 @@ pub fn normalize_with_depth<'a,'b,'tcx,T>(selcx: &'a mut SelectionContext<'b,'tc depth: usize, value: &T) -> Normalized<'tcx, T> - where T : TypeFoldable<'tcx> + HasProjectionTypes + Clone + Repr + where T : TypeFoldable<'tcx> + HasProjectionTypes { let mut normalizer = AssociatedTypeNormalizer::new(selcx, cause, depth); let result = normalizer.fold(value); @@ -236,7 +239,7 @@ impl<'a,'b,'tcx> AssociatedTypeNormalizer<'a,'b,'tcx> { } } - fn fold + HasProjectionTypes + Clone>(&mut self, value: &T) -> T { + fn fold + HasProjectionTypes>(&mut self, value: &T) -> T { let value = self.selcx.infcx().resolve_type_vars_if_possible(value); if !value.has_projection_types() { @@ -864,7 +867,7 @@ fn confirm_param_env_candidate<'cx,'tcx>( &format!("Failed to unify `{}` and `{}` in projection: {}", obligation.repr(), projection.repr(), - ty::type_err_to_str(selcx.tcx(), &e))); + e)); } } @@ -915,32 +918,6 @@ fn confirm_impl_candidate<'cx,'tcx>( trait_ref.repr())); } -impl<'tcx> Repr for ProjectionTyError<'tcx> { - fn repr(&self) -> String { - match *self { - ProjectionTyError::TooManyCandidates => - format!("NoCandidate"), - ProjectionTyError::TraitSelectionError(ref e) => - format!("TraitSelectionError({})", e.repr()), - } - } -} - -impl<'tcx> Repr for ProjectionTyCandidate<'tcx> { - fn repr(&self) -> String { - match *self { - ProjectionTyCandidate::ParamEnv(ref data) => - format!("ParamEnv({})", data.repr()), - ProjectionTyCandidate::Impl(ref data) => - format!("Impl({})", data.repr()), - ProjectionTyCandidate::Closure(ref data) => - format!("Closure({})", data.repr()), - ProjectionTyCandidate::FnPointer(a) => - format!("FnPointer(({}))", a.repr()), - } - } -} - impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Normalized<'tcx, T> { fn fold_with>(&self, folder: &mut F) -> Normalized<'tcx, T> { Normalized { @@ -950,10 +927,10 @@ impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Normalized<'tcx, T> { } } -impl<'tcx, T:Repr> Repr for Normalized<'tcx, T> { - fn repr(&self) -> String { - format!("Normalized({},{})", - self.value.repr(), - self.obligations.repr()) +impl<'tcx, T:fmt::Debug> fmt::Debug for Normalized<'tcx, T> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Normalized({:?},{:?})", + self.value, + self.obligations) } } diff --git a/src/librustc/middle/traits/select.rs b/src/librustc/middle/traits/select.rs index 5519ad97d222..96d48faf9e09 100644 --- a/src/librustc/middle/traits/select.rs +++ b/src/librustc/middle/traits/select.rs @@ -44,7 +44,9 @@ use middle::infer::{InferCtxt, TypeFreshener}; use middle::ty_fold::TypeFoldable; use middle::ty_match; use middle::ty_relate::TypeRelation; + use std::cell::RefCell; +use std::fmt; use std::rc::Rc; use syntax::{abi, ast}; use util::common::ErrorReported; @@ -2666,14 +2668,12 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { origin, impl_trait_ref.value.clone(), skol_obligation_trait_ref) { - debug!("match_impl: failed sub_trait_refs due to `{}`", - ty::type_err_to_str(self.tcx(), &e)); + debug!("match_impl: failed sub_trait_refs due to `{}`", e); return Err(()); } if let Err(e) = self.infcx.leak_check(&skol_map, snapshot) { - debug!("match_impl: failed leak check due to `{}`", - ty::type_err_to_str(self.tcx(), &e)); + debug!("match_impl: failed leak check due to `{}`", e); return Err(()); } @@ -2962,28 +2962,6 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } } -impl<'tcx> Repr for SelectionCandidate<'tcx> { - fn repr(&self) -> String { - match *self { - PhantomFnCandidate => format!("PhantomFnCandidate"), - ErrorCandidate => format!("ErrorCandidate"), - BuiltinCandidate(b) => format!("BuiltinCandidate({:?})", b), - BuiltinObjectCandidate => format!("BuiltinObjectCandidate"), - BuiltinUnsizeCandidate => format!("BuiltinUnsizeCandidate"), - ParamCandidate(ref a) => format!("ParamCandidate({})", a.repr()), - ImplCandidate(a) => format!("ImplCandidate({})", a.repr()), - DefaultImplCandidate(t) => format!("DefaultImplCandidate({:?})", t), - DefaultImplObjectCandidate(t) => format!("DefaultImplObjectCandidate({:?})", t), - ProjectionCandidate => format!("ProjectionCandidate"), - FnPointerCandidate => format!("FnPointerCandidate"), - ObjectCandidate => format!("ObjectCandidate"), - ClosureCandidate(c, ref s) => { - format!("ClosureCandidate({:?},{})", c, s.repr()) - } - } - } -} - impl<'tcx> SelectionCache<'tcx> { pub fn new() -> SelectionCache<'tcx> { SelectionCache { @@ -3031,10 +3009,9 @@ impl<'o,'tcx> Iterator for TraitObligationStackList<'o,'tcx>{ } } -impl<'o,'tcx> Repr for TraitObligationStack<'o,'tcx> { - fn repr(&self) -> String { - format!("TraitObligationStack({})", - self.obligation.repr()) +impl<'o,'tcx> fmt::Debug for TraitObligationStack<'o,'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "TraitObligationStack({:?})", self.obligation) } } diff --git a/src/librustc/middle/traits/util.rs b/src/librustc/middle/traits/util.rs index 475e2f69a4c1..2c6feb66fa8c 100644 --- a/src/librustc/middle/traits/util.rs +++ b/src/librustc/middle/traits/util.rs @@ -302,24 +302,12 @@ pub fn fresh_type_vars_for_impl<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>, infcx.fresh_substs_for_generics(span, &impl_generics) } -impl<'tcx, N> fmt::Debug for VtableImplData<'tcx, N> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "VtableImpl({:?})", self.impl_def_id) - } -} - impl<'tcx, N> fmt::Debug for super::VtableClosureData<'tcx, N> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "VtableClosure({:?})", self.closure_def_id) } } -impl<'tcx> fmt::Debug for super::VtableObjectData<'tcx> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "VtableObject(...)") - } -} - /// See `super::obligations_for_generics` pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>, recursion_depth: usize, @@ -485,118 +473,84 @@ pub fn closure_trait_ref_and_return_type<'tcx>( ty::Binder((trait_ref, sig.0.output.unwrap_or(ty::mk_nil(tcx)))) } -impl<'tcx,O:Repr> Repr for super::Obligation<'tcx, O> { - fn repr(&self) -> String { - format!("Obligation(predicate={},depth={})", - self.predicate.repr(), - self.recursion_depth) +impl<'tcx,O:fmt::Debug> fmt::Debug for super::Obligation<'tcx, O> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Obligation(predicate={:?},depth={})", + self.predicate, + self.recursion_depth) } } -impl<'tcx, N:Repr> Repr for super::Vtable<'tcx, N> { - fn repr(&self) -> String { +impl<'tcx, N:fmt::Debug> fmt::Debug for super::Vtable<'tcx, N> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { super::VtableImpl(ref v) => - v.repr(), + write!(f, "{:?}", v), super::VtableDefaultImpl(ref t) => - t.repr(), + write!(f, "{:?}", t), super::VtableClosure(ref d) => - d.repr(), + write!(f, "{:?}", d), super::VtableFnPointer(ref d) => - format!("VtableFnPointer({})", - d.repr()), + write!(f, "VtableFnPointer({:?})", d), super::VtableObject(ref d) => - format!("VtableObject({})", - d.repr()), + write!(f, "VtableObject({:?})", d), super::VtableParam(ref n) => - format!("VtableParam({})", - n.repr()), + write!(f, "VtableParam({:?})", n), super::VtableBuiltin(ref d) => - d.repr() + write!(f, "{:?}", d) } } } -impl<'tcx, N:Repr> Repr for super::VtableImplData<'tcx, N> { - fn repr(&self) -> String { - format!("VtableImpl(impl_def_id={}, substs={}, nested={})", - self.impl_def_id.repr(), - self.substs.repr(), - self.nested.repr()) +impl<'tcx, N:fmt::Debug> fmt::Debug for super::VtableImplData<'tcx, N> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "VtableImpl(impl_def_id={:?}, substs={:?}, nested={:?})", + self.impl_def_id, + self.substs, + self.nested) } } -impl<'tcx, N:Repr> Repr for super::VtableClosureData<'tcx, N> { - fn repr(&self) -> String { - format!("VtableClosure(closure_def_id={}, substs={}, nested={})", - self.closure_def_id.repr(), - self.substs.repr(), - self.nested.repr()) +impl<'tcx, N:fmt::Debug> fmt::Debug for super::VtableClosureData<'tcx, N> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "VtableClosure(closure_def_id={:?}, substs={:?}, nested={:?})", + self.closure_def_id, + self.substs, + self.nested) } } -impl<'tcx, N:Repr> Repr for super::VtableBuiltinData { - fn repr(&self) -> String { - format!("VtableBuiltin(nested={})", - self.nested.repr()) +impl<'tcx, N:fmt::Debug> fmt::Debug for super::VtableBuiltinData { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "VtableBuiltin(nested={:?})", self.nested) } } -impl<'tcx, N:Repr> Repr for super::VtableDefaultImplData { - fn repr(&self) -> String { - format!("VtableDefaultImplData(trait_def_id={}, nested={})", - self.trait_def_id.repr(), - self.nested.repr()) +impl<'tcx, N:fmt::Debug> fmt::Debug for super::VtableDefaultImplData { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "VtableDefaultImplData(trait_def_id={:?}, nested={:?})", + self.trait_def_id, + self.nested) } } -impl<'tcx> Repr for super::VtableObjectData<'tcx> { - fn repr(&self) -> String { - format!("VtableObject(object_ty={})", - self.object_ty.repr()) +impl<'tcx> fmt::Debug for super::VtableObjectData<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "VtableObject(object_ty={:?})", self.object_ty) } } -impl<'tcx> Repr for super::SelectionError<'tcx> { - fn repr(&self) -> String { - match *self { - super::Unimplemented => - format!("Unimplemented"), - - super::OutputTypeParameterMismatch(ref a, ref b, ref c) => - format!("OutputTypeParameterMismatch({},{},{})", - a.repr(), - b.repr(), - c.repr()), - - super::TraitNotObjectSafe(ref tr) => - format!("TraitNotObjectSafe({})", - tr.repr()) - } - } -} - -impl<'tcx> Repr for super::FulfillmentError<'tcx> { - fn repr(&self) -> String { - format!("FulfillmentError({},{})", - self.obligation.repr(), - self.code.repr()) - } -} - -impl<'tcx> Repr for super::FulfillmentErrorCode<'tcx> { - fn repr(&self) -> String { - match *self { - super::CodeSelectionError(ref o) => o.repr(), - super::CodeProjectionError(ref o) => o.repr(), - super::CodeAmbiguity => format!("Ambiguity") - } +impl<'tcx> fmt::Debug for super::FulfillmentError<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "FulfillmentError({:?},{:?})", + self.obligation, + self.code) } } @@ -610,14 +564,8 @@ impl<'tcx> fmt::Debug for super::FulfillmentErrorCode<'tcx> { } } -impl<'tcx> Repr for super::MismatchedProjectionTypes<'tcx> { - fn repr(&self) -> String { - self.err.repr() - } -} - impl<'tcx> fmt::Debug for super::MismatchedProjectionTypes<'tcx> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "MismatchedProjectionTypes(..)") + write!(f, "MismatchedProjectionTypes({:?})", self.err) } } diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 293043af5397..1274b3498fd3 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -12,7 +12,6 @@ pub use self::terr_vstore_kind::*; pub use self::type_err::*; -pub use self::BuiltinBound::*; pub use self::InferTy::*; pub use self::InferRegion::*; pub use self::ImplOrTraitItemId::*; @@ -35,6 +34,11 @@ pub use self::IntVarValue::*; pub use self::MethodOrigin::*; pub use self::CopyImplementationError::*; +pub use self::BuiltinBound::Send as BoundSend; +pub use self::BuiltinBound::Sized as BoundSized; +pub use self::BuiltinBound::Copy as BoundCopy; +pub use self::BuiltinBound::Sync as BoundSync; + use ast_map::{self, LinkedPath}; use back::svh::Svh; use session::Session; @@ -78,7 +82,7 @@ use std::mem; use std::ops; use std::rc::Rc; use std::vec::IntoIter; -use collections::enum_set::{EnumSet, CLike}; +use collections::enum_set::{self, EnumSet, CLike}; use std::collections::{HashMap, HashSet}; use syntax::abi; use syntax::ast::{CrateNum, DefId, ItemImpl, ItemTrait, LOCAL_CRATE}; @@ -130,7 +134,7 @@ impl ImplOrTraitItemContainer { } } -#[derive(Clone, Debug)] +#[derive(Clone)] pub enum ImplOrTraitItem<'tcx> { ConstTraitItem(Rc>), MethodTraitItem(Rc>), @@ -293,7 +297,7 @@ pub struct ItemVariances { pub regions: VecPerParamSpace, } -#[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Debug, Copy)] +#[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Copy)] pub enum Variance { Covariant, // T <: T iff A <: B -- e.g., function return type Invariant, // T <: T iff B == A -- e.g., type of mutable cell @@ -301,7 +305,7 @@ pub enum Variance { Bivariant, // T <: T -- e.g., unused type parameter } -#[derive(Copy, Clone, Debug)] +#[derive(Copy, Clone)] pub enum AutoAdjustment<'tcx> { AdjustReifyFnPointer, // go from a fn-item type to a fn-pointer type AdjustUnsafeFnPointer, // go from a safe fn pointer to an unsafe fn pointer @@ -370,7 +374,7 @@ pub enum AutoAdjustment<'tcx> { /// unsize: Some(Box<[i32]>), /// } /// ``` -#[derive(Copy, Clone, Debug)] +#[derive(Copy, Clone)] pub struct AutoDerefRef<'tcx> { /// Step 1. Apply a number of dereferences, producing an lvalue. pub autoderefs: usize, @@ -400,7 +404,7 @@ pub enum CustomCoerceUnsized { Struct(usize) } -#[derive(Clone, Debug)] +#[derive(Clone)] pub enum MethodOrigin<'tcx> { // fully statically resolved method MethodStatic(ast::DefId), @@ -418,7 +422,7 @@ pub enum MethodOrigin<'tcx> { // details for a method invoked with a receiver whose type is a type parameter // with a bounded trait. -#[derive(Clone, Debug)] +#[derive(Clone)] pub struct MethodParam<'tcx> { // the precise trait reference that occurs as a bound -- this may // be a supertrait of what the user actually typed. Note that it @@ -439,7 +443,7 @@ pub struct MethodParam<'tcx> { } // details for a method invoked with a receiver whose type is an object -#[derive(Clone, Debug)] +#[derive(Clone)] pub struct MethodObject<'tcx> { // the (super)trait containing the method to be invoked pub trait_ref: TraitRef<'tcx>, @@ -803,7 +807,7 @@ impl<'tcx> ctxt<'tcx> { self.free_region_maps.borrow()[&id].clone() } - pub fn lift>(&self, value: &T) -> Option { + pub fn lift>(&self, value: &T) -> Option { value.lift_to_tcx(self) } } @@ -825,7 +829,7 @@ impl<'tcx, A: Lift<'tcx>, B: Lift<'tcx>> Lift<'tcx> for (A, B) { } } -impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for Vec { +impl<'tcx, T: Lift<'tcx>> Lift<'tcx> for [T] { type Lifted = Vec; fn lift_to_tcx(&self, tcx: &ctxt<'tcx>) -> Option { let mut result = Vec::with_capacity(self.len()); @@ -1115,7 +1119,6 @@ impl<'tcx> ctxt<'tcx> { } } -#[derive(Debug)] pub struct TyS<'tcx> { pub sty: TypeVariants<'tcx>, pub flags: Cell, @@ -1238,7 +1241,7 @@ pub struct BareFnTy<'tcx> { pub sig: PolyFnSig<'tcx>, } -#[derive(Clone, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, PartialEq, Eq, Hash)] pub struct ClosureTy<'tcx> { pub unsafety: ast::Unsafety, pub abi: abi::Abi, @@ -1309,7 +1312,7 @@ impl<'tcx> PolyFnSig<'tcx> { } } -#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct ParamTy { pub space: subst::ParamSpace, pub idx: u32, @@ -1363,7 +1366,7 @@ pub struct DebruijnIndex { } /// Representation of regions: -#[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, Copy)] +#[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Copy)] pub enum Region { // Region bound in a type or fn declaration which will be // substituted 'early' -- that is, at the same time when type @@ -1411,7 +1414,7 @@ pub struct EarlyBoundRegion { /// Upvars do not get their own node-id. Instead, we use the pair of /// the original var id (that is, the root variable that is referenced /// by the upvar) and the id of the closure expression. -#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct UpvarId { pub var_id: ast::NodeId, pub closure_expr_id: ast::NodeId, @@ -1476,7 +1479,7 @@ pub enum UpvarCapture { ByRef(UpvarBorrow), } -#[derive(PartialEq, Clone, RustcEncodable, RustcDecodable, Debug, Copy)] +#[derive(PartialEq, Clone, RustcEncodable, RustcDecodable, Copy)] pub struct UpvarBorrow { /// The kind of borrow: by-ref upvars have access to shared /// immutable borrows, which are not part of the normal language @@ -1516,7 +1519,7 @@ impl Region { } #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, - RustcEncodable, RustcDecodable, Debug, Copy)] + RustcEncodable, RustcDecodable, Copy)] /// A "free" region `fr` can be interpreted as "some region /// at least as big as the scope `fr.scope`". pub struct FreeRegion { @@ -1525,7 +1528,7 @@ pub struct FreeRegion { } #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, - RustcEncodable, RustcDecodable, Debug, Copy)] + RustcEncodable, RustcDecodable, Copy, Debug)] pub enum BoundRegion { /// An anonymous region parameter for a given fn (&T) BrAnon(u32), @@ -1636,7 +1639,7 @@ pub enum TypeVariants<'tcx> { TyError, } -#[derive(Clone, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, PartialEq, Eq, Hash)] pub struct TraitTy<'tcx> { pub principal: ty::PolyTraitRef<'tcx>, pub bounds: ExistentialBounds<'tcx>, @@ -1707,7 +1710,7 @@ impl<'tcx> TraitTy<'tcx> { /// Note that a `TraitRef` introduces a level of region binding, to /// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a /// U>` or higher-ranked object types. -#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] +#[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct TraitRef<'tcx> { pub def_id: DefId, pub substs: &'tcx Substs<'tcx>, @@ -1842,7 +1845,7 @@ pub enum type_err<'tcx> { /// Bounds suitable for a named type parameter like `A` in `fn foo` /// as well as the existential type parameter in an object type. -#[derive(PartialEq, Eq, Hash, Clone, Debug)] +#[derive(PartialEq, Eq, Hash, Clone)] pub struct ParamBounds<'tcx> { pub region_bounds: Vec, pub builtin_bounds: BuiltinBounds, @@ -1855,41 +1858,57 @@ pub struct ParamBounds<'tcx> { /// major difference between this case and `ParamBounds` is that /// general purpose trait bounds are omitted and there must be /// *exactly one* region. -#[derive(PartialEq, Eq, Hash, Clone, Debug)] +#[derive(PartialEq, Eq, Hash, Clone)] pub struct ExistentialBounds<'tcx> { pub region_bound: ty::Region, pub builtin_bounds: BuiltinBounds, pub projection_bounds: Vec>, } -pub type BuiltinBounds = EnumSet; +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub struct BuiltinBounds(EnumSet); + +impl BuiltinBounds { + pub fn empty() -> BuiltinBounds { + BuiltinBounds(EnumSet::new()) + } + + pub fn iter(&self) -> enum_set::Iter { + self.into_iter() + } +} + +impl ops::Deref for BuiltinBounds { + type Target = EnumSet; + fn deref(&self) -> &Self::Target { &self.0 } +} + +impl ops::DerefMut for BuiltinBounds { + fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } +} + +impl<'a> IntoIterator for &'a BuiltinBounds { + type Item = BuiltinBound; + type IntoIter = enum_set::Iter; + fn into_iter(self) -> Self::IntoIter { + (**self).into_iter() + } +} #[derive(Clone, RustcEncodable, PartialEq, Eq, RustcDecodable, Hash, Debug, Copy)] #[repr(usize)] pub enum BuiltinBound { - BoundSend, - BoundSized, - BoundCopy, - BoundSync, -} - -pub fn empty_builtin_bounds() -> BuiltinBounds { - EnumSet::new() -} - -pub fn all_builtin_bounds() -> BuiltinBounds { - let mut set = EnumSet::new(); - set.insert(BoundSend); - set.insert(BoundSized); - set.insert(BoundSync); - set + Send, + Sized, + Copy, + Sync, } /// An existential bound that does not implement any traits. pub fn region_existential_bound<'tcx>(r: ty::Region) -> ExistentialBounds<'tcx> { ty::ExistentialBounds { region_bound: r, - builtin_bounds: empty_builtin_bounds(), + builtin_bounds: BuiltinBounds::empty(), projection_bounds: Vec::new() } } @@ -1968,7 +1987,7 @@ impl cmp::PartialEq for InferRegion { } impl fmt::Debug for TyVid { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "_#{}t", self.index) } } @@ -2024,7 +2043,7 @@ impl fmt::Debug for IntVarValue { /// from `T:'a` annotations appearing in the type definition. If /// this is `None`, then the default is inherited from the /// surrounding context. See RFC #599 for details. -#[derive(Copy, Clone, Debug)] +#[derive(Copy, Clone)] pub enum ObjectLifetimeDefault { /// Require an explicit annotation. Occurs when multiple /// `T:'a` constraints are found. @@ -2034,7 +2053,7 @@ pub enum ObjectLifetimeDefault { Specific(Region), } -#[derive(Clone, Debug)] +#[derive(Clone)] pub struct TypeParameterDef<'tcx> { pub name: ast::Name, pub def_id: ast::DefId, @@ -2097,7 +2116,7 @@ impl<'tcx> Generics<'tcx> { } /// Bounds on generics. -#[derive(Clone, Debug)] +#[derive(Clone)] pub struct GenericPredicates<'tcx> { pub predicates: VecPerParamSpace>, } @@ -2127,7 +2146,7 @@ impl<'tcx> GenericPredicates<'tcx> { } } -#[derive(Clone, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, PartialEq, Eq, Hash)] pub enum Predicate<'tcx> { /// Corresponds to `where Foo : Bar`. `Foo` here would be /// the `Self` type of the trait reference and `A`, `B`, and `C` @@ -2258,7 +2277,7 @@ impl<'tcx> Predicate<'tcx> { } } -#[derive(Clone, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, PartialEq, Eq, Hash)] pub struct TraitPredicate<'tcx> { pub trait_ref: TraitRef<'tcx> } @@ -2306,7 +2325,7 @@ pub type PolyTypeOutlivesPredicate<'tcx> = PolyOutlivesPredicate, ty::R /// equality between arbitrary types. Processing an instance of Form /// #2 eventually yields one of these `ProjectionPredicate` /// instances to normalize the LHS. -#[derive(Clone, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, PartialEq, Eq, Hash)] pub struct ProjectionPredicate<'tcx> { pub projection_ty: ProjectionTy<'tcx>, pub ty: Ty<'tcx>, @@ -2495,7 +2514,7 @@ impl<'tcx> Predicate<'tcx> { /// `[[], [U:Bar]]`. Now if there were some particular reference /// like `Foo`, then the `InstantiatedPredicates` would be `[[], /// [usize:Bar]]`. -#[derive(Clone, Debug)] +#[derive(Clone)] pub struct InstantiatedPredicates<'tcx> { pub predicates: VecPerParamSpace>, } @@ -3679,7 +3698,7 @@ impl<'tcx> ItemSubsts<'tcx> { impl<'tcx> ParamBounds<'tcx> { pub fn empty() -> ParamBounds<'tcx> { ParamBounds { - builtin_bounds: empty_builtin_bounds(), + builtin_bounds: BuiltinBounds::empty(), trait_bounds: Vec::new(), region_bounds: Vec::new(), projection_bounds: Vec::new(), @@ -5316,138 +5335,132 @@ pub fn ty_sort_string(cx: &ctxt, ty: Ty) -> String { } } -impl<'tcx> Repr for ty::type_err<'tcx> { - fn repr(&self) -> String { - tls::with(|tcx| ty::type_err_to_str(tcx, self)) - } -} - /// Explains the source of a type err in a short, human readable way. This is meant to be placed /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()` /// afterwards to present additional details, particularly when it comes to lifetime-related /// errors. -pub fn type_err_to_str(cx: &ctxt, err: &type_err) -> String { - match *err { - terr_cyclic_ty => "cyclic type of infinite size".to_string(), - terr_mismatch => "types differ".to_string(), - terr_unsafety_mismatch(values) => { - format!("expected {} fn, found {} fn", - values.expected, - values.found) - } - terr_abi_mismatch(values) => { - format!("expected {} fn, found {} fn", - values.expected, - values.found) - } - terr_mutability => "values differ in mutability".to_string(), - terr_box_mutability => { - "boxed values differ in mutability".to_string() - } - terr_vec_mutability => "vectors differ in mutability".to_string(), - terr_ptr_mutability => "pointers differ in mutability".to_string(), - terr_ref_mutability => "references differ in mutability".to_string(), - terr_ty_param_size(values) => { - format!("expected a type with {} type params, \ - found one with {} type params", - values.expected, - values.found) - } - terr_fixed_array_size(values) => { - format!("expected an array with a fixed size of {} elements, \ - found one with {} elements", - values.expected, - values.found) - } - terr_tuple_size(values) => { - format!("expected a tuple with {} elements, \ - found one with {} elements", - values.expected, - values.found) - } - terr_arg_count => { - "incorrect number of function parameters".to_string() - } - terr_regions_does_not_outlive(..) => { - "lifetime mismatch".to_string() - } - terr_regions_not_same(..) => { - "lifetimes are not the same".to_string() - } - terr_regions_no_overlap(..) => { - "lifetimes do not intersect".to_string() - } - terr_regions_insufficiently_polymorphic(br, _) => { - format!("expected bound lifetime parameter {}, \ - found concrete lifetime", - br.user_string()) - } - terr_regions_overly_polymorphic(br, _) => { - format!("expected concrete lifetime, \ - found bound lifetime parameter {}", - br.user_string()) - } - terr_sorts(values) => { - // A naive approach to making sure that we're not reporting silly errors such as: - // (expected closure, found closure). - let expected_str = ty_sort_string(cx, values.expected); - let found_str = ty_sort_string(cx, values.found); - if expected_str == found_str { - format!("expected {}, found a different {}", expected_str, found_str) - } else { - format!("expected {}, found {}", expected_str, found_str) +impl<'tcx> fmt::Display for type_err<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + terr_cyclic_ty => write!(f, "cyclic type of infinite size"), + terr_mismatch => write!(f, "types differ"), + terr_unsafety_mismatch(values) => { + write!(f, "expected {} fn, found {} fn", + values.expected, + values.found) } - } - terr_traits(values) => { - format!("expected trait `{}`, found trait `{}`", - item_path_str(cx, values.expected), - item_path_str(cx, values.found)) - } - terr_builtin_bounds(values) => { - if values.expected.is_empty() { - format!("expected no bounds, found `{}`", - values.found.user_string()) - } else if values.found.is_empty() { - format!("expected bounds `{}`, found no bounds", - values.expected.user_string()) - } else { - format!("expected bounds `{}`, found bounds `{}`", - values.expected.user_string(), - values.found.user_string()) + terr_abi_mismatch(values) => { + write!(f, "expected {} fn, found {} fn", + values.expected, + values.found) + } + terr_mutability => write!(f, "values differ in mutability"), + terr_box_mutability => { + write!(f, "boxed values differ in mutability") + } + terr_vec_mutability => write!(f, "vectors differ in mutability"), + terr_ptr_mutability => write!(f, "pointers differ in mutability"), + terr_ref_mutability => write!(f, "references differ in mutability"), + terr_ty_param_size(values) => { + write!(f, "expected a type with {} type params, \ + found one with {} type params", + values.expected, + values.found) + } + terr_fixed_array_size(values) => { + write!(f, "expected an array with a fixed size of {} elements, \ + found one with {} elements", + values.expected, + values.found) + } + terr_tuple_size(values) => { + write!(f, "expected a tuple with {} elements, \ + found one with {} elements", + values.expected, + values.found) + } + terr_arg_count => { + write!(f, "incorrect number of function parameters") + } + terr_regions_does_not_outlive(..) => { + write!(f, "lifetime mismatch") + } + terr_regions_not_same(..) => { + write!(f, "lifetimes are not the same") + } + terr_regions_no_overlap(..) => { + write!(f, "lifetimes do not intersect") + } + terr_regions_insufficiently_polymorphic(br, _) => { + write!(f, "expected bound lifetime parameter {}, \ + found concrete lifetime", br) + } + terr_regions_overly_polymorphic(br, _) => { + write!(f, "expected concrete lifetime, \ + found bound lifetime parameter {}", br) + } + terr_sorts(values) => tls::with(|tcx| { + // A naive approach to making sure that we're not reporting silly errors such as: + // (expected closure, found closure). + let expected_str = ty_sort_string(tcx, values.expected); + let found_str = ty_sort_string(tcx, values.found); + if expected_str == found_str { + write!(f, "expected {}, found a different {}", expected_str, found_str) + } else { + write!(f, "expected {}, found {}", expected_str, found_str) + } + }), + terr_traits(values) => tls::with(|tcx| { + write!(f, "expected trait `{}`, found trait `{}`", + item_path_str(tcx, values.expected), + item_path_str(tcx, values.found)) + }), + terr_builtin_bounds(values) => { + if values.expected.is_empty() { + write!(f, "expected no bounds, found `{}`", + values.found) + } else if values.found.is_empty() { + write!(f, "expected bounds `{}`, found no bounds", + values.expected) + } else { + write!(f, "expected bounds `{}`, found bounds `{}`", + values.expected, + values.found) + } + } + terr_integer_as_char => { + write!(f, "expected an integral type, found `char`") + } + terr_int_mismatch(ref values) => { + write!(f, "expected `{:?}`, found `{:?}`", + values.expected, + values.found) + } + terr_float_mismatch(ref values) => { + write!(f, "expected `{:?}`, found `{:?}`", + values.expected, + values.found) + } + terr_variadic_mismatch(ref values) => { + write!(f, "expected {} fn, found {} function", + if values.expected { "variadic" } else { "non-variadic" }, + if values.found { "variadic" } else { "non-variadic" }) + } + terr_convergence_mismatch(ref values) => { + write!(f, "expected {} fn, found {} function", + if values.expected { "converging" } else { "diverging" }, + if values.found { "converging" } else { "diverging" }) + } + terr_projection_name_mismatched(ref values) => { + write!(f, "expected {}, found {}", + values.expected, + values.found) + } + terr_projection_bounds_length(ref values) => { + write!(f, "expected {} associated type bindings, found {}", + values.expected, + values.found) } - } - terr_integer_as_char => { - "expected an integral type, found `char`".to_string() - } - terr_int_mismatch(ref values) => { - format!("expected `{:?}`, found `{:?}`", - values.expected, - values.found) - } - terr_float_mismatch(ref values) => { - format!("expected `{:?}`, found `{:?}`", - values.expected, - values.found) - } - terr_variadic_mismatch(ref values) => { - format!("expected {} fn, found {} function", - if values.expected { "variadic" } else { "non-variadic" }, - if values.found { "variadic" } else { "non-variadic" }) - } - terr_convergence_mismatch(ref values) => { - format!("expected {} fn, found {} function", - if values.expected { "converging" } else { "diverging" }, - if values.found { "converging" } else { "diverging" }) - } - terr_projection_name_mismatched(ref values) => { - format!("expected {}, found {}", - token::get_name(values.expected), - token::get_name(values.found)) - } - terr_projection_bounds_length(ref values) => { - format!("expected {} associated type bindings, found {}", - values.expected, - values.found) } } } @@ -6914,14 +6927,14 @@ pub fn hash_crate_independent<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>, svh: &Svh) - } } -impl Variance { - pub fn to_string(self) -> &'static str { - match self { +impl fmt::Debug for Variance { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str(match *self { Covariant => "+", Contravariant => "-", Invariant => "o", Bivariant => "*", - } + }) } } @@ -7265,7 +7278,7 @@ pub fn liberate_late_bound_regions<'tcx, T>( all_outlive_scope: region::DestructionScopeData, value: &Binder) -> T - where T : TypeFoldable<'tcx> + Repr + where T : TypeFoldable<'tcx> { ty_fold::replace_late_bound_regions( tcx, value, @@ -7276,7 +7289,7 @@ pub fn count_late_bound_regions<'tcx, T>( tcx: &ty::ctxt<'tcx>, value: &Binder) -> usize - where T : TypeFoldable<'tcx> + Repr + where T : TypeFoldable<'tcx> { let (_, skol_map) = ty_fold::replace_late_bound_regions(tcx, value, |_| ty::ReStatic); skol_map.len() @@ -7286,7 +7299,7 @@ pub fn binds_late_bound_regions<'tcx, T>( tcx: &ty::ctxt<'tcx>, value: &Binder) -> bool - where T : TypeFoldable<'tcx> + Repr + where T : TypeFoldable<'tcx> { count_late_bound_regions(tcx, value) > 0 } @@ -7297,7 +7310,7 @@ pub fn flatten_late_bound_regions<'tcx, T>( tcx: &ty::ctxt<'tcx>, bound2_value: &Binder>) -> Binder - where T: TypeFoldable<'tcx> + Repr + where T: TypeFoldable<'tcx> { let bound0_value = bound2_value.skip_binder().skip_binder(); let value = ty_fold::fold_regions(tcx, bound0_value, |region, current_depth| { @@ -7319,7 +7332,7 @@ pub fn no_late_bound_regions<'tcx, T>( tcx: &ty::ctxt<'tcx>, value: &Binder) -> Option - where T : TypeFoldable<'tcx> + Repr + Clone + where T : TypeFoldable<'tcx> { if binds_late_bound_regions(tcx, value) { None @@ -7334,7 +7347,7 @@ pub fn erase_late_bound_regions<'tcx, T>( tcx: &ty::ctxt<'tcx>, value: &Binder) -> T - where T : TypeFoldable<'tcx> + Repr + where T : TypeFoldable<'tcx> { ty_fold::replace_late_bound_regions(tcx, value, |_| ty::ReStatic).0 } @@ -7351,7 +7364,7 @@ pub fn anonymize_late_bound_regions<'tcx, T>( tcx: &ctxt<'tcx>, sig: &Binder) -> Binder - where T : TypeFoldable<'tcx> + Repr, + where T : TypeFoldable<'tcx>, { let mut counter = 0; ty::Binder(ty_fold::replace_late_bound_regions(tcx, sig, |_| { @@ -7371,58 +7384,45 @@ impl DebruijnIndex { } } -impl<'tcx> Repr for AutoAdjustment<'tcx> { - fn repr(&self) -> String { +impl<'tcx> fmt::Debug for AutoAdjustment<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { AdjustReifyFnPointer => { - format!("AdjustReifyFnPointer") + write!(f, "AdjustReifyFnPointer") } AdjustUnsafeFnPointer => { - format!("AdjustUnsafeFnPointer") + write!(f, "AdjustUnsafeFnPointer") } AdjustDerefRef(ref data) => { - data.repr() + write!(f, "{:?}", data) } } } } -impl<'tcx> Repr for AutoDerefRef<'tcx> { - fn repr(&self) -> String { - format!("AutoDerefRef({}, unsize={}, {})", - self.autoderefs, self.unsize.repr(), self.autoref.repr()) +impl<'tcx> fmt::Debug for AutoDerefRef<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "AutoDerefRef({}, unsize={:?}, {:?})", + self.autoderefs, self.unsize, self.autoref) } } -impl<'tcx> Repr for AutoRef<'tcx> { - fn repr(&self) -> String { +impl<'tcx> fmt::Debug for TraitTy<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "TraitTy({:?},{:?})", + self.principal, + self.bounds) + } +} + +impl<'tcx> fmt::Debug for ty::Predicate<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - AutoPtr(a, b) => { - format!("AutoPtr({},{:?})", a.repr(), b) - } - AutoUnsafe(ref a) => { - format!("AutoUnsafe({:?})", a) - } - } - } -} - -impl<'tcx> Repr for TraitTy<'tcx> { - fn repr(&self) -> String { - format!("TraitTy({},{})", - self.principal.repr(), - self.bounds.repr()) - } -} - -impl<'tcx> Repr for ty::Predicate<'tcx> { - fn repr(&self) -> String { - match *self { - Predicate::Trait(ref a) => a.repr(), - Predicate::Equate(ref pair) => pair.repr(), - Predicate::RegionOutlives(ref pair) => pair.repr(), - Predicate::TypeOutlives(ref pair) => pair.repr(), - Predicate::Projection(ref pair) => pair.repr(), + Predicate::Trait(ref a) => write!(f, "{:?}", a), + Predicate::Equate(ref pair) => write!(f, "{:?}", pair), + Predicate::RegionOutlives(ref pair) => write!(f, "{:?}", pair), + Predicate::TypeOutlives(ref pair) => write!(f, "{:?}", pair), + Predicate::Projection(ref pair) => write!(f, "{:?}", pair), } } } @@ -7628,14 +7628,6 @@ impl<'tcx> RegionEscape for ProjectionTy<'tcx> { } } -impl<'tcx> Repr for ty::ProjectionPredicate<'tcx> { - fn repr(&self) -> String { - format!("ProjectionPredicate({}, {})", - self.projection_ty.repr(), - self.ty.repr()) - } -} - pub trait HasProjectionTypes { fn has_projection_types(&self) -> bool; } @@ -7870,48 +7862,46 @@ impl ReferencesError for Region } } -impl<'tcx> Repr for ClosureTy<'tcx> { - fn repr(&self) -> String { - format!("ClosureTy({},{},{})", - self.unsafety, - self.sig.repr(), - self.abi) +impl<'tcx> fmt::Debug for ClosureTy<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "ClosureTy({},{:?},{})", + self.unsafety, + self.sig, + self.abi) } } -impl<'tcx> Repr for ClosureUpvar<'tcx> { - fn repr(&self) -> String { - format!("ClosureUpvar({},{})", - self.def.repr(), - self.ty.repr()) +impl<'tcx> fmt::Debug for ClosureUpvar<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "ClosureUpvar({:?},{:?})", + self.def, + self.ty) } } -impl<'tcx> Repr for field<'tcx> { - fn repr(&self) -> String { - format!("field({},{})", - self.name.repr(), - self.mt.repr()) +impl<'tcx> fmt::Debug for field<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "field({},{})", self.name, self.mt) } } -impl<'a, 'tcx> Repr for ParameterEnvironment<'a, 'tcx> { - fn repr(&self) -> String { - format!("ParameterEnvironment(\ - free_substs={}, \ - implicit_region_bound={}, \ - caller_bounds={})", - self.free_substs.repr(), - self.implicit_region_bound.repr(), - self.caller_bounds.repr()) +impl<'a, 'tcx> fmt::Debug for ParameterEnvironment<'a, 'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "ParameterEnvironment(\ + free_substs={:?}, \ + implicit_region_bound={:?}, \ + caller_bounds={:?})", + self.free_substs, + self.implicit_region_bound, + self.caller_bounds) } } -impl<'tcx> Repr for ObjectLifetimeDefault { - fn repr(&self) -> String { +impl<'tcx> fmt::Debug for ObjectLifetimeDefault { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - ObjectLifetimeDefault::Ambiguous => format!("Ambiguous"), - ObjectLifetimeDefault::Specific(ref r) => r.repr(), + ObjectLifetimeDefault::Ambiguous => write!(f, "Ambiguous"), + ObjectLifetimeDefault::Specific(ref r) => write!(f, "{:?}", r), } } } diff --git a/src/librustc/middle/ty_fold.rs b/src/librustc/middle/ty_fold.rs index 00905eda1498..adc282bc2fdd 100644 --- a/src/librustc/middle/ty_fold.rs +++ b/src/librustc/middle/ty_fold.rs @@ -38,6 +38,8 @@ use middle::subst; use middle::subst::VecPerParamSpace; use middle::ty::{self, Ty}; use middle::traits; + +use std::fmt; use std::rc::Rc; use syntax::abi; use syntax::ast; @@ -50,7 +52,7 @@ use util::ppaux::Repr; /// The TypeFoldable trait is implemented for every type that can be folded. /// Basically, every type that has a corresponding method in TypeFolder. -pub trait TypeFoldable<'tcx>: Repr + Clone { +pub trait TypeFoldable<'tcx>: fmt::Debug + Clone { fn fold_with>(&self, folder: &mut F) -> Self; } @@ -74,7 +76,7 @@ pub trait TypeFolder<'tcx> : Sized { fn exit_region_binder(&mut self) { } fn fold_binder(&mut self, t: &ty::Binder) -> ty::Binder - where T : TypeFoldable<'tcx> + Repr + Clone + where T : TypeFoldable<'tcx> { // FIXME(#20526) this should replace `enter_region_binder`/`exit_region_binder`. super_fold_binder(self, t) @@ -197,7 +199,7 @@ impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Vec { } } -impl<'tcx, T:TypeFoldable<'tcx>+Repr+Clone> TypeFoldable<'tcx> for ty::Binder { +impl<'tcx, T:TypeFoldable<'tcx>> TypeFoldable<'tcx> for ty::Binder { fn fold_with>(&self, folder: &mut F) -> ty::Binder { folder.fold_binder(self) } @@ -885,7 +887,7 @@ pub fn replace_late_bound_regions<'tcx,T,F>(tcx: &ty::ctxt<'tcx>, mut f: F) -> (T, FnvHashMap) where F : FnMut(ty::BoundRegion) -> ty::Region, - T : TypeFoldable<'tcx> + Repr, + T : TypeFoldable<'tcx>, { debug!("replace_late_bound_regions({})", value.repr()); let mut replacer = RegionReplacer::new(tcx, &mut f); @@ -994,8 +996,8 @@ pub fn shift_region(region: ty::Region, amount: u32) -> ty::Region { } } -pub fn shift_regions<'tcx, T:TypeFoldable<'tcx>+Repr>(tcx: &ty::ctxt<'tcx>, - amount: u32, value: &T) -> T { +pub fn shift_regions<'tcx, T:TypeFoldable<'tcx>>(tcx: &ty::ctxt<'tcx>, + amount: u32, value: &T) -> T { debug!("shift_regions(value={}, amount={})", value.repr(), amount); diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index 3851eb6573ba..5d524c51b5eb 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -9,15 +9,12 @@ // except according to those terms. -use middle::def; -use middle::region; -use middle::subst::{VecPerParamSpace,Subst}; -use middle::subst; +use middle::subst::{self, Subst}; use middle::ty::{BoundRegion, BrAnon, BrNamed}; use middle::ty::{ReEarlyBound, BrFresh, ctxt}; use middle::ty::{ReFree, ReScope, ReInfer, ReStatic, Region, ReEmpty}; use middle::ty::{ReSkolemized, ReVar, BrEnv}; -use middle::ty::{mt, Ty, ParamTy}; +use middle::ty::{mt, Ty}; use middle::ty::{TyBool, TyChar, TyStruct, TyEnum}; use middle::ty::{TyError, TyStr, TyArray, TySlice, TyFloat, TyBareFn}; use middle::ty::{TyParam, TyRawPtr, TyRef, TyTuple}; @@ -26,16 +23,10 @@ use middle::ty::{TyBox, TyTrait, TyInt, TyUint, TyInfer}; use middle::ty; use middle::ty_fold::{self, TypeFoldable}; -use std::collections::HashMap; -use std::collections::hash_state::HashState; -use std::hash::Hash; -use std::rc::Rc; +use std::fmt; use syntax::abi; -use syntax::codemap::Span; use syntax::parse::token; -use syntax::ptr::P; use syntax::{ast, ast_util}; -use syntax::owned_slice::OwnedSlice; /// Produces a string suitable for debugging output. pub trait Repr { @@ -47,51 +38,114 @@ pub trait UserString { fn user_string(&self) -> String; } +impl Repr for T { + fn repr(&self) -> String { + format!("{:?}", *self) + } +} + +impl UserString for T { + fn user_string(&self) -> String { + format!("{}", *self) + } +} + pub fn verbose() -> bool { ty::tls::with(|tcx| tcx.sess.verbose()) } -fn parameterized(substs: &subst::Substs, +fn fn_sig(f: &mut fmt::Formatter, + inputs: &[Ty], + variadic: bool, + output: ty::FnOutput) + -> fmt::Result { + try!(write!(f, "(")); + let mut inputs = inputs.iter(); + if let Some(&ty) = inputs.next() { + try!(write!(f, "{}", ty)); + for &ty in inputs { + try!(write!(f, ", {}", ty)); + } + if variadic { + try!(write!(f, ", ...")); + } + } + try!(write!(f, ")")); + + match output { + ty::FnConverging(ty) => { + if !ty::type_is_nil(ty) { + try!(write!(f, " -> {}", ty)); + } + Ok(()) + } + ty::FnDiverging => { + write!(f, " -> !") + } + } +} + +fn parameterized(f: &mut fmt::Formatter, + substs: &subst::Substs, did: ast::DefId, projections: &[ty::ProjectionPredicate], get_generics: GG) - -> String + -> fmt::Result where GG: for<'tcx> FnOnce(&ty::ctxt<'tcx>) -> ty::Generics<'tcx> { - let base = ty::tls::with(|tcx| ty::item_path_str(tcx, did)); - if verbose() { - let mut strings = vec![]; + let (fn_trait_kind, verbose) = try!(ty::tls::with(|tcx| { + try!(write!(f, "{}", ty::item_path_str(tcx, did))); + Ok((tcx.lang_items.fn_trait_kind(did), tcx.sess.verbose())) + })); + + let mut empty = true; + let mut start_or_continue = |f: &mut fmt::Formatter, start: &str, cont: &str| { + if empty { + empty = false; + write!(f, "{}", start) + } else { + write!(f, "{}", cont) + } + }; + + if verbose { match substs.regions { subst::ErasedRegions => { - strings.push(format!("..")); + try!(start_or_continue(f, "<", ", ")); + try!(write!(f, "..")); } subst::NonerasedRegions(ref regions) => { for region in regions { - strings.push(region.repr()); + try!(start_or_continue(f, "<", ", ")); + try!(write!(f, "{:?}", region)); } } } - for ty in &substs.types { - strings.push(ty.repr()); + for &ty in &substs.types { + try!(start_or_continue(f, "<", ", ")); + try!(write!(f, "{}", ty)); } for projection in projections { - strings.push(format!("{}={}", - projection.projection_ty.item_name.user_string(), - projection.ty.user_string())); + try!(start_or_continue(f, "<", ", ")); + try!(write!(f, "{}={}", + projection.projection_ty.item_name, + projection.ty)); } - return if strings.is_empty() { - format!("{}", base) - } else { - format!("{}<{}>", base, strings.connect(",")) - }; + return start_or_continue(f, "", ">"); } - let mut strs = Vec::new(); + if fn_trait_kind.is_some() && projections.len() == 1 { + let projection_ty = projections[0].ty; + if let TyTuple(ref args) = substs.types.get_slice(subst::TypeSpace)[0].sty { + return fn_sig(f, args, false, ty::FnConverging(projection_ty)); + } + } match substs.regions { subst::ErasedRegions => { } subst::NonerasedRegions(ref regions) => { for &r in regions { + try!(start_or_continue(f, "<", ", ")); let s = r.user_string(); if s.is_empty() { // This happens when the value of the region @@ -99,9 +153,9 @@ fn parameterized(substs: &subst::Substs, // because the user omitted it in the first place, // or because it refers to some block in the code, // etc. I'm not sure how best to serialize this. - strs.push(format!("'_")); + try!(write!(f, "'_")); } else { - strs.push(s) + try!(write!(f, "{}", s)); } } } @@ -112,14 +166,13 @@ fn parameterized(substs: &subst::Substs, // ICEs trying to fetch the generics early in the pipeline. This // is kind of a hacky workaround in that -Z verbose is required to // avoid those ICEs. - ty::tls::with(|tcx| { + let tps = substs.types.get_slice(subst::TypeSpace); + let num_defaults = ty::tls::with(|tcx| { let generics = get_generics(tcx); let has_self = substs.self_ty().is_some(); - let tps = substs.types.get_slice(subst::TypeSpace); let ty_params = generics.types.get_slice(subst::TypeSpace); - let has_defaults = ty_params.last().map_or(false, |def| def.default.is_some()); - let num_defaults = if has_defaults { + if ty_params.last().map_or(false, |def| def.default.is_some()) { let substs = tcx.lift(&substs); ty_params.iter().zip(tps).rev().take_while(|&(def, &actual)| { match def.default { @@ -142,49 +195,29 @@ fn parameterized(substs: &subst::Substs, }).count() } else { 0 - }; - - for t in &tps[..tps.len() - num_defaults] { - strs.push(t.user_string()) } }); - for projection in projections { - strs.push(format!("{}={}", - projection.projection_ty.item_name.user_string(), - projection.ty.user_string())); + for &ty in &tps[..tps.len() - num_defaults] { + try!(start_or_continue(f, "<", ", ")); + try!(write!(f, "{}", ty)); } - let fn_trait_kind = ty::tls::with(|tcx| tcx.lang_items.fn_trait_kind(did)); - if fn_trait_kind.is_some() && projections.len() == 1 { - let projection_ty = projections[0].ty; - let tail = - if ty::type_is_nil(projection_ty) { - format!("") - } else { - format!(" -> {}", projection_ty.user_string()) - }; - format!("{}({}){}", - base, - if strs[0].starts_with("(") && strs[0].ends_with(",)") { - &strs[0][1 .. strs[0].len() - 2] // Remove '(' and ',)' - } else if strs[0].starts_with("(") && strs[0].ends_with(")") { - &strs[0][1 .. strs[0].len() - 1] // Remove '(' and ')' - } else { - &strs[0][..] - }, - tail) - } else if !strs.is_empty() { - format!("{}<{}>", base, strs.connect(", ")) - } else { - format!("{}", base) + for projection in projections { + try!(start_or_continue(f, "<", ", ")); + try!(write!(f, "{}={}", + projection.projection_ty.item_name, + projection.ty)); } + + start_or_continue(f, "", ">") } -fn in_binder<'tcx, T, U>(tcx: &ty::ctxt<'tcx>, +fn in_binder<'tcx, T, U>(f: &mut fmt::Formatter, + tcx: &ty::ctxt<'tcx>, original: &ty::Binder, - lifted: Option>) -> String - where T: UserString, U: UserString + TypeFoldable<'tcx> + lifted: Option>) -> fmt::Result + where T: fmt::Display, U: fmt::Display + TypeFoldable<'tcx> { // Replace any anonymous late-bound regions with named // variants, using gensym'd identifiers, so that we can @@ -194,110 +227,38 @@ fn in_binder<'tcx, T, U>(tcx: &ty::ctxt<'tcx>, let value = if let Some(v) = lifted { v } else { - return original.0.user_string(); + return write!(f, "{}", original.0); }; - let mut names = Vec::new(); - let value_str = ty_fold::replace_late_bound_regions(tcx, &value, |br| { + + let mut empty = true; + let mut start_or_continue = |f: &mut fmt::Formatter, start: &str, cont: &str| { + if empty { + empty = false; + write!(f, "{}", start) + } else { + write!(f, "{}", cont) + } + }; + + let new_value = ty_fold::replace_late_bound_regions(tcx, &value, |br| { + let _ = start_or_continue(f, "for<", ", "); ty::ReLateBound(ty::DebruijnIndex::new(1), match br { ty::BrNamed(_, name) => { - names.push(token::get_name(name).to_string()); + let _ = write!(f, "{}", name); br } ty::BrAnon(_) | ty::BrFresh(_) | ty::BrEnv => { - let name = token::gensym("'r"); - names.push(token::get_name(name).to_string()); + let name = token::intern("'r"); + let _ = write!(f, "{}", name); ty::BrNamed(ast_util::local_def(ast::DUMMY_NODE_ID), name) } }) - }).0.user_string(); + }).0; - if names.is_empty() { - value_str - } else { - format!("for<{}> {}", names.connect(","), value_str) - } -} - -impl Repr for Option { - fn repr(&self) -> String { - match self { - &None => "None".to_string(), - &Some(ref t) => t.repr(), - } - } -} - -impl Repr for P { - fn repr(&self) -> String { - (**self).repr() - } -} - -impl Repr for Result { - fn repr(&self) -> String { - match self { - &Ok(ref t) => t.repr(), - &Err(ref u) => format!("Err({})", u.repr()) - } - } -} - -impl Repr for () { - fn repr(&self) -> String { - "()".to_string() - } -} - -impl<'a, T: ?Sized +Repr> Repr for &'a T { - fn repr(&self) -> String { - (**self).repr() - } -} - -impl Repr for Rc { - fn repr(&self) -> String { - (&**self).repr() - } -} - -impl Repr for Box { - fn repr(&self) -> String { - (&**self).repr() - } -} - -impl Repr for [T] { - fn repr(&self) -> String { - format!("[{}]", self.iter().map(|t| t.repr()).collect::>().connect(", ")) - } -} - -impl Repr for OwnedSlice { - fn repr(&self) -> String { - self[..].repr() - } -} - -// This is necessary to handle types like Option>, for which -// autoderef cannot convert the &[T] handler -impl Repr for Vec { - fn repr(&self) -> String { - self[..].repr() - } -} - -impl<'a, T: ?Sized +UserString> UserString for &'a T { - fn user_string(&self) -> String { - (**self).user_string() - } -} - -impl Repr for def::Def { - fn repr(&self) -> String { - format!("{:?}", *self) - } + try!(start_or_continue(f, "", "> ")); + write!(f, "{}", new_value) } /// This curious type is here to help pretty-print trait objects. In @@ -311,274 +272,194 @@ impl Repr for def::Def { /// Right now there is only one trait in an object that can have /// projection bounds, so we just stuff them altogether. But in /// reality we should eventually sort things out better. -type TraitAndProjections<'tcx> = - (ty::TraitRef<'tcx>, Vec>); +#[derive(Clone, Debug)] +struct TraitAndProjections<'tcx>(ty::TraitRef<'tcx>, Vec>); -impl<'tcx> UserString for TraitAndProjections<'tcx> { - fn user_string(&self) -> String { - let &(ref trait_ref, ref projection_bounds) = self; - parameterized(trait_ref.substs, +impl<'tcx> TypeFoldable<'tcx> for TraitAndProjections<'tcx> { + fn fold_with>(&self, folder: &mut F) + -> TraitAndProjections<'tcx> { + TraitAndProjections(self.0.fold_with(folder), self.1.fold_with(folder)) + } +} + +impl<'tcx> fmt::Display for TraitAndProjections<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let TraitAndProjections(ref trait_ref, ref projection_bounds) = *self; + parameterized(f, trait_ref.substs, trait_ref.def_id, - &projection_bounds[..], + projection_bounds, |tcx| ty::lookup_trait_def(tcx, trait_ref.def_id).generics.clone()) } } -impl<'tcx> UserString for ty::TraitTy<'tcx> { - fn user_string(&self) -> String { - let &ty::TraitTy { ref principal, ref bounds } = self; - - let mut components = vec![]; - - let tap: ty::Binder> = - ty::Binder((principal.0.clone(), - bounds.projection_bounds.iter().map(|x| x.0.clone()).collect())); +impl<'tcx> fmt::Display for ty::TraitTy<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let bounds = &self.bounds; // Generate the main trait ref, including associated types. - components.push(tap.user_string()); + try!(ty::tls::with(|tcx| { + let principal = tcx.lift(&self.principal.0) + .expect("could not lift TraitRef for printing"); + let projections = tcx.lift(&bounds.projection_bounds[..]) + .expect("could not lift projections for printing"); + let projections = projections.map_in_place(|p| p.0); + + let tap = ty::Binder(TraitAndProjections(principal, projections)); + in_binder(f, tcx, &ty::Binder(""), Some(tap)) + })); // Builtin bounds. for bound in &bounds.builtin_bounds { - components.push(bound.user_string()); + try!(write!(f, " + {:?}", bound)); } // Region, if not obviously implied by builtin bounds. if bounds.region_bound != ty::ReStatic { // Region bound is implied by builtin bounds: - components.push(bounds.region_bound.user_string()); + let bound = bounds.region_bound.user_string(); + if !bound.is_empty() { + try!(write!(f, " + {}", bound)); + } } - components.retain(|s| !s.is_empty()); - - components.connect(" + ") + Ok(()) } } -impl<'tcx> Repr for ty::TypeParameterDef<'tcx> { - fn repr(&self) -> String { - format!("TypeParameterDef({:?}, {:?}/{})", - self.def_id, - self.space, - self.index) +impl<'tcx> fmt::Debug for ty::TypeParameterDef<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "TypeParameterDef({:?}, {:?}/{})", + self.def_id, self.space, self.index) } } -impl Repr for ty::RegionParameterDef { - fn repr(&self) -> String { - format!("RegionParameterDef(name={}, def_id={}, bounds={})", - token::get_name(self.name), - self.def_id.repr(), - self.bounds.repr()) +impl<'tcx> fmt::Debug for ty::TyS<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", *self) } } -impl<'tcx> Repr for ty::TyS<'tcx> { - fn repr(&self) -> String { - self.user_string() +impl<'tcx> fmt::Display for ty::mt<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}{}", + if self.mutbl == ast::MutMutable { "mut " } else { "" }, + self.ty) } } -impl<'tcx> Repr for ty::mt<'tcx> { - fn repr(&self) -> String { - format!("{}{}", - if self.mutbl == ast::MutMutable { "mut " } else { "" }, - self.ty.user_string()) +impl<'tcx> fmt::Debug for subst::Substs<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Substs[types={:?}, regions={:?}]", + self.types, self.regions) } } -impl<'tcx> Repr for subst::Substs<'tcx> { - fn repr(&self) -> String { - format!("Substs[types={}, regions={}]", - self.types.repr(), - self.regions.repr()) +impl<'tcx> fmt::Debug for ty::ItemSubsts<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "ItemSubsts({:?})", self.substs) } } -impl Repr for subst::VecPerParamSpace { - fn repr(&self) -> String { - format!("[{};{};{}]", - self.get_slice(subst::TypeSpace).repr(), - self.get_slice(subst::SelfSpace).repr(), - self.get_slice(subst::FnSpace).repr()) - } -} - -impl<'tcx> Repr for ty::ItemSubsts<'tcx> { - fn repr(&self) -> String { - format!("ItemSubsts({})", self.substs.repr()) - } -} - -impl Repr for subst::RegionSubsts { - fn repr(&self) -> String { +impl fmt::Debug for subst::RegionSubsts { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - subst::ErasedRegions => "erased".to_string(), - subst::NonerasedRegions(ref regions) => regions.repr() + subst::ErasedRegions => write!(f, "erased"), + subst::NonerasedRegions(ref regions) => write!(f, "{:?}", regions) } } } -impl Repr for ty::BuiltinBounds { - fn repr(&self) -> String { - let mut res = Vec::new(); - for b in self { - res.push(match b { - ty::BoundSend => "Send".to_string(), - ty::BoundSized => "Sized".to_string(), - ty::BoundCopy => "Copy".to_string(), - ty::BoundSync => "Sync".to_string(), - }); + +impl<'tcx> fmt::Debug for ty::ParamBounds<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + try!(write!(f, "{:?}", self.builtin_bounds)); + let mut bounds = self.trait_bounds.iter(); + if self.builtin_bounds.is_empty() { + if let Some(bound) = bounds.next() { + try!(write!(f, "{:?}", bound)); + } } - res.connect("+") + for bound in bounds { + try!(write!(f, " + {:?}", bound)); + } + Ok(()) } } -impl<'tcx> Repr for ty::ParamBounds<'tcx> { - fn repr(&self) -> String { - let mut res = Vec::new(); - res.push(self.builtin_bounds.repr()); - for t in &self.trait_bounds { - res.push(t.repr()); - } - res.connect("+") - } -} - -impl<'tcx> Repr for ty::TraitRef<'tcx> { - fn repr(&self) -> String { +impl<'tcx> fmt::Debug for ty::TraitRef<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // when printing out the debug representation, we don't need // to enumerate the `for<...>` etc because the debruijn index // tells you everything you need to know. - let result = self.user_string(); match self.substs.self_ty() { - None => result, - Some(sty) => format!("<{} as {}>", sty.repr(), result) + None => write!(f, "{}", *self), + Some(self_ty) => write!(f, "<{:?} as {}>", self_ty, *self) } } } -impl<'tcx> Repr for ty::TraitDef<'tcx> { - fn repr(&self) -> String { - format!("TraitDef(generics={}, trait_ref={})", - self.generics.repr(), - self.trait_ref.repr()) +impl<'tcx> fmt::Debug for ty::TraitDef<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "TraitDef(generics={:?}, trait_ref={:?})", + self.generics, self.trait_ref) } } -impl Repr for ast::Expr { - fn repr(&self) -> String { - format!("{:?}", *self) - } -} - -impl Repr for ast::Path { - fn repr(&self) -> String { - format!("{:?}", *self) - } -} - -impl UserString for ast::Path { - fn user_string(&self) -> String { - format!("{}", *self) - } -} - -impl Repr for ast::Ty { - fn repr(&self) -> String { - format!("{:?}", *self) - } -} - -impl Repr for ast::Lifetime { - fn repr(&self) -> String { - format!("{:?}", *self) - } -} - -impl Repr for ast::Stmt { - fn repr(&self) -> String { - format!("{:?}", *self) - } -} - -impl Repr for ast::Pat { - fn repr(&self) -> String { - format!("{:?}", *self) - } -} - -impl Repr for ty::BoundRegion { - fn repr(&self) -> String { - match *self { - ty::BrAnon(id) => format!("BrAnon({})", id), - ty::BrNamed(id, name) => { - format!("BrNamed({}, {})", id.repr(), token::get_name(name)) - } - ty::BrFresh(id) => format!("BrFresh({})", id), - ty::BrEnv => "BrEnv".to_string() - } - } -} - -impl UserString for ty::BoundRegion { - fn user_string(&self) -> String { +impl fmt::Display for ty::BoundRegion { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if verbose() { - return self.repr(); + return write!(f, "{:?}", *self); } match *self { - BrNamed(_, name) => token::get_name(name).to_string(), - BrAnon(_) | BrFresh(_) | BrEnv => String::new() + BrNamed(_, name) => write!(f, "{}", name), + BrAnon(_) | BrFresh(_) | BrEnv => Ok(()) } } } -impl Repr for ty::Region { - fn repr(&self) -> String { +impl fmt::Debug for ty::Region { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ty::ReEarlyBound(ref data) => { - format!("ReEarlyBound({}, {:?}, {}, {})", - data.param_id, - data.space, - data.index, - token::get_name(data.name)) + write!(f, "ReEarlyBound({}, {:?}, {}, {})", + data.param_id, + data.space, + data.index, + data.name) } ty::ReLateBound(binder_id, ref bound_region) => { - format!("ReLateBound({:?}, {})", - binder_id, - bound_region.repr()) + write!(f, "ReLateBound({:?}, {:?})", + binder_id, + bound_region) } - ty::ReFree(ref fr) => fr.repr(), + ty::ReFree(ref fr) => write!(f, "{:?}", fr), ty::ReScope(id) => { - format!("ReScope({:?})", id) + write!(f, "ReScope({:?})", id) } - ty::ReStatic => { - "ReStatic".to_string() - } + ty::ReStatic => write!(f, "ReStatic"), ty::ReInfer(ReVar(ref vid)) => { - format!("{:?}", vid) + write!(f, "{:?}", vid) } ty::ReInfer(ReSkolemized(id, ref bound_region)) => { - format!("re_skolemized({}, {})", id, bound_region.repr()) + write!(f, "ReSkolemized({}, {:?})", id, bound_region) } - ty::ReEmpty => { - "ReEmpty".to_string() - } + ty::ReEmpty => write!(f, "ReEmpty") } } } -impl UserString for ty::Region { - fn user_string(&self) -> String { +impl fmt::Display for ty::Region { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if verbose() { - return self.repr(); + return write!(f, "{:?}", *self); } // These printouts are concise. They do not contain all the information @@ -587,672 +468,344 @@ impl UserString for ty::Region { // `explain_region()` or `note_and_explain_region()`. match *self { ty::ReEarlyBound(ref data) => { - token::get_name(data.name).to_string() + write!(f, "{}", data.name) } ty::ReLateBound(_, br) | ty::ReFree(ty::FreeRegion { bound_region: br, .. }) | ty::ReInfer(ReSkolemized(_, br)) => { - br.user_string() + write!(f, "{}", br) } ty::ReScope(_) | - ty::ReInfer(ReVar(_)) => String::new(), - ty::ReStatic => "'static".to_owned(), - ty::ReEmpty => "'".to_owned(), + ty::ReInfer(ReVar(_)) => Ok(()), + ty::ReStatic => write!(f, "'static"), + ty::ReEmpty => write!(f, "'"), } } } -impl Repr for ty::FreeRegion { - fn repr(&self) -> String { - format!("ReFree({}, {})", - self.scope.repr(), - self.bound_region.repr()) +impl fmt::Debug for ty::FreeRegion { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "ReFree({:?}, {:?})", + self.scope, self.bound_region) } } -impl Repr for region::CodeExtent { - fn repr(&self) -> String { +impl fmt::Debug for ty::ItemVariances { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "ItemVariances(types={:?}, regions={:?})", + self.types, self.regions) + } +} + +impl<'tcx> fmt::Debug for ty::GenericPredicates<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "GenericPredicates({:?})", self.predicates) + } +} + +impl<'tcx> fmt::Debug for ty::InstantiatedPredicates<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "InstantiatedPredicates({:?})", + self.predicates) + } +} + +impl<'tcx> fmt::Debug for ty::ImplOrTraitItem<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + try!(write!(f, "ImplOrTraitItem(")); + try!(match *self { + ty::ImplOrTraitItem::MethodTraitItem(ref i) => write!(f, "{:?}", i), + ty::ImplOrTraitItem::ConstTraitItem(ref i) => write!(f, "{:?}", i), + ty::ImplOrTraitItem::TypeTraitItem(ref i) => write!(f, "{:?}", i), + }); + write!(f, ")") + } +} + +impl<'tcx> fmt::Display for ty::FnSig<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + try!(write!(f, "fn")); + fn_sig(f, &self.inputs, self.variadic, self.output) + } +} + +impl<'tcx> fmt::Debug for ty::MethodOrigin<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - region::CodeExtent::ParameterScope { fn_id, body_id } => - format!("ParameterScope({}, {})", fn_id, body_id), - region::CodeExtent::Misc(node_id) => - format!("Misc({})", node_id), - region::CodeExtent::DestructionScope(node_id) => - format!("DestructionScope({})", node_id), - region::CodeExtent::Remainder(rem) => - format!("Remainder({}, {})", rem.block, rem.first_statement_index), + ty::MethodStatic(def_id) => { + write!(f, "MethodStatic({:?})", def_id) + } + ty::MethodStaticClosure(def_id) => { + write!(f, "MethodStaticClosure({:?})", def_id) + } + ty::MethodTypeParam(ref p) => write!(f, "{:?}", p), + ty::MethodTraitObject(ref p) => write!(f, "{:?}", p) } } } -impl Repr for region::DestructionScopeData { - fn repr(&self) -> String { - match *self { - region::DestructionScopeData{ node_id } => - format!("DestructionScopeData {{ node_id: {} }}", node_id), - } +impl<'tcx> fmt::Debug for ty::MethodParam<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "MethodParam({:?},{})", + self.trait_ref, + self.method_num) } } -impl Repr for ast::DefId { - fn repr(&self) -> String { - format!("{:?}", *self) +impl<'tcx> fmt::Debug for ty::MethodObject<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "MethodObject({:?},{},{})", + self.trait_ref, + self.method_num, + self.vtable_index) } } -impl<'tcx> Repr for ty::TypeScheme<'tcx> { - fn repr(&self) -> String { - format!("TypeScheme {{generics: {}, ty: {}}}", - self.generics.repr(), - self.ty.repr()) - } -} - -impl<'tcx> Repr for ty::Generics<'tcx> { - fn repr(&self) -> String { - format!("Generics(types: {}, regions: {})", - self.types.repr(), - self.regions.repr()) - } -} - -impl<'tcx> Repr for ty::GenericPredicates<'tcx> { - fn repr(&self) -> String { - format!("GenericPredicates(predicates: {})", - self.predicates.repr()) - } -} - -impl<'tcx> Repr for ty::InstantiatedPredicates<'tcx> { - fn repr(&self) -> String { - format!("InstantiatedPredicates({})", - self.predicates.repr()) - } -} - -impl Repr for ty::ItemVariances { - fn repr(&self) -> String { - format!("ItemVariances(types={}, \ - regions={})", - self.types.repr(), - self.regions.repr()) - } -} - -impl Repr for ty::Variance { - fn repr(&self) -> String { - // The first `.to_string()` returns a &'static str (it is not an implementation - // of the ToString trait). Because of that, we need to call `.to_string()` again - // if we want to have a `String`. - let result: &'static str = (*self).to_string(); - result.to_string() - } -} - -impl<'tcx> Repr for ty::ImplOrTraitItem<'tcx> { - fn repr(&self) -> String { - format!("ImplOrTraitItem({})", - match *self { - ty::ImplOrTraitItem::MethodTraitItem(ref i) => i.repr(), - ty::ImplOrTraitItem::ConstTraitItem(ref i) => i.repr(), - ty::ImplOrTraitItem::TypeTraitItem(ref i) => i.repr(), - }) - } -} - -impl<'tcx> Repr for ty::AssociatedConst<'tcx> { - fn repr(&self) -> String { - format!("AssociatedConst(name: {}, ty: {}, vis: {}, def_id: {})", - self.name.repr(), - self.ty.repr(), - self.vis.repr(), - self.def_id.repr()) - } -} - -impl<'tcx> Repr for ty::AssociatedType<'tcx> { - fn repr(&self) -> String { - format!("AssociatedType(name: {}, vis: {}, def_id: {})", - self.name.repr(), - self.vis.repr(), - self.def_id.repr()) - } -} - -impl<'tcx> Repr for ty::Method<'tcx> { - fn repr(&self) -> String { - format!("Method(name: {}, generics: {}, predicates: {}, fty: {}, \ - explicit_self: {}, vis: {}, def_id: {})", - self.name.repr(), - self.generics.repr(), - self.predicates.repr(), - self.fty.repr(), - self.explicit_self.repr(), - self.vis.repr(), - self.def_id.repr()) - } -} - -impl Repr for ast::Name { - fn repr(&self) -> String { - format!("{:?}", *self) - } -} - -impl UserString for ast::Name { - fn user_string(&self) -> String { - format!("{}", *self) - } -} - -impl Repr for ast::ExplicitSelf_ { - fn repr(&self) -> String { - format!("{:?}", *self) - } -} - -impl Repr for ast::Visibility { - fn repr(&self) -> String { - format!("{:?}", *self) - } -} - -impl<'tcx> Repr for ty::BareFnTy<'tcx> { - fn repr(&self) -> String { - format!("BareFnTy {{unsafety: {}, abi: {}, sig: {}}}", - self.unsafety, - self.abi.to_string(), - self.sig.repr()) - } -} - - -impl<'tcx> Repr for ty::FnSig<'tcx> { - fn repr(&self) -> String { - format!("fn{} -> {}", self.inputs.repr(), self.output.repr()) - } -} - -impl<'tcx> Repr for ty::FnOutput<'tcx> { - fn repr(&self) -> String { - match *self { - ty::FnConverging(ty) => - format!("FnConverging({0})", ty.repr()), - ty::FnDiverging => - "FnDiverging".to_string() - } - } -} - -impl<'tcx> Repr for ty::MethodCallee<'tcx> { - fn repr(&self) -> String { - format!("MethodCallee {{origin: {}, ty: {}, {}}}", - self.origin.repr(), - self.ty.repr(), - self.substs.repr()) - } -} - -impl<'tcx> Repr for ty::MethodOrigin<'tcx> { - fn repr(&self) -> String { - match self { - &ty::MethodStatic(def_id) => { - format!("MethodStatic({})", def_id.repr()) - } - &ty::MethodStaticClosure(def_id) => { - format!("MethodStaticClosure({})", def_id.repr()) - } - &ty::MethodTypeParam(ref p) => { - p.repr() - } - &ty::MethodTraitObject(ref p) => { - p.repr() +impl<'tcx> fmt::Display for ty::ParamBounds<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + try!(write!(f, "{}", self.builtin_bounds)); + let mut bounds = self.trait_bounds.iter(); + if self.builtin_bounds.is_empty() { + if let Some(bound) = bounds.next() { + try!(write!(f, "{}", bound)); } } - } -} - -impl<'tcx> Repr for ty::MethodParam<'tcx> { - fn repr(&self) -> String { - format!("MethodParam({},{})", - self.trait_ref.repr(), - self.method_num) - } -} - -impl<'tcx> Repr for ty::MethodObject<'tcx> { - fn repr(&self) -> String { - format!("MethodObject({},{},{})", - self.trait_ref.repr(), - self.method_num, - self.vtable_index) - } -} - -impl Repr for ty::BuiltinBound { - fn repr(&self) -> String { - format!("{:?}", *self) - } -} - -impl UserString for ty::BuiltinBound { - fn user_string(&self) -> String { - match *self { - ty::BoundSend => "Send".to_string(), - ty::BoundSized => "Sized".to_string(), - ty::BoundCopy => "Copy".to_string(), - ty::BoundSync => "Sync".to_string(), + for bound in bounds { + try!(write!(f, " + {}", bound)); } + Ok(()) } } -impl Repr for Span { - fn repr(&self) -> String { - format!("{:?}", *self) - } -} - -impl UserString for Rc { - fn user_string(&self) -> String { - let this: &A = &**self; - this.user_string() - } -} - -impl<'tcx> UserString for ty::ParamBounds<'tcx> { - fn user_string(&self) -> String { - let mut result = Vec::new(); - let s = self.builtin_bounds.user_string(); - if !s.is_empty() { - result.push(s); - } - for n in &self.trait_bounds { - result.push(n.user_string()); - } - result.connect(" + ") - } -} - -impl<'tcx> Repr for ty::ExistentialBounds<'tcx> { - fn repr(&self) -> String { - let mut res = Vec::new(); +impl<'tcx> fmt::Debug for ty::ExistentialBounds<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut empty = true; + let mut maybe_continue = |f: &mut fmt::Formatter| { + if empty { + empty = false; + Ok(()) + } else { + write!(f, " + ") + } + }; let region_str = self.region_bound.repr(); if !region_str.is_empty() { - res.push(region_str); + try!(maybe_continue(f)); + try!(write!(f, "{}", region_str)); } for bound in &self.builtin_bounds { - res.push(bound.repr()); + try!(maybe_continue(f)); + try!(write!(f, "{:?}", bound)); } for projection_bound in &self.projection_bounds { - res.push(projection_bound.repr()); + try!(maybe_continue(f)); + try!(write!(f, "{:?}", projection_bound)); } - res.connect("+") + Ok(()) } } -impl UserString for ty::BuiltinBounds { - fn user_string(&self) -> String { - self.iter() - .map(|bb| bb.user_string()) - .collect::>() - .connect("+") - .to_string() +impl fmt::Display for ty::BuiltinBounds { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut bounds = self.iter(); + if let Some(bound) = bounds.next() { + try!(write!(f, "{:?}", bound)); + for bound in bounds { + try!(write!(f, " + {:?}", bound)); + } + } + Ok(()) } } // The generic impl doesn't work yet because projections are not // normalized under HRTB. -/*impl UserString for ty::Binder - where T: UserString + for<'a> ty::Lift<'a>, - for<'a> >::Lifted: UserString + TypeFoldable<'a> +/*impl fmt::Display for ty::Binder + where T: fmt::Display + for<'a> ty::Lift<'a>, + for<'a> >::Lifted: fmt::Display + TypeFoldable<'a> { - fn user_string(&self) -> String { - ty::tls::with(|tcx| in_binder(tcx, self, tcx.lift(self))) + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self))) } }*/ -impl<'tcx> UserString for ty::Binder> { - fn user_string(&self) -> String { - ty::tls::with(|tcx| in_binder(tcx, self, tcx.lift(self))) +impl<'tcx> fmt::Display for ty::Binder> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self))) } } -impl<'tcx> UserString for ty::Binder> { - fn user_string(&self) -> String { - ty::tls::with(|tcx| in_binder(tcx, self, tcx.lift(self))) +impl<'tcx> fmt::Display for ty::Binder> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self))) } } -impl<'tcx> UserString for ty::Binder> { - fn user_string(&self) -> String { - ty::tls::with(|tcx| in_binder(tcx, self, tcx.lift(self))) +impl<'tcx> fmt::Display for ty::Binder> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self))) } } -impl<'tcx> UserString for ty::Binder> { - fn user_string(&self) -> String { - ty::tls::with(|tcx| in_binder(tcx, self, tcx.lift(self))) +impl<'tcx> fmt::Display for ty::Binder> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self))) } } -impl<'tcx> UserString for ty::Binder> { - fn user_string(&self) -> String { - ty::tls::with(|tcx| in_binder(tcx, self, tcx.lift(self))) +impl<'tcx> fmt::Display for ty::Binder, ty::Region>> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self))) } } -impl<'tcx> UserString for ty::Binder, ty::Region>> { - fn user_string(&self) -> String { - ty::tls::with(|tcx| in_binder(tcx, self, tcx.lift(self))) +impl fmt::Display for ty::Binder> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + ty::tls::with(|tcx| in_binder(f, tcx, self, tcx.lift(self))) } } -impl UserString for ty::Binder> { - fn user_string(&self) -> String { - ty::tls::with(|tcx| in_binder(tcx, self, tcx.lift(self))) - } -} - -impl<'tcx> UserString for ty::TraitRef<'tcx> { - fn user_string(&self) -> String { - parameterized(self.substs, self.def_id, &[], +impl<'tcx> fmt::Display for ty::TraitRef<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + parameterized(f, self.substs, self.def_id, &[], |tcx| ty::lookup_trait_def(tcx, self.def_id).generics.clone()) } } -impl<'tcx> UserString for ty::TyS<'tcx> { - fn user_string(&self) -> String { - fn bare_fn_to_string(opt_def_id: Option, - unsafety: ast::Unsafety, - abi: abi::Abi, - ident: Option, - sig: &ty::PolyFnSig) - -> String { - let mut s = String::new(); - - match unsafety { - ast::Unsafety::Normal => {} - ast::Unsafety::Unsafe => { - s.push_str(&unsafety.to_string()); - s.push(' '); - } - }; - - if abi != abi::Rust { - s.push_str(&format!("extern {} ", abi.to_string())); - }; - - s.push_str("fn"); - - match ident { - Some(i) => { - s.push(' '); - s.push_str(&token::get_ident(i)); - } - _ => { } - } - - push_sig_to_string(&mut s, '(', ')', sig); - - match opt_def_id { - Some(def_id) => { - s.push_str(" {"); - let path_str = ty::tls::with(|tcx| ty::item_path_str(tcx, def_id)); - s.push_str(&path_str[..]); - s.push_str("}"); - } - None => { } - } - - s - } - - fn push_sig_to_string(s: &mut String, - bra: char, - ket: char, - sig: &ty::PolyFnSig) { - s.push(bra); - let strs = sig.0.inputs - .iter() - .map(|a| a.user_string()) - .collect::>(); - s.push_str(&strs.connect(", ")); - if sig.0.variadic { - s.push_str(", ..."); - } - s.push(ket); - - match sig.0.output { - ty::FnConverging(t) => { - if !ty::type_is_nil(t) { - s.push_str(" -> "); - s.push_str(&t.user_string()); - } - } - ty::FnDiverging => { - s.push_str(" -> !"); - } - } - } - - // pretty print the structural type representation: - match self.sty { - TyBool => "bool".to_string(), - TyChar => "char".to_string(), - TyInt(t) => ast_util::int_ty_to_string(t, None).to_string(), - TyUint(t) => ast_util::uint_ty_to_string(t, None).to_string(), - TyFloat(t) => ast_util::float_ty_to_string(t).to_string(), - TyBox(typ) => format!("Box<{}>", typ.user_string()), +impl<'tcx> fmt::Display for ty::TypeVariants<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + TyBool => write!(f, "bool"), + TyChar => write!(f, "char"), + TyInt(t) => write!(f, "{}", ast_util::int_ty_to_string(t, None)), + TyUint(t) => write!(f, "{}", ast_util::uint_ty_to_string(t, None)), + TyFloat(t) => write!(f, "{}", ast_util::float_ty_to_string(t)), + TyBox(typ) => write!(f, "Box<{}>", typ), TyRawPtr(ref tm) => { - format!("*{} {}", match tm.mutbl { + write!(f, "*{} {}", match tm.mutbl { ast::MutMutable => "mut", ast::MutImmutable => "const", - }, tm.ty.user_string()) + }, tm.ty) } TyRef(r, ref tm) => { - let mut buf = "&".to_owned(); - buf.push_str(&r.user_string()); - if buf.len() > 1 { - buf.push_str(" "); + try!(write!(f, "&")); + let s = r.user_string(); + try!(write!(f, "{}", s)); + if !s.is_empty() { + try!(write!(f, " ")); } - buf.push_str(&tm.repr()); - buf + write!(f, "{}", tm) } - TyTuple(ref elems) => { - let strs = elems - .iter() - .map(|elem| elem.user_string()) - .collect::>(); - match &strs[..] { - [ref string] => format!("({},)", string), - strs => format!("({})", strs.connect(", ")) + TyTuple(ref tys) => { + try!(write!(f, "(")); + let mut tys = tys.iter(); + if let Some(&ty) = tys.next() { + try!(write!(f, "{},", ty)); + if let Some(&ty) = tys.next() { + try!(write!(f, " {}", ty)); + for &ty in tys { + try!(write!(f, ", {}", ty)); + } + } } + write!(f, ")") } - TyBareFn(opt_def_id, ref f) => { - bare_fn_to_string(opt_def_id, f.unsafety, f.abi, None, &f.sig) + TyBareFn(opt_def_id, ref bare_fn) => { + if bare_fn.unsafety == ast::Unsafety::Unsafe { + try!(write!(f, "unsafe ")); + } + + if bare_fn.abi != abi::Rust { + try!(write!(f, "extern {} ", bare_fn.abi)); + } + + try!(write!(f, "{}", bare_fn.sig.0)); + + if let Some(def_id) = opt_def_id { + try!(write!(f, " {{{}}}", ty::tls::with(|tcx| { + ty::item_path_str(tcx, def_id) + }))); + } + Ok(()) } - TyInfer(infer_ty) => infer_ty.repr(), - TyError => "[type error]".to_string(), - TyParam(ref param_ty) => param_ty.user_string(), + TyInfer(infer_ty) => write!(f, "{}", infer_ty), + TyError => write!(f, "[type error]"), + TyParam(ref param_ty) => write!(f, "{}", param_ty), TyEnum(did, substs) | TyStruct(did, substs) => { - parameterized(substs, did, &[], + parameterized(f, substs, did, &[], |tcx| ty::lookup_item_type(tcx, did).generics) } - TyTrait(ref data) => { - data.user_string() - } - ty::TyProjection(ref data) => { - format!("<{} as {}>::{}", - data.trait_ref.self_ty().user_string(), - data.trait_ref.user_string(), - data.item_name.user_string()) - } - TyStr => "str".to_string(), + TyTrait(ref data) => write!(f, "{}", data), + ty::TyProjection(ref data) => write!(f, "{}", data), + TyStr => write!(f, "str"), TyClosure(ref did, substs) => ty::tls::with(|tcx| { + try!(write!(f, "[closure")); let closure_tys = tcx.closure_tys.borrow(); - closure_tys.get(did).map(|cty| &cty.sig).and_then(|sig| { + try!(closure_tys.get(did).map(|cty| &cty.sig).and_then(|sig| { tcx.lift(&substs).map(|substs| sig.subst(tcx, substs)) }).map(|sig| { - let mut s = String::new(); - s.push_str("[closure"); - push_sig_to_string(&mut s, '(', ')', &sig); - if verbose() { - s.push_str(&format!(" id={:?}]", did)); - } else { - s.push(']'); - } - s + fn_sig(f, &sig.0.inputs, false, sig.0.output) }).unwrap_or_else(|| { - let id_str = if verbose() { - format!(" id={:?}", did) - } else { - "".to_owned() - }; - if did.krate == ast::LOCAL_CRATE { - let span = ty::tls::with(|tcx| tcx.map.span(did.node)); - format!("[closure {}{}]", span.repr(), id_str) - } else { - format!("[closure{}]", id_str) + try!(write!(f, " {:?}", tcx.map.span(did.node))); } - }) + Ok(()) + })); + if verbose() { + try!(write!(f, " id={:?}", did)); + } + write!(f, "]") }), - TyArray(t, sz) => { - format!("[{}; {}]", t.user_string(), sz) - } - TySlice(t) => { - format!("[{}]", t.user_string()) - } + TyArray(ty, sz) => write!(f, "[{}; {}]", ty, sz), + TySlice(ty) => write!(f, "[{}]", ty) } } } -impl UserString for ast::Ident { - fn user_string(&self) -> String { - format!("{}", *self) +impl<'tcx> fmt::Display for ty::TyS<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.sty) } } -impl Repr for abi::Abi { - fn repr(&self) -> String { - self.to_string() +impl fmt::Debug for ty::UpvarId { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "UpvarId({};`{}`;{})", + self.var_id, + ty::tls::with(|tcx| ty::local_var_name_str(tcx, self.var_id)), + self.closure_expr_id) } } -impl UserString for abi::Abi { - fn user_string(&self) -> String { - self.to_string() +impl fmt::Debug for ty::UpvarBorrow { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "UpvarBorrow({:?}, {:?})", + self.kind, self.region) } } -impl Repr for ty::UpvarId { - fn repr(&self) -> String { - format!("UpvarId({};`{}`;{})", - self.var_id, - ty::tls::with(|tcx| ty::local_var_name_str(tcx, self.var_id)), - self.closure_expr_id) - } -} - -impl Repr for ast::Mutability { - fn repr(&self) -> String { - format!("{:?}", *self) - } -} - -impl Repr for ty::BorrowKind { - fn repr(&self) -> String { - format!("{:?}", *self) - } -} - -impl Repr for ty::UpvarBorrow { - fn repr(&self) -> String { - format!("UpvarBorrow({}, {})", - self.kind.repr(), - self.region.repr()) - } -} - -impl Repr for ty::UpvarCapture { - fn repr(&self) -> String { - match *self { - ty::UpvarCapture::ByValue => format!("ByValue"), - ty::UpvarCapture::ByRef(ref data) => format!("ByRef({})", data.repr()), - } - } -} - -impl Repr for ty::IntVid { - fn repr(&self) -> String { - format!("{:?}", self) - } -} - -impl Repr for ty::FloatVid { - fn repr(&self) -> String { - format!("{:?}", self) - } -} - -impl Repr for ty::RegionVid { - fn repr(&self) -> String { - format!("{:?}", self) - } -} - -impl Repr for ty::TyVid { - fn repr(&self) -> String { - format!("{:?}", self) - } -} - -impl Repr for ty::IntVarValue { - fn repr(&self) -> String { - format!("{:?}", *self) - } -} - -impl Repr for ty::InferTy { - fn repr(&self) -> String { +impl fmt::Display for ty::InferTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let print_var_ids = verbose(); match *self { - ty::TyVar(ref vid) if print_var_ids => vid.repr(), - ty::IntVar(ref vid) if print_var_ids => vid.repr(), - ty::FloatVar(ref vid) if print_var_ids => vid.repr(), - ty::TyVar(_) | ty::IntVar(_) | ty::FloatVar(_) => format!("_"), - ty::FreshTy(v) => format!("FreshTy({})", v), - ty::FreshIntTy(v) => format!("FreshIntTy({})", v), - ty::FreshFloatTy(v) => format!("FreshFloatTy({})", v) + ty::TyVar(ref vid) if print_var_ids => write!(f, "{:?}", vid), + ty::IntVar(ref vid) if print_var_ids => write!(f, "{:?}", vid), + ty::FloatVar(ref vid) if print_var_ids => write!(f, "{:?}", vid), + ty::TyVar(_) | ty::IntVar(_) | ty::FloatVar(_) => write!(f, "_"), + ty::FreshTy(v) => write!(f, "FreshTy({})", v), + ty::FreshIntTy(v) => write!(f, "FreshIntTy({})", v), + ty::FreshFloatTy(v) => write!(f, "FreshFloatTy({})", v) } } } -impl Repr for ast::IntTy { - fn repr(&self) -> String { - format!("{:?}", *self) - } -} - -impl Repr for ast::UintTy { - fn repr(&self) -> String { - format!("{:?}", *self) - } -} - -impl Repr for ast::FloatTy { - fn repr(&self) -> String { - format!("{:?}", *self) - } -} - -impl Repr for ty::ExplicitSelfCategory { - fn repr(&self) -> String { - match *self { +impl fmt::Display for ty::ExplicitSelfCategory { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str(match *self { ty::StaticExplicitSelfCategory => "static", ty::ByValueExplicitSelfCategory => "self", ty::ByReferenceExplicitSelfCategory(_, ast::MutMutable) => { @@ -1260,142 +813,83 @@ impl Repr for ty::ExplicitSelfCategory { } ty::ByReferenceExplicitSelfCategory(_, ast::MutImmutable) => "&self", ty::ByBoxExplicitSelfCategory => "Box", - }.to_owned() + }) } } -impl UserString for ParamTy { - fn user_string(&self) -> String { - format!("{}", token::get_name(self.name)) +impl fmt::Display for ty::ParamTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.name) } } -impl Repr for ParamTy { - fn repr(&self) -> String { - let ident = self.user_string(); - format!("{}/{:?}.{}", ident, self.space, self.idx) +impl fmt::Debug for ty::ParamTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}/{:?}.{}", self, self.space, self.idx) } } -impl Repr for (A,B) { - fn repr(&self) -> String { - let &(ref a, ref b) = self; - format!("({},{})", a.repr(), b.repr()) - } -} - -impl Repr for ty::Binder { - fn repr(&self) -> String { - format!("Binder({})", self.0.repr()) - } -} - -impl Repr for HashMap - where K: Hash + Eq + Repr, - V: Repr, - S: HashState, +impl<'tcx, T, U> fmt::Display for ty::OutlivesPredicate + where T: fmt::Display, U: fmt::Display { - fn repr(&self) -> String { - format!("HashMap({})", - self.iter() - .map(|(k,v)| format!("{} => {}", k.repr(), v.repr())) - .collect::>() - .connect(", ")) + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{} : {}", self.0, self.1) } } -impl<'tcx, T, U> Repr for ty::OutlivesPredicate - where T : Repr + TypeFoldable<'tcx>, - U : Repr + TypeFoldable<'tcx>, -{ - fn repr(&self) -> String { - format!("OutlivesPredicate({}, {})", - self.0.repr(), - self.1.repr()) +impl<'tcx> fmt::Display for ty::EquatePredicate<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{} == {}", self.0, self.1) } } -impl<'tcx, T, U> UserString for ty::OutlivesPredicate - where T : UserString + TypeFoldable<'tcx>, - U : UserString + TypeFoldable<'tcx>, -{ - fn user_string(&self) -> String { - format!("{} : {}", - self.0.user_string(), - self.1.user_string()) +impl<'tcx> fmt::Debug for ty::TraitPredicate<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "TraitPredicate({:?})", + self.trait_ref) } } -impl<'tcx> Repr for ty::EquatePredicate<'tcx> { - fn repr(&self) -> String { - format!("EquatePredicate({}, {})", - self.0.repr(), - self.1.repr()) +impl<'tcx> fmt::Display for ty::TraitPredicate<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{} : {}", + self.trait_ref.self_ty(), + self.trait_ref) } } -impl<'tcx> UserString for ty::EquatePredicate<'tcx> { - fn user_string(&self) -> String { - format!("{} == {}", - self.0.user_string(), - self.1.user_string()) +impl<'tcx> fmt::Debug for ty::ProjectionPredicate<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "ProjectionPredicate({:?}, {:?})", + self.projection_ty, + self.ty) } } -impl<'tcx> Repr for ty::TraitPredicate<'tcx> { - fn repr(&self) -> String { - format!("TraitPredicate({})", - self.trait_ref.repr()) +impl<'tcx> fmt::Display for ty::ProjectionPredicate<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{} == {}", + self.projection_ty, + self.ty) } } -impl<'tcx> UserString for ty::TraitPredicate<'tcx> { - fn user_string(&self) -> String { - format!("{} : {}", - self.trait_ref.self_ty().user_string(), - self.trait_ref.user_string()) +impl<'tcx> fmt::Display for ty::ProjectionTy<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{:?}::{}", + self.trait_ref, + self.item_name) } } -impl<'tcx> UserString for ty::ProjectionPredicate<'tcx> { - fn user_string(&self) -> String { - format!("{} == {}", - self.projection_ty.user_string(), - self.ty.user_string()) - } -} - -impl<'tcx> Repr for ty::ProjectionTy<'tcx> { - fn repr(&self) -> String { - format!("{}::{}", - self.trait_ref.repr(), - self.item_name.repr()) - } -} - -impl<'tcx> UserString for ty::ProjectionTy<'tcx> { - fn user_string(&self) -> String { - format!("<{} as {}>::{}", - self.trait_ref.self_ty().user_string(), - self.trait_ref.user_string(), - self.item_name.user_string()) - } -} - -impl<'tcx> UserString for ty::Predicate<'tcx> { - fn user_string(&self) -> String { +impl<'tcx> fmt::Display for ty::Predicate<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - ty::Predicate::Trait(ref data) => data.user_string(), - ty::Predicate::Equate(ref predicate) => predicate.user_string(), - ty::Predicate::RegionOutlives(ref predicate) => predicate.user_string(), - ty::Predicate::TypeOutlives(ref predicate) => predicate.user_string(), - ty::Predicate::Projection(ref predicate) => predicate.user_string(), + ty::Predicate::Trait(ref data) => write!(f, "{}", data), + ty::Predicate::Equate(ref predicate) => write!(f, "{}", predicate), + ty::Predicate::RegionOutlives(ref predicate) => write!(f, "{}", predicate), + ty::Predicate::TypeOutlives(ref predicate) => write!(f, "{}", predicate), + ty::Predicate::Projection(ref predicate) => write!(f, "{}", predicate), } } } - -impl Repr for ast::Unsafety { - fn repr(&self) -> String { - format!("{:?}", *self) - } -} diff --git a/src/librustc_borrowck/borrowck/mod.rs b/src/librustc_borrowck/borrowck/mod.rs index 93b16795fe8d..63d9383d69d5 100644 --- a/src/librustc_borrowck/borrowck/mod.rs +++ b/src/librustc_borrowck/borrowck/mod.rs @@ -34,9 +34,10 @@ use rustc::middle::mem_categorization as mc; use rustc::middle::region; use rustc::middle::ty::{self, Ty}; use rustc::util::ppaux::{Repr, UserString}; + +use std::fmt; use std::mem; use std::rc::Rc; -use std::string::String; use syntax::ast; use syntax::ast_util; use syntax::codemap::Span; @@ -329,7 +330,7 @@ impl<'tcx> Loan<'tcx> { } } -#[derive(Eq, Hash, Debug)] +#[derive(Eq, Hash)] pub struct LoanPath<'tcx> { kind: LoanPathKind<'tcx>, ty: ty::Ty<'tcx>, @@ -369,7 +370,7 @@ const DOWNCAST_PRINTED_OPERATOR: &'static str = " as "; // information that is not relevant to loan-path analysis. (In // particular, the distinction between how precisely a array-element // is tracked is irrelevant here.) -#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Copy, PartialEq, Eq, Hash)] pub enum InteriorKind { InteriorField(mc::FieldName), InteriorElement(mc::ElementKind), @@ -1148,39 +1149,38 @@ impl DataFlowOperator for LoanDataFlowOperator { } } -impl<'tcx> Repr for InteriorKind { - fn repr(&self) -> String { +impl<'tcx> fmt::Debug for InteriorKind { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - InteriorField(mc::NamedField(fld)) => - format!("{}", token::get_name(fld)), - InteriorField(mc::PositionalField(i)) => format!("#{}", i), - InteriorElement(..) => "[]".to_string(), + InteriorField(mc::NamedField(fld)) => write!(f, "{}", fld), + InteriorField(mc::PositionalField(i)) => write!(f, "#{}", i), + InteriorElement(..) => write!(f, "[]"), } } } -impl<'tcx> Repr for Loan<'tcx> { - fn repr(&self) -> String { - format!("Loan_{}({}, {:?}, {:?}-{:?}, {})", - self.index, - self.loan_path.repr(), - self.kind, - self.gen_scope, - self.kill_scope, - self.restricted_paths.repr()) +impl<'tcx> fmt::Debug for Loan<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Loan_{}({:?}, {:?}, {:?}-{:?}, {:?})", + self.index, + self.loan_path, + self.kind, + self.gen_scope, + self.kill_scope, + self.restricted_paths) } } -impl<'tcx> Repr for LoanPath<'tcx> { - fn repr(&self) -> String { +impl<'tcx> fmt::Debug for LoanPath<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.kind { LpVar(id) => { - format!("$({})", ty::tls::with(|tcx| tcx.map.node_to_string(id))) + write!(f, "$({})", ty::tls::with(|tcx| tcx.map.node_to_string(id))) } LpUpvar(ty::UpvarId{ var_id, closure_expr_id }) => { let s = ty::tls::with(|tcx| tcx.map.node_to_string(var_id)); - format!("$({} captured by id={})", s, closure_expr_id) + write!(f, "$({} captured by id={})", s, closure_expr_id) } LpDowncast(ref lp, variant_def_id) => { @@ -1189,30 +1189,30 @@ impl<'tcx> Repr for LoanPath<'tcx> { } else { variant_def_id.repr() }; - format!("({}{}{})", lp.repr(), DOWNCAST_PRINTED_OPERATOR, variant_str) + write!(f, "({:?}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str) } LpExtend(ref lp, _, LpDeref(_)) => { - format!("{}.*", lp.repr()) + write!(f, "{:?}.*", lp) } LpExtend(ref lp, _, LpInterior(ref interior)) => { - format!("{}.{}", lp.repr(), interior.repr()) + write!(f, "{:?}.{:?}", lp, interior) } } } } -impl<'tcx> UserString for LoanPath<'tcx> { - fn user_string(&self) -> String { +impl<'tcx> fmt::Display for LoanPath<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.kind { LpVar(id) => { - format!("$({})", ty::tls::with(|tcx| tcx.map.node_to_user_string(id))) + write!(f, "$({})", ty::tls::with(|tcx| tcx.map.node_to_user_string(id))) } LpUpvar(ty::UpvarId{ var_id, closure_expr_id: _ }) => { let s = ty::tls::with(|tcx| tcx.map.node_to_user_string(var_id)); - format!("$({} captured by closure)", s) + write!(f, "$({} captured by closure)", s) } LpDowncast(ref lp, variant_def_id) => { @@ -1221,15 +1221,15 @@ impl<'tcx> UserString for LoanPath<'tcx> { } else { variant_def_id.repr() }; - format!("({}{}{})", lp.user_string(), DOWNCAST_PRINTED_OPERATOR, variant_str) + write!(f, "({}{}{})", lp, DOWNCAST_PRINTED_OPERATOR, variant_str) } LpExtend(ref lp, _, LpDeref(_)) => { - format!("{}.*", lp.user_string()) + write!(f, "{}.*", lp) } LpExtend(ref lp, _, LpInterior(ref interior)) => { - format!("{}.{}", lp.user_string(), interior.repr()) + write!(f, "{}.{:?}", lp, interior) } } } diff --git a/src/librustc_driver/test.rs b/src/librustc_driver/test.rs index 16f35a8c10a8..658d5166ef5f 100644 --- a/src/librustc_driver/test.rs +++ b/src/librustc_driver/test.rs @@ -227,8 +227,7 @@ impl<'a, 'tcx> Env<'a, 'tcx> { pub fn make_subtype(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool { match infer::mk_subty(self.infcx, true, infer::Misc(DUMMY_SP), a, b) { Ok(_) => true, - Err(ref e) => panic!("Encountered error: {}", - ty::type_err_to_str(self.infcx.tcx, e)) + Err(ref e) => panic!("Encountered error: {}", e) } } @@ -376,8 +375,7 @@ impl<'a, 'tcx> Env<'a, 'tcx> { pub fn make_lub_ty(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> Ty<'tcx> { match self.lub().relate(&t1, &t2) { Ok(t) => t, - Err(ref e) => panic!("unexpected error computing LUB: {}", - ty::type_err_to_str(self.infcx.tcx, e)) + Err(ref e) => panic!("unexpected error computing LUB: {}", e) } } @@ -390,7 +388,7 @@ impl<'a, 'tcx> Env<'a, 'tcx> { panic!("unexpected error computing sub({},{}): {}", t1.repr(), t2.repr(), - ty::type_err_to_str(self.infcx.tcx, e)); + e); } } } @@ -415,8 +413,7 @@ impl<'a, 'tcx> Env<'a, 'tcx> { self.assert_eq(t, t_lub); } Err(ref e) => { - panic!("unexpected error in LUB: {}", - ty::type_err_to_str(self.infcx.tcx, e)) + panic!("unexpected error in LUB: {}", e) } } } diff --git a/src/librustc_trans/trans/_match.rs b/src/librustc_trans/trans/_match.rs index 065aad96f794..7f68e654c2c5 100644 --- a/src/librustc_trans/trans/_match.rs +++ b/src/librustc_trans/trans/_match.rs @@ -221,6 +221,7 @@ use util::ppaux::{self, Repr}; use std; use std::cmp::Ordering; +use std::fmt; use std::rc::Rc; use syntax::ast; use syntax::ast::{DUMMY_NODE_ID, NodeId}; @@ -371,13 +372,13 @@ struct Match<'a, 'p: 'a, 'blk: 'a, 'tcx: 'blk> { pat_renaming_map: Option<&'a FnvHashMap<(NodeId, Span), NodeId>> } -impl<'a, 'p, 'blk, 'tcx> Repr for Match<'a, 'p, 'blk, 'tcx> { - fn repr(&self) -> String { +impl<'a, 'p, 'blk, 'tcx> fmt::Debug for Match<'a, 'p, 'blk, 'tcx> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if ppaux::verbose() { // for many programs, this just take too long to serialize - self.pats.repr() + write!(f, "{:?}", self.pats) } else { - format!("{} pats", self.pats.len()) + write!(f, "{} pats", self.pats.len()) } } } diff --git a/src/librustc_trans/trans/common.rs b/src/librustc_trans/trans/common.rs index 1f8e7e07568e..22582787c7c0 100644 --- a/src/librustc_trans/trans/common.rs +++ b/src/librustc_trans/trans/common.rs @@ -64,7 +64,7 @@ pub use trans::context::CrateContext; /// subtyping, but they are anonymized and normalized as well). This /// is a stronger, caching version of `ty_fold::erase_regions`. pub fn erase_regions<'tcx,T>(cx: &ty::ctxt<'tcx>, value: &T) -> T - where T : TypeFoldable<'tcx> + Repr + where T : TypeFoldable<'tcx> { let value1 = value.fold_with(&mut RegionEraser(cx)); debug!("erase_regions({}) = {}", @@ -88,7 +88,7 @@ pub fn erase_regions<'tcx,T>(cx: &ty::ctxt<'tcx>, value: &T) -> T } fn fold_binder(&mut self, t: &ty::Binder) -> ty::Binder - where T : TypeFoldable<'tcx> + Repr + where T : TypeFoldable<'tcx> { let u = ty::anonymize_late_bound_regions(self.tcx(), t); ty_fold::super_fold_binder(self, &u) @@ -518,7 +518,7 @@ impl<'a, 'tcx> FunctionContext<'a, 'tcx> { } pub fn monomorphize(&self, value: &T) -> T - where T : TypeFoldable<'tcx> + Repr + HasProjectionTypes + Clone + where T : TypeFoldable<'tcx> + HasProjectionTypes { monomorphize::apply_param_substs(self.ccx.tcx(), self.param_substs, @@ -624,7 +624,7 @@ impl<'blk, 'tcx> BlockS<'blk, 'tcx> { } pub fn monomorphize(&self, value: &T) -> T - where T : TypeFoldable<'tcx> + Repr + HasProjectionTypes + Clone + where T : TypeFoldable<'tcx> + HasProjectionTypes { monomorphize::apply_param_substs(self.tcx(), self.fcx.param_substs, @@ -1135,7 +1135,7 @@ pub fn drain_fulfillment_cx_or_panic<'a,'tcx,T>(span: Span, fulfill_cx: &mut traits::FulfillmentContext<'tcx>, result: &T) -> T - where T : TypeFoldable<'tcx> + Repr + where T : TypeFoldable<'tcx> { match drain_fulfillment_cx(infcx, fulfill_cx, result) { Ok(v) => v, @@ -1159,7 +1159,7 @@ pub fn drain_fulfillment_cx<'a,'tcx,T>(infcx: &infer::InferCtxt<'a,'tcx>, fulfill_cx: &mut traits::FulfillmentContext<'tcx>, result: &T) -> StdResult>> - where T : TypeFoldable<'tcx> + Repr + where T : TypeFoldable<'tcx> { debug!("drain_fulfillment_cx(result={})", result.repr()); diff --git a/src/librustc_trans/trans/glue.rs b/src/librustc_trans/trans/glue.rs index e885f56ef8e4..e0ac4391d67d 100644 --- a/src/librustc_trans/trans/glue.rs +++ b/src/librustc_trans/trans/glue.rs @@ -205,19 +205,6 @@ impl<'tcx> DropGlueKind<'tcx> { } } -impl<'tcx> Repr for DropGlueKind<'tcx> { - fn repr(&self) -> String { - match *self { - DropGlueKind::Ty(ty) => { - format!("DropGlueKind::Ty({})", ty.repr()) - } - DropGlueKind::TyContents(ty) => { - format!("DropGlueKind::TyContents({})", ty.repr()) - } - } - } -} - fn get_drop_glue_core<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, g: DropGlueKind<'tcx>) -> ValueRef { debug!("make drop glue for {}", g.repr()); diff --git a/src/librustc_trans/trans/monomorphize.rs b/src/librustc_trans/trans/monomorphize.rs index 374471696000..4a81610dd852 100644 --- a/src/librustc_trans/trans/monomorphize.rs +++ b/src/librustc_trans/trans/monomorphize.rs @@ -303,7 +303,7 @@ pub fn apply_param_substs<'tcx,T>(tcx: &ty::ctxt<'tcx>, param_substs: &Substs<'tcx>, value: &T) -> T - where T : TypeFoldable<'tcx> + Repr + HasProjectionTypes + Clone + where T : TypeFoldable<'tcx> + HasProjectionTypes { let substituted = value.subst(tcx, param_substs); normalize_associated_type(tcx, &substituted) @@ -314,7 +314,7 @@ pub fn apply_param_substs<'tcx,T>(tcx: &ty::ctxt<'tcx>, /// and hence we can be sure that all associated types will be /// completely normalized away. pub fn normalize_associated_type<'tcx,T>(tcx: &ty::ctxt<'tcx>, value: &T) -> T - where T : TypeFoldable<'tcx> + Repr + HasProjectionTypes + Clone + where T : TypeFoldable<'tcx> + HasProjectionTypes { debug!("normalize_associated_type(t={})", value.repr()); diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index b7516530e6f1..dee8eefd9da5 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -2106,7 +2106,7 @@ pub fn partition_bounds<'a>(tcx: &ty::ctxt, ast_bounds: &'a [ast::TyParamBound]) -> PartitionedBounds<'a> { - let mut builtin_bounds = ty::empty_builtin_bounds(); + let mut builtin_bounds = ty::BuiltinBounds::empty(); let mut region_bounds = Vec::new(); let mut trait_bounds = Vec::new(); for ast_bound in ast_bounds { diff --git a/src/librustc_typeck/check/assoc.rs b/src/librustc_typeck/check/assoc.rs index 5e25404bf738..ec5752fb50ff 100644 --- a/src/librustc_typeck/check/assoc.rs +++ b/src/librustc_typeck/check/assoc.rs @@ -24,7 +24,7 @@ pub fn normalize_associated_types_in<'a,'tcx,T>(infcx: &InferCtxt<'a,'tcx>, body_id: ast::NodeId, value: &T) -> T - where T : TypeFoldable<'tcx> + HasProjectionTypes + Clone + Repr + where T : TypeFoldable<'tcx> + HasProjectionTypes { debug!("normalize_associated_types_in(value={})", value.repr()); let mut selcx = SelectionContext::new(infcx, typer); diff --git a/src/librustc_typeck/check/callee.rs b/src/librustc_typeck/check/callee.rs index a5422e1e58e5..da1c44604f9f 100644 --- a/src/librustc_typeck/check/callee.rs +++ b/src/librustc_typeck/check/callee.rs @@ -328,6 +328,7 @@ fn write_overloaded_call_method_map<'a,'tcx>(fcx: &FnCtxt<'a, 'tcx>, fcx.inh.method_map.borrow_mut().insert(method_call, method_callee); } +#[derive(Debug)] struct CallResolution<'tcx> { call_expr: &'tcx ast::Expr, callee_expr: &'tcx ast::Expr, @@ -337,19 +338,6 @@ struct CallResolution<'tcx> { closure_def_id: ast::DefId, } -impl<'tcx> Repr for CallResolution<'tcx> { - fn repr(&self) -> String { - format!("CallResolution(call_expr={}, callee_expr={}, adjusted_ty={}, \ - autoderefs={}, fn_sig={}, closure_def_id={})", - self.call_expr.repr(), - self.callee_expr.repr(), - self.adjusted_ty.repr(), - self.autoderefs, - self.fn_sig.repr(), - self.closure_def_id.repr()) - } -} - impl<'tcx> DeferredCallResolution<'tcx> for CallResolution<'tcx> { fn resolve<'a>(&mut self, fcx: &FnCtxt<'a,'tcx>) { debug!("DeferredCallResolution::resolve() {}", diff --git a/src/librustc_typeck/check/compare_method.rs b/src/librustc_typeck/check/compare_method.rs index eb50b231155b..3c38f471c853 100644 --- a/src/librustc_typeck/check/compare_method.rs +++ b/src/librustc_typeck/check/compare_method.rs @@ -341,7 +341,7 @@ pub fn compare_impl_method<'tcx>(tcx: &ty::ctxt<'tcx>, span_err!(tcx.sess, impl_m_span, E0053, "method `{}` has an incompatible type for trait: {}", token::get_name(trait_m.name), - ty::type_err_to_str(tcx, &terr)); + terr); return; } } @@ -487,7 +487,7 @@ pub fn compare_const_impl<'tcx>(tcx: &ty::ctxt<'tcx>, "implemented const `{}` has an incompatible type for \ trait: {}", token::get_name(trait_c.name), - ty::type_err_to_str(tcx, &terr)); + terr); return; } } diff --git a/src/librustc_typeck/check/method/confirm.rs b/src/librustc_typeck/check/method/confirm.rs index 2b8394f2e165..2b5fb524b524 100644 --- a/src/librustc_typeck/check/method/confirm.rs +++ b/src/librustc_typeck/check/method/confirm.rs @@ -657,7 +657,7 @@ impl<'a,'tcx> ConfirmContext<'a,'tcx> { } fn replace_late_bound_regions_with_fresh_var(&self, value: &ty::Binder) -> T - where T : TypeFoldable<'tcx> + Repr + where T : TypeFoldable<'tcx> { self.infcx().replace_late_bound_regions_with_fresh_var( self.span, infer::FnCall, value).0 diff --git a/src/librustc_typeck/check/method/probe.rs b/src/librustc_typeck/check/method/probe.rs index eeccb576749c..d71b91762e92 100644 --- a/src/librustc_typeck/check/method/probe.rs +++ b/src/librustc_typeck/check/method/probe.rs @@ -46,18 +46,21 @@ struct ProbeContext<'a, 'tcx:'a> { static_candidates: Vec, } +#[derive(Debug)] struct CandidateStep<'tcx> { self_ty: Ty<'tcx>, autoderefs: usize, unsize: bool } +#[derive(Debug)] struct Candidate<'tcx> { xform_self_ty: Ty<'tcx>, item: ty::ImplOrTraitItem<'tcx>, kind: CandidateKind<'tcx>, } +#[derive(Debug)] enum CandidateKind<'tcx> { InherentImplCandidate(/* Impl */ ast::DefId, subst::Substs<'tcx>, /* Normalize obligations */ Vec>), @@ -70,6 +73,7 @@ enum CandidateKind<'tcx> { ProjectionCandidate(ast::DefId, ItemIndex), } +#[derive(Debug)] pub struct Pick<'tcx> { pub item: ty::ImplOrTraitItem<'tcx>, pub kind: PickKind<'tcx>, @@ -1264,7 +1268,7 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> { /// and/or tracking the substitution and /// so forth. fn erase_late_bound_regions(&self, value: &ty::Binder) -> T - where T : TypeFoldable<'tcx> + Repr + where T : TypeFoldable<'tcx> { ty::erase_late_bound_regions(self.tcx(), value) } @@ -1370,59 +1374,3 @@ impl<'tcx> Candidate<'tcx> { } } } - -impl<'tcx> Repr for Candidate<'tcx> { - fn repr(&self) -> String { - format!("Candidate(xform_self_ty={}, kind={})", - self.xform_self_ty.repr(), - self.kind.repr()) - } -} - -impl<'tcx> Repr for CandidateKind<'tcx> { - fn repr(&self) -> String { - match *self { - InherentImplCandidate(ref a, ref b, ref c) => - format!("InherentImplCandidate({},{},{})", a.repr(), b.repr(), - c.repr()), - ObjectCandidate(a, b, c) => - format!("ObjectCandidate({},{},{})", a.repr(), b, c), - ExtensionImplCandidate(ref a, ref b, ref c, ref d, ref e) => - format!("ExtensionImplCandidate({},{},{},{},{})", a.repr(), b.repr(), - c.repr(), d, e.repr()), - ClosureCandidate(ref a, ref b) => - format!("ClosureCandidate({},{})", a.repr(), b), - WhereClauseCandidate(ref a, ref b) => - format!("WhereClauseCandidate({},{})", a.repr(), b), - ProjectionCandidate(ref a, ref b) => - format!("ProjectionCandidate({},{})", a.repr(), b), - } - } -} - -impl<'tcx> Repr for CandidateStep<'tcx> { - fn repr(&self) -> String { - format!("CandidateStep({}, autoderefs={}, unsize={})", - self.self_ty.repr(), - self.autoderefs, - self.unsize) - } -} - -impl<'tcx> Repr for PickKind<'tcx> { - fn repr(&self) -> String { - format!("{:?}", self) - } -} - -impl<'tcx> Repr for Pick<'tcx> { - fn repr(&self) -> String { - format!("Pick(item={}, autoderefs={}, - autoref={}, unsize={}, kind={:?})", - self.item.repr(), - self.autoderefs, - self.autoref.repr(), - self.unsize.repr(), - self.kind) - } -} diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index b728c0129193..cc57ec8a8cd8 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -193,7 +193,7 @@ type DeferredCallResolutionHandler<'tcx> = Box+'tcx /// When type-checking an expression, we propagate downward /// whatever type hint we are able in the form of an `Expectation`. -#[derive(Copy, Clone)] +#[derive(Copy, Clone, Debug)] pub enum Expectation<'tcx> { /// We know nothing about what type this expression should have. NoExpectation, @@ -398,7 +398,7 @@ impl<'a, 'tcx> Inherited<'a, 'tcx> { body_id: ast::NodeId, value: &T) -> T - where T : TypeFoldable<'tcx> + Clone + HasProjectionTypes + Repr + where T : TypeFoldable<'tcx> + HasProjectionTypes { let mut fulfillment_cx = self.fulfillment_cx.borrow_mut(); assoc::normalize_associated_types_in(&self.infcx, @@ -1444,7 +1444,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { substs: &Substs<'tcx>, value: &T) -> T - where T : TypeFoldable<'tcx> + Clone + HasProjectionTypes + Repr + where T : TypeFoldable<'tcx> + HasProjectionTypes { let value = value.subst(self.tcx(), substs); let result = self.normalize_associated_types_in(span, &value); @@ -1470,7 +1470,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn normalize_associated_types_in(&self, span: Span, value: &T) -> T - where T : TypeFoldable<'tcx> + Clone + HasProjectionTypes + Repr + where T : TypeFoldable<'tcx> + HasProjectionTypes { self.inh.normalize_associated_types_in(self, span, self.body_id, value) } @@ -3605,8 +3605,6 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, type_and_substs.ty) { Ok(()) => {} Err(type_error) => { - let type_error_description = - ty::type_err_to_str(tcx, &type_error); span_err!(fcx.tcx().sess, path.span, E0235, "structure constructor specifies a \ structure of type `{}`, but this \ @@ -3616,7 +3614,7 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, fcx.infcx() .ty_to_string( actual_structure_type), - type_error_description); + type_error); ty::note_and_explain_type_err(tcx, &type_error, path.span); } } @@ -3907,20 +3905,6 @@ impl<'tcx> Expectation<'tcx> { } } -impl<'tcx> Repr for Expectation<'tcx> { - fn repr(&self) -> String { - match *self { - NoExpectation => format!("NoExpectation"), - ExpectHasType(t) => format!("ExpectHasType({})", - t.repr()), - ExpectCastableToType(t) => format!("ExpectCastableToType({})", - t.repr()), - ExpectRvalueLikeUnsized(t) => format!("ExpectRvalueLikeUnsized({})", - t.repr()), - } - } -} - pub fn check_decl_initializer<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>, local: &'tcx ast::Local, init: &'tcx ast::Expr) diff --git a/src/librustc_typeck/check/wf.rs b/src/librustc_typeck/check/wf.rs index bd7b212d3206..7bcd3ddf5904 100644 --- a/src/librustc_typeck/check/wf.rs +++ b/src/librustc_typeck/check/wf.rs @@ -536,7 +536,7 @@ impl<'cx,'tcx> TypeFolder<'tcx> for BoundsChecker<'cx,'tcx> { } fn fold_binder(&mut self, binder: &ty::Binder) -> ty::Binder - where T : TypeFoldable<'tcx> + Repr + where T : TypeFoldable<'tcx> { self.binding_count += 1; let value = liberate_late_bound_regions( diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 4bb9aa495577..9987b884cf28 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -2235,7 +2235,7 @@ fn check_method_self_type<'a, 'tcx, RS:RegionScope>( scope: region::DestructionScopeData, value: &T) -> T - where T : TypeFoldable<'tcx> + Repr + where T : TypeFoldable<'tcx> { /*! * Convert early-bound regions into free regions; normally this is done by diff --git a/src/librustc_typeck/lib.rs b/src/librustc_typeck/lib.rs index 3f779d679448..b56bb895b9ed 100644 --- a/src/librustc_typeck/lib.rs +++ b/src/librustc_typeck/lib.rs @@ -199,11 +199,7 @@ fn require_same_types<'a, 'tcx, M>(tcx: &ty::ctxt<'tcx>, match result { Ok(_) => true, Err(ref terr) => { - span_err!(tcx.sess, span, E0211, - "{}: {}", - msg(), - ty::type_err_to_str(tcx, - terr)); + span_err!(tcx.sess, span, E0211, "{}: {}", msg(), terr); ty::note_and_explain_type_err(tcx, terr, span); false } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 77409f2746a5..d40a9522f23a 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -522,7 +522,7 @@ pub enum TyParamBound { impl TyParamBound { fn maybe_sized(cx: &DocContext) -> TyParamBound { use syntax::ast::TraitBoundModifier as TBM; - let mut sized_bound = ty::BuiltinBound::BoundSized.clean(cx); + let mut sized_bound = ty::BoundSized.clean(cx); if let TyParamBound::TraitBound(_, ref mut tbm) = sized_bound { *tbm = TBM::Maybe }; diff --git a/src/test/compile-fail/object-lifetime-default.rs b/src/test/compile-fail/object-lifetime-default.rs index ac03c085b7b6..b71eadd6d08a 100644 --- a/src/test/compile-fail/object-lifetime-default.rs +++ b/src/test/compile-fail/object-lifetime-default.rs @@ -29,6 +29,6 @@ struct E<'a,'b:'a,T:'b>(&'a T, &'b T); //~ ERROR 'b struct F<'a,'b,T:'a,U:'b>(&'a T, &'b U); //~ ERROR 'a,'b #[rustc_object_lifetime_default] -struct G<'a,'b,T:'a,U:'a+'b>(&'a T, &'b U); //~ ERROR 'a,Ambiguous +struct G<'a,'b,T:'a,U:'a+'b>(&'a T, &'b U); //~ ERROR 'a,Some(Ambiguous) fn main() { }