From 4ef3f591881a1713d8c7bd6a21c16f67ab2ad2ec Mon Sep 17 00:00:00 2001 From: Srinivas Reddy Thatiparthy Date: Mon, 26 Sep 2016 09:11:27 +0530 Subject: [PATCH] Run rustfmt on librustc_typeck/check/ folder --- src/librustc_typeck/check/assoc.rs | 6 +- src/librustc_typeck/check/autoderef.rs | 109 +++--- src/librustc_typeck/check/callee.rs | 169 ++++---- src/librustc_typeck/check/cast.rs | 214 +++++----- src/librustc_typeck/check/closure.rs | 121 +++--- src/librustc_typeck/check/coercion.rs | 209 +++++----- src/librustc_typeck/check/compare_method.rs | 408 ++++++++++---------- 7 files changed, 633 insertions(+), 603 deletions(-) diff --git a/src/librustc_typeck/check/assoc.rs b/src/librustc_typeck/check/assoc.rs index 41f34b9040e83..9610477d8fd91 100644 --- a/src/librustc_typeck/check/assoc.rs +++ b/src/librustc_typeck/check/assoc.rs @@ -9,13 +9,13 @@ // except according to those terms. use rustc::infer::InferCtxt; -use rustc::traits::{self, FulfillmentContext, Normalized, MiscObligation, - SelectionContext, ObligationCause}; +use rustc::traits::{self, FulfillmentContext, Normalized, MiscObligation, SelectionContext, + ObligationCause}; use rustc::ty::fold::TypeFoldable; use syntax::ast; use syntax_pos::Span; -//FIXME(@jroesch): Ideally we should be able to drop the fulfillment_cx argument. +// FIXME(@jroesch): Ideally we should be able to drop the fulfillment_cx argument. pub fn normalize_associated_types_in<'a, 'gcx, 'tcx, T>( infcx: &InferCtxt<'a, 'gcx, 'tcx>, fulfillment_cx: &mut FulfillmentContext<'tcx>, diff --git a/src/librustc_typeck/check/autoderef.rs b/src/librustc_typeck/check/autoderef.rs index 19261a2447f91..8127bcf825643 100644 --- a/src/librustc_typeck/check/autoderef.rs +++ b/src/librustc_typeck/check/autoderef.rs @@ -26,7 +26,7 @@ use syntax::parse::token; #[derive(Copy, Clone, Debug)] enum AutoderefKind { Builtin, - Overloaded + Overloaded, } pub struct Autoderef<'a, 'gcx: 'tcx, 'tcx: 'a> { @@ -35,7 +35,7 @@ pub struct Autoderef<'a, 'gcx: 'tcx, 'tcx: 'a> { cur_ty: Ty<'tcx>, obligations: Vec>, at_start: bool, - span: Span + span: Span, } impl<'a, 'gcx, 'tcx> Iterator for Autoderef<'a, 'gcx, 'tcx> { @@ -45,7 +45,8 @@ impl<'a, 'gcx, 'tcx> Iterator for Autoderef<'a, 'gcx, 'tcx> { let tcx = self.fcx.tcx; debug!("autoderef: steps={:?}, cur_ty={:?}", - self.steps, self.cur_ty); + self.steps, + self.cur_ty); if self.at_start { self.at_start = false; debug!("autoderef stage #0 is {:?}", self.cur_ty); @@ -54,11 +55,13 @@ impl<'a, 'gcx, 'tcx> Iterator for Autoderef<'a, 'gcx, 'tcx> { if self.steps.len() == tcx.sess.recursion_limit.get() { // We've reached the recursion limit, error gracefully. - struct_span_err!(tcx.sess, self.span, E0055, - "reached the recursion limit while auto-dereferencing {:?}", - self.cur_ty) - .span_label(self.span, &format!("deref recursion limit reached")) - .emit(); + struct_span_err!(tcx.sess, + self.span, + E0055, + "reached the recursion limit while auto-dereferencing {:?}", + self.cur_ty) + .span_label(self.span, &format!("deref recursion limit reached")) + .emit(); return None; } @@ -72,7 +75,7 @@ impl<'a, 'gcx, 'tcx> Iterator for Autoderef<'a, 'gcx, 'tcx> { } else { match self.overloaded_deref_ty(self.cur_ty) { Some(ty) => (AutoderefKind::Overloaded, ty), - _ => return None + _ => return None, } }; @@ -81,8 +84,10 @@ impl<'a, 'gcx, 'tcx> Iterator for Autoderef<'a, 'gcx, 'tcx> { } self.steps.push((self.cur_ty, kind)); - debug!("autoderef stage #{:?} is {:?} from {:?}", self.steps.len(), - new_ty, (self.cur_ty, kind)); + debug!("autoderef stage #{:?} is {:?} from {:?}", + self.steps.len(), + new_ty, + (self.cur_ty, kind)); self.cur_ty = new_ty; Some((self.cur_ty, self.steps.len())) @@ -99,9 +104,9 @@ impl<'a, 'gcx, 'tcx> Autoderef<'a, 'gcx, 'tcx> { let trait_ref = TraitRef { def_id: match tcx.lang_items.deref_trait() { Some(f) => f, - None => return None + None => return None, }, - substs: Substs::new_trait(tcx, self.cur_ty, &[]) + substs: Substs::new_trait(tcx, self.cur_ty, &[]), }; let cause = traits::ObligationCause::misc(self.span, self.fcx.body_id); @@ -113,15 +118,13 @@ impl<'a, 'gcx, 'tcx> Autoderef<'a, 'gcx, 'tcx> { return None; } - let normalized = traits::normalize_projection_type( - &mut selcx, - ty::ProjectionTy { - trait_ref: trait_ref, - item_name: token::intern("Target") - }, - cause, - 0 - ); + let normalized = traits::normalize_projection_type(&mut selcx, + ty::ProjectionTy { + trait_ref: trait_ref, + item_name: token::intern("Target"), + }, + cause, + 0); debug!("overloaded_deref_ty({:?}) = {:?}", ty, normalized); self.obligations.extend(normalized.obligations); @@ -134,17 +137,23 @@ impl<'a, 'gcx, 'tcx> Autoderef<'a, 'gcx, 'tcx> { } pub fn finalize<'b, I>(self, pref: LvaluePreference, exprs: I) - where I: IntoIterator + where I: IntoIterator { - let methods : Vec<_> = self.steps.iter().map(|&(ty, kind)| { - if let AutoderefKind::Overloaded = kind { - self.fcx.try_overloaded_deref(self.span, None, ty, pref) - } else { - None - } - }).collect(); + let methods: Vec<_> = self.steps + .iter() + .map(|&(ty, kind)| { + if let AutoderefKind::Overloaded = kind { + self.fcx.try_overloaded_deref(self.span, None, ty, pref) + } else { + None + } + }) + .collect(); - debug!("finalize({:?}) - {:?},{:?}", pref, methods, self.obligations); + debug!("finalize({:?}) - {:?},{:?}", + pref, + methods, + self.obligations); for expr in exprs { debug!("finalize - finalizing #{} - {:?}", expr.id, expr); @@ -163,18 +172,14 @@ impl<'a, 'gcx, 'tcx> Autoderef<'a, 'gcx, 'tcx> { } impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { - pub fn autoderef(&'a self, - span: Span, - base_ty: Ty<'tcx>) - -> Autoderef<'a, 'gcx, 'tcx> - { + pub fn autoderef(&'a self, span: Span, base_ty: Ty<'tcx>) -> Autoderef<'a, 'gcx, 'tcx> { Autoderef { fcx: self, steps: vec![], cur_ty: self.resolve_type_vars_if_possible(&base_ty), obligations: vec![], at_start: true, - span: span + span: span, } } @@ -183,28 +188,36 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { base_expr: Option<&hir::Expr>, base_ty: Ty<'tcx>, lvalue_pref: LvaluePreference) - -> Option> - { + -> Option> { debug!("try_overloaded_deref({:?},{:?},{:?},{:?})", - span, base_expr, base_ty, lvalue_pref); + span, + base_expr, + base_ty, + lvalue_pref); // Try DerefMut first, if preferred. let method = match (lvalue_pref, self.tcx.lang_items.deref_mut_trait()) { (PreferMutLvalue, Some(trait_did)) => { - self.lookup_method_in_trait(span, base_expr, - token::intern("deref_mut"), trait_did, - base_ty, None) + self.lookup_method_in_trait(span, + base_expr, + token::intern("deref_mut"), + trait_did, + base_ty, + None) } - _ => None + _ => None, }; // Otherwise, fall back to Deref. let method = match (method, self.tcx.lang_items.deref_trait()) { (None, Some(trait_did)) => { - self.lookup_method_in_trait(span, base_expr, - token::intern("deref"), trait_did, - base_ty, None) + self.lookup_method_in_trait(span, + base_expr, + token::intern("deref"), + trait_did, + base_ty, + None) } - (method, _) => method + (method, _) => method, }; method diff --git a/src/librustc_typeck/check/callee.rs b/src/librustc_typeck/check/callee.rs index 75c1d28f7d830..c5a21d7dd91ce 100644 --- a/src/librustc_typeck/check/callee.rs +++ b/src/librustc_typeck/check/callee.rs @@ -8,8 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use super::{DeferredCallResolution, Expectation, FnCtxt, - TupleArgumentsFlag}; +use super::{DeferredCallResolution, Expectation, FnCtxt, TupleArgumentsFlag}; use CrateCtxt; use hir::def::Def; @@ -27,7 +26,10 @@ use rustc::hir; /// method that is called) pub fn check_legal_trait_for_method_call(ccx: &CrateCtxt, span: Span, trait_id: DefId) { if ccx.tcx.lang_items.drop_trait() == Some(trait_id) { - struct_span_err!(ccx.tcx.sess, span, E0040, "explicit use of destructor method") + struct_span_err!(ccx.tcx.sess, + span, + E0040, + "explicit use of destructor method") .span_label(span, &format!("explicit destructor calls not allowed")) .emit(); } @@ -36,7 +38,7 @@ pub fn check_legal_trait_for_method_call(ccx: &CrateCtxt, span: Span, trait_id: enum CallStep<'tcx> { Builtin, DeferredClosure(ty::FnSig<'tcx>), - Overloaded(ty::MethodCallee<'tcx>) + Overloaded(ty::MethodCallee<'tcx>), } impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { @@ -44,15 +46,17 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { call_expr: &'gcx hir::Expr, callee_expr: &'gcx hir::Expr, arg_exprs: &'gcx [P], - expected: Expectation<'tcx>) -> Ty<'tcx> - { + expected: Expectation<'tcx>) + -> Ty<'tcx> { let original_callee_ty = self.check_expr(callee_expr); let expr_ty = self.structurally_resolved_type(call_expr.span, original_callee_ty); let mut autoderef = self.autoderef(callee_expr.span, expr_ty); - let result = autoderef.by_ref().flat_map(|(adj_ty, idx)| { - self.try_overloaded_call_step(call_expr, callee_expr, adj_ty, idx) - }).next(); + let result = autoderef.by_ref() + .flat_map(|(adj_ty, idx)| { + self.try_overloaded_call_step(call_expr, callee_expr, adj_ty, idx) + }) + .next(); let callee_ty = autoderef.unambiguous_final_ty(); autoderef.finalize(LvaluePreference::NoPreference, Some(callee_expr)); @@ -71,8 +75,11 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } Some(CallStep::Overloaded(method_callee)) => { - self.confirm_overloaded_call(call_expr, callee_expr, - arg_exprs, expected, method_callee) + self.confirm_overloaded_call(call_expr, + callee_expr, + arg_exprs, + expected, + method_callee) } }; @@ -87,8 +94,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { callee_expr: &'gcx hir::Expr, adjusted_ty: Ty<'tcx>, autoderefs: usize) - -> Option> - { + -> Option> { debug!("try_overloaded_call_step(call_expr={:?}, adjusted_ty={:?}, autoderefs={})", call_expr, adjusted_ty, @@ -108,20 +114,20 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // haven't yet decided on whether the closure is fn vs // fnmut vs fnonce. If so, we have to defer further processing. if self.closure_kind(def_id).is_none() { - let closure_ty = - self.closure_type(def_id, substs); - let fn_sig = - self.replace_late_bound_regions_with_fresh_var(call_expr.span, - infer::FnCall, - &closure_ty.sig).0; - self.record_deferred_call_resolution(def_id, Box::new(CallResolution { - call_expr: call_expr, - callee_expr: callee_expr, - adjusted_ty: adjusted_ty, - autoderefs: autoderefs, - fn_sig: fn_sig.clone(), - closure_def_id: def_id - })); + let closure_ty = self.closure_type(def_id, substs); + let fn_sig = self.replace_late_bound_regions_with_fresh_var(call_expr.span, + infer::FnCall, + &closure_ty.sig) + .0; + self.record_deferred_call_resolution(def_id, + Box::new(CallResolution { + call_expr: call_expr, + callee_expr: callee_expr, + adjusted_ty: adjusted_ty, + autoderefs: autoderefs, + fn_sig: fn_sig.clone(), + closure_def_id: def_id, + })); return Some(CallStep::DeferredClosure(fn_sig)); } } @@ -150,14 +156,12 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { callee_expr: &hir::Expr, adjusted_ty: Ty<'tcx>, autoderefs: usize) - -> Option> - { + -> Option> { // Try the options that are least restrictive on the caller first. - for &(opt_trait_def_id, method_name) in &[ - (self.tcx.lang_items.fn_trait(), token::intern("call")), - (self.tcx.lang_items.fn_mut_trait(), token::intern("call_mut")), - (self.tcx.lang_items.fn_once_trait(), token::intern("call_once")), - ] { + for &(opt_trait_def_id, method_name) in + &[(self.tcx.lang_items.fn_trait(), token::intern("call")), + (self.tcx.lang_items.fn_mut_trait(), token::intern("call_mut")), + (self.tcx.lang_items.fn_once_trait(), token::intern("call_once"))] { let trait_def_id = match opt_trait_def_id { Some(def_id) => def_id, None => continue, @@ -185,19 +189,20 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { call_expr: &hir::Expr, callee_ty: Ty<'tcx>, arg_exprs: &'gcx [P], - expected: Expectation<'tcx>) -> Ty<'tcx> - { + expected: Expectation<'tcx>) + -> Ty<'tcx> { let error_fn_sig; let fn_sig = match callee_ty.sty { - ty::TyFnDef(.., &ty::BareFnTy {ref sig, ..}) | - ty::TyFnPtr(&ty::BareFnTy {ref sig, ..}) => { - sig - } + ty::TyFnDef(.., &ty::BareFnTy { ref sig, .. }) | + ty::TyFnPtr(&ty::BareFnTy { ref sig, .. }) => sig, _ => { - let mut err = self.type_error_struct(call_expr.span, |actual| { - format!("expected function, found `{}`", actual) - }, callee_ty); + let mut err = self.type_error_struct(call_expr.span, + |actual| { + format!("expected function, found `{}`", + actual) + }, + callee_ty); if let hir::ExprCall(ref expr, _) = call_expr.node { let tcx = self.tcx; @@ -218,7 +223,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { error_fn_sig = ty::Binder(ty::FnSig { inputs: self.err_args(arg_exprs.len()), output: self.tcx.types.err, - variadic: false + variadic: false, }); &error_fn_sig @@ -231,17 +236,16 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // previously appeared within a `Binder<>` and hence would not // have been normalized before. let fn_sig = - self.replace_late_bound_regions_with_fresh_var(call_expr.span, - infer::FnCall, - fn_sig).0; - let fn_sig = - self.normalize_associated_types_in(call_expr.span, &fn_sig); + self.replace_late_bound_regions_with_fresh_var(call_expr.span, infer::FnCall, fn_sig) + .0; + let fn_sig = self.normalize_associated_types_in(call_expr.span, &fn_sig); // Call the generic checker. - let expected_arg_tys = self.expected_types_for_fn_args(call_expr.span, - expected, - fn_sig.output, - &fn_sig.inputs); + let expected_arg_tys = + self.expected_types_for_fn_args(call_expr.span, + expected, + fn_sig.output, + &fn_sig.inputs); self.check_argument_types(call_expr.span, &fn_sig.inputs, &expected_arg_tys[..], @@ -256,18 +260,17 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { call_expr: &hir::Expr, arg_exprs: &'gcx [P], expected: Expectation<'tcx>, - fn_sig: ty::FnSig<'tcx>) -> Ty<'tcx> - { + fn_sig: ty::FnSig<'tcx>) + -> Ty<'tcx> { // `fn_sig` is the *signature* of the cosure being called. We // don't know the full details yet (`Fn` vs `FnMut` etc), but we // do know the types expected for each argument and the return // type. - let expected_arg_tys = - self.expected_types_for_fn_args(call_expr.span, - expected, - fn_sig.output.clone(), - &fn_sig.inputs); + let expected_arg_tys = self.expected_types_for_fn_args(call_expr.span, + expected, + fn_sig.output.clone(), + &fn_sig.inputs); self.check_argument_types(call_expr.span, &fn_sig.inputs, @@ -284,15 +287,14 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { callee_expr: &'gcx hir::Expr, arg_exprs: &'gcx [P], expected: Expectation<'tcx>, - method_callee: ty::MethodCallee<'tcx>) -> Ty<'tcx> - { - let output_type = - self.check_method_argument_types(call_expr.span, - method_callee.ty, - callee_expr, - arg_exprs, - TupleArgumentsFlag::TupleArguments, - expected); + method_callee: ty::MethodCallee<'tcx>) + -> Ty<'tcx> { + let output_type = self.check_method_argument_types(call_expr.span, + method_callee.ty, + callee_expr, + arg_exprs, + TupleArgumentsFlag::TupleArguments, + expected); self.write_overloaded_call_method_map(call_expr, method_callee); output_type @@ -318,16 +320,17 @@ struct CallResolution<'gcx: 'tcx, 'tcx> { impl<'gcx, 'tcx> DeferredCallResolution<'gcx, 'tcx> for CallResolution<'gcx, 'tcx> { fn resolve<'a>(&mut self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) { - debug!("DeferredCallResolution::resolve() {:?}", - self); + debug!("DeferredCallResolution::resolve() {:?}", self); // we should not be invoked until the closure kind has been // determined by upvar inference assert!(fcx.closure_kind(self.closure_def_id).is_some()); // We may now know enough to figure out fn vs fnmut etc. - match fcx.try_overloaded_call_traits(self.call_expr, self.callee_expr, - self.adjusted_ty, self.autoderefs) { + match fcx.try_overloaded_call_traits(self.call_expr, + self.callee_expr, + self.adjusted_ty, + self.autoderefs) { Some(method_callee) => { // One problem is that when we get here, we are going // to have a newly instantiated function signature @@ -337,28 +340,24 @@ impl<'gcx, 'tcx> DeferredCallResolution<'gcx, 'tcx> for CallResolution<'gcx, 'tc // can't because of the annoying need for a TypeTrace. // (This always bites me, should find a way to // refactor it.) - let method_sig = fcx.tcx.no_late_bound_regions(method_callee.ty.fn_sig()) - .unwrap(); + let method_sig = fcx.tcx + .no_late_bound_regions(method_callee.ty.fn_sig()) + .unwrap(); - debug!("attempt_resolution: method_callee={:?}", - method_callee); + debug!("attempt_resolution: method_callee={:?}", method_callee); for (&method_arg_ty, &self_arg_ty) in - method_sig.inputs[1..].iter().zip(&self.fn_sig.inputs) - { + method_sig.inputs[1..].iter().zip(&self.fn_sig.inputs) { fcx.demand_eqtype(self.call_expr.span, self_arg_ty, method_arg_ty); } - fcx.demand_eqtype(self.call_expr.span, - method_sig.output, - self.fn_sig.output); + fcx.demand_eqtype(self.call_expr.span, method_sig.output, self.fn_sig.output); fcx.write_overloaded_call_method_map(self.call_expr, method_callee); } None => { - span_bug!( - self.call_expr.span, - "failed to find an overloaded call trait for closure call"); + span_bug!(self.call_expr.span, + "failed to find an overloaded call trait for closure call"); } } } diff --git a/src/librustc_typeck/check/cast.rs b/src/librustc_typeck/check/cast.rs index 51a9b18392dcf..c456b9358b3e2 100644 --- a/src/librustc_typeck/check/cast.rs +++ b/src/librustc_typeck/check/cast.rs @@ -69,7 +69,7 @@ enum UnsizeKind<'tcx> { /// The unsize info of this projection OfProjection(&'tcx ty::ProjectionTy<'tcx>), /// The unsize info of this parameter - OfParam(&'tcx ty::ParamTy) + OfParam(&'tcx ty::ParamTy), } impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { @@ -83,13 +83,13 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // FIXME(arielb1): do some kind of normalization match def.struct_variant().fields.last() { None => None, - Some(f) => self.unsize_kind(f.ty(self.tcx, substs)) + Some(f) => self.unsize_kind(f.ty(self.tcx, substs)), } } // We should really try to normalize here. ty::TyProjection(ref pi) => Some(UnsizeKind::OfProjection(pi)), ty::TyParam(ref p) => Some(UnsizeKind::OfParam(p)), - _ => None + _ => None, } } } @@ -133,9 +133,7 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> { check.report_cast_to_unsized_type(fcx); Err(ErrorReported) } - _ => { - Ok(check) - } + _ => Ok(check), } } @@ -145,18 +143,21 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> { CastError::NeedViaThinPtr | CastError::NeedViaInt | CastError::NeedViaUsize => { - fcx.type_error_struct(self.span, |actual| { - format!("casting `{}` as `{}` is invalid", - actual, - fcx.ty_to_string(self.cast_ty)) - }, self.expr_ty) - .help(&format!("cast through {} first", match e { - CastError::NeedViaPtr => "a raw pointer", - CastError::NeedViaThinPtr => "a thin pointer", - CastError::NeedViaInt => "an integer", - CastError::NeedViaUsize => "a usize", - _ => bug!() - })) + fcx.type_error_struct(self.span, + |actual| { + format!("casting `{}` as `{}` is invalid", + actual, + fcx.ty_to_string(self.cast_ty)) + }, + self.expr_ty) + .help(&format!("cast through {} first", + match e { + CastError::NeedViaPtr => "a raw pointer", + CastError::NeedViaThinPtr => "a thin pointer", + CastError::NeedViaInt => "an integer", + CastError::NeedViaUsize => "a usize", + _ => bug!(), + })) .emit(); } CastError::CastToBool => { @@ -166,37 +167,49 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> { .emit(); } CastError::CastToChar => { - fcx.type_error_message(self.span, |actual| { - format!("only `u8` can be cast as `char`, not `{}`", actual) - }, self.expr_ty); + fcx.type_error_message(self.span, + |actual| { + format!("only `u8` can be cast as `char`, not `{}`", + actual) + }, + self.expr_ty); } CastError::NonScalar => { - fcx.type_error_message(self.span, |actual| { - format!("non-scalar cast: `{}` as `{}`", - actual, - fcx.ty_to_string(self.cast_ty)) - }, self.expr_ty); + fcx.type_error_message(self.span, + |actual| { + format!("non-scalar cast: `{}` as `{}`", + actual, + fcx.ty_to_string(self.cast_ty)) + }, + self.expr_ty); } CastError::IllegalCast => { - fcx.type_error_message(self.span, |actual| { - format!("casting `{}` as `{}` is invalid", - actual, - fcx.ty_to_string(self.cast_ty)) - }, self.expr_ty); + fcx.type_error_message(self.span, + |actual| { + format!("casting `{}` as `{}` is invalid", + actual, + fcx.ty_to_string(self.cast_ty)) + }, + self.expr_ty); } CastError::SizedUnsizedCast => { - fcx.type_error_message(self.span, |actual| { - format!("cannot cast thin pointer `{}` to fat pointer `{}`", - actual, - fcx.ty_to_string(self.cast_ty)) - }, self.expr_ty) + fcx.type_error_message(self.span, + |actual| { + format!("cannot cast thin pointer `{}` to fat pointer \ + `{}`", + actual, + fcx.ty_to_string(self.cast_ty)) + }, + self.expr_ty) } CastError::DifferingKinds => { - fcx.type_error_struct(self.span, |actual| { - format!("casting `{}` as `{}` is invalid", - actual, - fcx.ty_to_string(self.cast_ty)) - }, self.expr_ty) + fcx.type_error_struct(self.span, + |actual| { + format!("casting `{}` as `{}` is invalid", + actual, + fcx.ty_to_string(self.cast_ty)) + }, + self.expr_ty) .note("vtable kinds may not match") .emit(); } @@ -204,22 +217,22 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> { } fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) { - if - self.cast_ty.references_error() || - self.expr_ty.references_error() - { + if self.cast_ty.references_error() || self.expr_ty.references_error() { return; } let tstr = fcx.ty_to_string(self.cast_ty); - let mut err = fcx.type_error_struct(self.span, |actual| { - format!("cast to unsized type: `{}` as `{}`", actual, tstr) - }, self.expr_ty); + let mut err = + fcx.type_error_struct(self.span, + |actual| { + format!("cast to unsized type: `{}` as `{}`", actual, tstr) + }, + self.expr_ty); match self.expr_ty.sty { ty::TyRef(_, ty::TypeAndMut { mutbl: mt, .. }) => { let mtstr = match mt { hir::MutMutable => "mut ", - hir::MutImmutable => "" + hir::MutImmutable => "", }; if self.cast_ty.is_trait() { match fcx.tcx.sess.codemap().span_to_snippet(self.cast_span) { @@ -227,15 +240,17 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> { err.span_suggestion(self.cast_span, "try casting to a reference instead:", format!("&{}{}", mtstr, s)); - }, - Err(_) => - span_help!(err, self.cast_span, - "did you mean `&{}{}`?", mtstr, tstr), + } + Err(_) => { + span_help!(err, self.cast_span, "did you mean `&{}{}`?", mtstr, tstr) + } } } else { - span_help!(err, self.span, + span_help!(err, + self.span, "consider using an implicit coercion to `&{}{}` instead", - mtstr, tstr); + mtstr, + tstr); } } ty::TyBox(..) => { @@ -244,13 +259,13 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> { err.span_suggestion(self.cast_span, "try casting to a `Box` instead:", format!("Box<{}>", s)); - }, - Err(_) => - span_help!(err, self.cast_span, "did you mean `Box<{}>`?", tstr), + } + Err(_) => span_help!(err, self.cast_span, "did you mean `Box<{}>`?", tstr), } } _ => { - span_help!(err, self.expr.span, + span_help!(err, + self.expr.span, "consider using a box or reference as appropriate"); } } @@ -286,7 +301,9 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> { self.expr_ty = fcx.structurally_resolved_type(self.span, self.expr_ty); self.cast_ty = fcx.structurally_resolved_type(self.span, self.cast_ty); - debug!("check_cast({}, {:?} as {:?})", self.expr.id, self.expr_ty, + debug!("check_cast({}, {:?} as {:?})", + self.expr.id, + self.expr_ty, self.cast_ty); if !fcx.type_is_known_to_be_sized(self.cast_ty, self.span) { @@ -296,15 +313,16 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> { } else if self.try_coercion_cast(fcx) { self.trivial_cast_lint(fcx); debug!(" -> CoercionCast"); - fcx.tcx.cast_kinds.borrow_mut().insert(self.expr.id, - CastKind::CoercionCast); - } else { match self.do_check(fcx) { - Ok(k) => { - debug!(" -> {:?}", k); - fcx.tcx.cast_kinds.borrow_mut().insert(self.expr.id, k); - } - Err(e) => self.report_cast_error(fcx, e) - };} + fcx.tcx.cast_kinds.borrow_mut().insert(self.expr.id, CastKind::CoercionCast); + } else { + match self.do_check(fcx) { + Ok(k) => { + debug!(" -> {:?}", k); + fcx.tcx.cast_kinds.borrow_mut().insert(self.expr.id, k); + } + Err(e) => self.report_cast_error(fcx, e), + }; + } } /// Check a cast, and report an error if one exists. In some cases, this @@ -330,9 +348,7 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> { return Err(CastError::NonScalar); } } - _ => { - return Err(CastError::NonScalar) - } + _ => return Err(CastError::NonScalar), }; match (t_from, t_cast) { @@ -347,17 +363,20 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> { (_, Int(Char)) => Err(CastError::CastToChar), // prim -> float,ptr - (Int(Bool), Float) | (Int(CEnum), Float) | (Int(Char), Float) - => Err(CastError::NeedViaInt), - (Int(Bool), Ptr(_)) | (Int(CEnum), Ptr(_)) | (Int(Char), Ptr(_)) - => Err(CastError::NeedViaUsize), + (Int(Bool), Float) | + (Int(CEnum), Float) | + (Int(Char), Float) => Err(CastError::NeedViaInt), + (Int(Bool), Ptr(_)) | + (Int(CEnum), Ptr(_)) | + (Int(Char), Ptr(_)) => Err(CastError::NeedViaUsize), // ptr -> * (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast (Ptr(m_expr), Int(_)) => self.check_ptr_addr_cast(fcx, m_expr), // ptr-addr-cast (Ptr(_), Float) | (FnPtr, Float) => Err(CastError::NeedViaUsize), (FnPtr, Int(_)) => Ok(CastKind::FnPtrAddrCast), - (RPtr(_), Int(_)) | (RPtr(_), Float) => Err(CastError::NeedViaPtr), + (RPtr(_), Int(_)) | + (RPtr(_), Float) => Err(CastError::NeedViaPtr), // * -> ptr (Int(_), Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt), // addr-ptr-cast (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt), @@ -366,12 +385,12 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> { // prim -> prim (Int(CEnum), Int(_)) => Ok(CastKind::EnumCast), - (Int(Char), Int(_)) | (Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast), + (Int(Char), Int(_)) | + (Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast), - (Int(_), Int(_)) | - (Int(_), Float) | - (Float, Int(_)) | - (Float, Float) => Ok(CastKind::NumericCast), + (Int(_), Int(_)) | (Int(_), Float) | (Float, Int(_)) | (Float, Float) => { + Ok(CastKind::NumericCast) + } } } @@ -380,10 +399,8 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> { fcx: &FnCtxt<'a, 'gcx, 'tcx>, m_expr: &'tcx ty::TypeAndMut<'tcx>, m_cast: &'tcx ty::TypeAndMut<'tcx>) - -> Result - { - debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", - m_expr, m_cast); + -> Result { + debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast); // ptr-ptr cast. vtables must match. // Cast to sized is OK @@ -399,15 +416,14 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> { // vtable kinds must match match (fcx.unsize_kind(m_cast.ty), fcx.unsize_kind(m_expr.ty)) { (Some(a), Some(b)) if a == b => Ok(CastKind::PtrPtrCast), - _ => Err(CastError::DifferingKinds) + _ => Err(CastError::DifferingKinds), } } fn check_fptr_ptr_cast(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>, m_cast: &'tcx ty::TypeAndMut<'tcx>) - -> Result - { + -> Result { // fptr-ptr cast. must be to sized ptr if fcx.type_is_known_to_be_sized(m_cast.ty, self.span) { @@ -420,8 +436,7 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> { fn check_ptr_addr_cast(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>, m_expr: &'tcx ty::TypeAndMut<'tcx>) - -> Result - { + -> Result { // ptr-addr cast. must be from sized ptr if fcx.type_is_known_to_be_sized(m_expr.ty, self.span) { @@ -435,8 +450,7 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> { fcx: &FnCtxt<'a, 'gcx, 'tcx>, m_expr: &'tcx ty::TypeAndMut<'tcx>, m_cast: &'tcx ty::TypeAndMut<'tcx>) - -> Result - { + -> Result { // array-ptr-cast. if m_expr.mutbl == hir::MutImmutable && m_cast.mutbl == hir::MutImmutable { @@ -460,28 +474,22 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> { fn check_addr_ptr_cast(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>, m_cast: &'tcx ty::TypeAndMut<'tcx>) - -> Result - { + -> Result { // ptr-addr cast. pointer must be thin. if fcx.type_is_known_to_be_sized(m_cast.ty, self.span) { - Ok(CastKind::AddrPtrCast) + Ok(CastKind::AddrPtrCast) } else { - Err(CastError::IllegalCast) + Err(CastError::IllegalCast) } } fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> bool { fcx.try_coerce(self.expr, self.expr_ty, self.cast_ty).is_ok() } - } impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { - fn type_is_known_to_be_sized(&self, - ty: Ty<'tcx>, - span: Span) - -> bool - { + fn type_is_known_to_be_sized(&self, ty: Ty<'tcx>, span: Span) -> bool { traits::type_known_to_meet_builtin_bound(self, ty, ty::BoundSized, span) } } diff --git a/src/librustc_typeck/check/closure.rs b/src/librustc_typeck/check/closure.rs index 9e41d1b5676e4..1dbd0728bf217 100644 --- a/src/librustc_typeck/check/closure.rs +++ b/src/librustc_typeck/check/closure.rs @@ -24,7 +24,8 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { _capture: hir::CaptureClause, decl: &'gcx hir::FnDecl, body: &'gcx hir::Block, - expected: Expectation<'tcx>) -> Ty<'tcx> { + expected: Expectation<'tcx>) + -> Ty<'tcx> { debug!("check_expr_closure(expr={:?},expected={:?})", expr, expected); @@ -32,9 +33,9 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // It's always helpful for inference if we know the kind of // closure sooner rather than later, so first examine the expected // type, and see if can glean a closure kind from there. - let (expected_sig,expected_kind) = match expected.to_option(self) { + let (expected_sig, expected_kind) = match expected.to_option(self) { Some(ty) => self.deduce_expectations_from_expected_type(ty), - None => (None, None) + None => (None, None), }; self.check_closure(expr, expected_kind, decl, body, expected_sig) } @@ -44,7 +45,8 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { opt_kind: Option, decl: &'gcx hir::FnDecl, body: &'gcx hir::Block, - expected_sig: Option>) -> Ty<'tcx> { + expected_sig: Option>) + -> Ty<'tcx> { let expr_def_id = self.tcx.map.local_def_id(expr.id); debug!("check_closure opt_kind={:?} expected_sig={:?}", @@ -64,18 +66,25 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { let upvar_tys = self.next_ty_vars(num_upvars); debug!("check_closure: expr.id={:?} upvar_tys={:?}", - expr.id, upvar_tys); + expr.id, + upvar_tys); let closure_type = self.tcx.mk_closure(expr_def_id, - self.parameter_environment.free_substs, - upvar_tys); - - let fn_sig = self.tcx.liberate_late_bound_regions( - self.tcx.region_maps.call_site_extent(expr.id, body.id), &fn_ty.sig); - let fn_sig = - (**self).normalize_associated_types_in(body.span, body.id, &fn_sig); - - check_fn(self, hir::Unsafety::Normal, expr.id, &fn_sig, decl, expr.id, &body); + self.parameter_environment.free_substs, + upvar_tys); + + let fn_sig = self.tcx + .liberate_late_bound_regions(self.tcx.region_maps.call_site_extent(expr.id, body.id), + &fn_ty.sig); + let fn_sig = (**self).normalize_associated_types_in(body.span, body.id, &fn_sig); + + check_fn(self, + hir::Unsafety::Normal, + expr.id, + &fn_sig, + decl, + expr.id, + &body); // Tuple up the arguments and insert the resulting function type into // the `closures` table. @@ -88,46 +97,47 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { self.tables.borrow_mut().closure_tys.insert(expr_def_id, fn_ty); match opt_kind { - Some(kind) => { self.tables.borrow_mut().closure_kinds.insert(expr_def_id, kind); } - None => { } + Some(kind) => { + self.tables.borrow_mut().closure_kinds.insert(expr_def_id, kind); + } + None => {} } closure_type } - fn deduce_expectations_from_expected_type(&self, expected_ty: Ty<'tcx>) - -> (Option>,Option) - { + fn deduce_expectations_from_expected_type + (&self, + expected_ty: Ty<'tcx>) + -> (Option>, Option) { debug!("deduce_expectations_from_expected_type(expected_ty={:?})", expected_ty); match expected_ty.sty { ty::TyTrait(ref object_type) => { - let sig = object_type.projection_bounds.iter().filter_map(|pb| { - let pb = pb.with_self_ty(self.tcx, self.tcx.types.err); - self.deduce_sig_from_projection(&pb) - }).next(); + let sig = object_type.projection_bounds + .iter() + .filter_map(|pb| { + let pb = pb.with_self_ty(self.tcx, self.tcx.types.err); + self.deduce_sig_from_projection(&pb) + }) + .next(); let kind = self.tcx.lang_items.fn_trait_kind(object_type.principal.def_id()); (sig, kind) } - ty::TyInfer(ty::TyVar(vid)) => { - self.deduce_expectations_from_obligations(vid) - } - _ => { - (None, None) - } + ty::TyInfer(ty::TyVar(vid)) => self.deduce_expectations_from_obligations(vid), + _ => (None, None), } } - fn deduce_expectations_from_obligations(&self, expected_vid: ty::TyVid) - -> (Option>, Option) - { + fn deduce_expectations_from_obligations + (&self, + expected_vid: ty::TyVid) + -> (Option>, Option) { let fulfillment_cx = self.fulfillment_cx.borrow(); // Here `expected_ty` is known to be a type inference variable. - let expected_sig = - fulfillment_cx - .pending_obligations() + let expected_sig = fulfillment_cx.pending_obligations() .iter() .map(|obligation| &obligation.obligation) .filter_map(|obligation| { @@ -142,9 +152,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { self.self_type_matches_expected_vid(trait_ref, expected_vid) .and_then(|_| self.deduce_sig_from_projection(proj_predicate)) } - _ => { - None - } + _ => None, } }) .next(); @@ -153,9 +161,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // infer the kind. This can occur if there is a trait-reference // like `F : Fn`. Note that due to subtyping we could encounter // many viable options, so pick the most restrictive. - let expected_kind = - fulfillment_cx - .pending_obligations() + let expected_kind = fulfillment_cx.pending_obligations() .iter() .map(|obligation| &obligation.obligation) .filter_map(|obligation| { @@ -178,11 +184,11 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // inference variable. ty::Predicate::ClosureKind(..) => None, }; - opt_trait_ref - .and_then(|tr| self.self_type_matches_expected_vid(tr, expected_vid)) + opt_trait_ref.and_then(|tr| self.self_type_matches_expected_vid(tr, expected_vid)) .and_then(|tr| self.tcx.lang_items.fn_trait_kind(tr.def_id())) }) - .fold(None, |best, cur| Some(best.map_or(cur, |best| cmp::min(best, cur)))); + .fold(None, + |best, cur| Some(best.map_or(cur, |best| cmp::min(best, cur)))); (expected_sig, expected_kind) } @@ -190,13 +196,11 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { /// Given a projection like "::Result == Y", we can deduce /// everything we need to know about a closure. fn deduce_sig_from_projection(&self, - projection: &ty::PolyProjectionPredicate<'tcx>) - -> Option> - { + projection: &ty::PolyProjectionPredicate<'tcx>) + -> Option> { let tcx = self.tcx; - debug!("deduce_sig_from_projection({:?})", - projection); + debug!("deduce_sig_from_projection({:?})", projection); let trait_ref = projection.to_poly_trait_ref(); @@ -206,22 +210,26 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { let arg_param_ty = trait_ref.substs().type_at(1); let arg_param_ty = self.resolve_type_vars_if_possible(&arg_param_ty); - debug!("deduce_sig_from_projection: arg_param_ty {:?}", arg_param_ty); + debug!("deduce_sig_from_projection: arg_param_ty {:?}", + arg_param_ty); let input_tys = match arg_param_ty.sty { ty::TyTuple(tys) => tys.to_vec(), - _ => { return None; } + _ => { + return None; + } }; debug!("deduce_sig_from_projection: input_tys {:?}", input_tys); let ret_param_ty = projection.0.ty; let ret_param_ty = self.resolve_type_vars_if_possible(&ret_param_ty); - debug!("deduce_sig_from_projection: ret_param_ty {:?}", ret_param_ty); + debug!("deduce_sig_from_projection: ret_param_ty {:?}", + ret_param_ty); let fn_sig = ty::FnSig { inputs: input_tys, output: ret_param_ty, - variadic: false + variadic: false, }; debug!("deduce_sig_from_projection: fn_sig {:?}", fn_sig); @@ -229,10 +237,9 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } fn self_type_matches_expected_vid(&self, - trait_ref: ty::PolyTraitRef<'tcx>, - expected_vid: ty::TyVid) - -> Option> - { + trait_ref: ty::PolyTraitRef<'tcx>, + expected_vid: ty::TyVid) + -> Option> { let self_ty = self.shallow_resolve(trait_ref.self_ty()); debug!("self_type_matches_expected_vid(trait_ref={:?}, self_ty={:?})", trait_ref, diff --git a/src/librustc_typeck/check/coercion.rs b/src/librustc_typeck/check/coercion.rs index 98a05989b140d..5be77cb12e9ef 100644 --- a/src/librustc_typeck/check/coercion.rs +++ b/src/librustc_typeck/check/coercion.rs @@ -60,7 +60,7 @@ //! sort of a minor point so I've opted to leave it for later---after all //! we may want to adjust precisely when coercions occur. -use check::{FnCtxt}; +use check::FnCtxt; use rustc::hir; use rustc::infer::{Coercion, InferOk, TypeOrigin, TypeTrace}; @@ -79,7 +79,7 @@ use std::cell::RefCell; use std::collections::VecDeque; use std::ops::Deref; -struct Coerce<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { +struct Coerce<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> { fcx: &'a FnCtxt<'a, 'gcx, 'tcx>, origin: TypeOrigin, use_lub: bool, @@ -102,7 +102,7 @@ fn coerce_mutbls<'tcx>(from_mutbl: hir::Mutability, (hir::MutMutable, hir::MutMutable) | (hir::MutImmutable, hir::MutImmutable) | (hir::MutMutable, hir::MutImmutable) => Ok(()), - (hir::MutImmutable, hir::MutMutable) => Err(TypeError::Mutability) + (hir::MutImmutable, hir::MutMutable) => Err(TypeError::Mutability), } } @@ -112,7 +112,7 @@ impl<'f, 'gcx, 'tcx> Coerce<'f, 'gcx, 'tcx> { fcx: fcx, origin: origin, use_lub: false, - unsizing_obligations: RefCell::new(vec![]) + unsizing_obligations: RefCell::new(vec![]), } } @@ -144,21 +144,18 @@ impl<'f, 'gcx, 'tcx> Coerce<'f, 'gcx, 'tcx> { /// Synthesize an identity adjustment. fn identity(&self, ty: Ty<'tcx>) -> CoerceResult<'tcx> { - Ok((ty, AdjustDerefRef(AutoDerefRef { - autoderefs: 0, - autoref: None, - unsize: None - }))) + Ok((ty, + AdjustDerefRef(AutoDerefRef { + autoderefs: 0, + autoref: None, + unsize: None, + }))) } - fn coerce<'a, E, I>(&self, - exprs: &E, - a: Ty<'tcx>, - b: Ty<'tcx>) - -> CoerceResult<'tcx> - // FIXME(eddyb) use copyable iterators when that becomes ergonomic. + fn coerce<'a, E, I>(&self, exprs: &E, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> where E: Fn() -> I, - I: IntoIterator { + I: IntoIterator + { let a = self.shallow_resolve(a); debug!("Coerce.tys({:?} => {:?})", a, b); @@ -223,9 +220,8 @@ impl<'f, 'gcx, 'tcx> Coerce<'f, 'gcx, 'tcx> { r_b: &'tcx ty::Region, mt_b: TypeAndMut<'tcx>) -> CoerceResult<'tcx> - // FIXME(eddyb) use copyable iterators when that becomes ergonomic. where E: Fn() -> I, - I: IntoIterator + I: IntoIterator { debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b); @@ -241,7 +237,7 @@ impl<'f, 'gcx, 'tcx> Coerce<'f, 'gcx, 'tcx> { coerce_mutbls(mt_a.mutbl, mt_b.mutbl)?; (r_a, mt_a) } - _ => return self.unify_and_identity(a, b) + _ => return self.unify_and_identity(a, b), }; let span = self.origin.span(); @@ -255,7 +251,7 @@ impl<'f, 'gcx, 'tcx> Coerce<'f, 'gcx, 'tcx> { if autoderefs == 0 { // Don't let this pass, otherwise it would cause // &T to autoref to &&T. - continue + continue; } // At this point, we have deref'd `a` to `referent_ty`. So @@ -333,19 +329,24 @@ impl<'f, 'gcx, 'tcx> Coerce<'f, 'gcx, 'tcx> { } else if autoderefs == 1 { r_a // [3] above } else { - if r_borrow_var.is_none() { // create var lazilly, at most once + if r_borrow_var.is_none() { + // create var lazilly, at most once let coercion = Coercion(span); let r = self.next_region_var(coercion); r_borrow_var = Some(r); // [4] above } r_borrow_var.unwrap() }; - let derefd_ty_a = self.tcx.mk_ref(r, TypeAndMut { - ty: referent_ty, - mutbl: mt_b.mutbl // [1] above - }); + let derefd_ty_a = self.tcx.mk_ref(r, + TypeAndMut { + ty: referent_ty, + mutbl: mt_b.mutbl, // [1] above + }); match self.unify(derefd_ty_a, b) { - Ok(ty) => { success = Some((ty, autoderefs)); break }, + Ok(ty) => { + success = Some((ty, autoderefs)); + break; + } Err(err) => { if first_error.is_none() { first_error = Some(err); @@ -391,29 +392,27 @@ impl<'f, 'gcx, 'tcx> Coerce<'f, 'gcx, 'tcx> { } let r_borrow = match ty.sty { ty::TyRef(r_borrow, _) => r_borrow, - _ => span_bug!(span, "expected a ref type, got {:?}", ty) + _ => span_bug!(span, "expected a ref type, got {:?}", ty), }; let autoref = Some(AutoPtr(r_borrow, mt_b.mutbl)); debug!("coerce_borrowed_pointer: succeeded ty={:?} autoderefs={:?} autoref={:?}", - ty, autoderefs, autoref); - Ok((ty, AdjustDerefRef(AutoDerefRef { - autoderefs: autoderefs, - autoref: autoref, - unsize: None - }))) + ty, + autoderefs, + autoref); + Ok((ty, + AdjustDerefRef(AutoDerefRef { + autoderefs: autoderefs, + autoref: autoref, + unsize: None, + }))) } // &[T; n] or &mut [T; n] -> &[T] // or &mut [T; n] -> &mut [T] // or &Concrete -> &Trait, etc. - fn coerce_unsized(&self, - source: Ty<'tcx>, - target: Ty<'tcx>) - -> CoerceResult<'tcx> { - debug!("coerce_unsized(source={:?}, target={:?})", - source, - target); + fn coerce_unsized(&self, source: Ty<'tcx>, target: Ty<'tcx>) -> CoerceResult<'tcx> { + debug!("coerce_unsized(source={:?}, target={:?})", source, target); let traits = (self.tcx.lang_items.unsize_trait(), self.tcx.lang_items.coerce_unsized_trait()); @@ -442,7 +441,7 @@ impl<'f, 'gcx, 'tcx> Coerce<'f, 'gcx, 'tcx> { coerce_mutbls(mt_a.mutbl, mt_b.mutbl)?; (mt_a.ty, Some(AutoUnsafe(mt_b.mutbl))) } - _ => (source, None) + _ => (source, None), }; let source = source.adjust_for_autoref(self.tcx, reborrow); @@ -454,11 +453,8 @@ impl<'f, 'gcx, 'tcx> Coerce<'f, 'gcx, 'tcx> { // Create an obligation for `Source: CoerceUnsized`. let cause = ObligationCause::misc(self.origin.span(), self.body_id); - queue.push_back(self.tcx.predicate_for_trait_def(cause, - coerce_unsized_did, - 0, - source, - &[target])); + queue.push_back(self.tcx + .predicate_for_trait_def(cause, coerce_unsized_did, 0, source, &[target])); // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where @@ -466,10 +462,8 @@ impl<'f, 'gcx, 'tcx> Coerce<'f, 'gcx, 'tcx> { let traits = [coerce_unsized_did, unsize_did]; while let Some(obligation) = queue.pop_front() { debug!("coerce_unsized resolve step: {:?}", obligation); - let trait_ref = match obligation.predicate { - ty::Predicate::Trait(ref tr) if traits.contains(&tr.def_id()) => { - tr.clone() - } + let trait_ref = match obligation.predicate { + ty::Predicate::Trait(ref tr) if traits.contains(&tr.def_id()) => tr.clone(), _ => { leftover_predicates.push(obligation); continue; @@ -477,7 +471,8 @@ impl<'f, 'gcx, 'tcx> Coerce<'f, 'gcx, 'tcx> { }; match selcx.select(&obligation.with(trait_ref)) { // Uncertain or unimplemented. - Ok(None) | Err(traits::Unimplemented) => { + Ok(None) | + Err(traits::Unimplemented) => { debug!("coerce_unsized: early return - can't prove obligation"); return Err(TypeError::Mismatch); } @@ -503,22 +498,20 @@ impl<'f, 'gcx, 'tcx> Coerce<'f, 'gcx, 'tcx> { let adjustment = AutoDerefRef { autoderefs: if reborrow.is_some() { 1 } else { 0 }, autoref: reborrow, - unsize: Some(target) + unsize: Some(target), }; debug!("Success, coerced with {:?}", adjustment); Ok((target, AdjustDerefRef(adjustment))) } fn coerce_from_fn_pointer(&self, - a: Ty<'tcx>, - fn_ty_a: &'tcx ty::BareFnTy<'tcx>, - b: Ty<'tcx>) - -> CoerceResult<'tcx> - { - /*! - * Attempts to coerce from the type of a Rust function item - * into a closure or a `proc`. - */ + a: Ty<'tcx>, + fn_ty_a: &'tcx ty::BareFnTy<'tcx>, + b: Ty<'tcx>) + -> CoerceResult<'tcx> { + //! Attempts to coerce from the type of a Rust function item + //! into a closure or a `proc`. + //! let b = self.shallow_resolve(b); debug!("coerce_from_fn_pointer(a={:?}, b={:?})", a, b); @@ -527,9 +520,8 @@ impl<'f, 'gcx, 'tcx> Coerce<'f, 'gcx, 'tcx> { match (fn_ty_a.unsafety, fn_ty_b.unsafety) { (hir::Unsafety::Normal, hir::Unsafety::Unsafe) => { let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a); - return self.unify_and_identity(unsafe_a, b).map(|(ty, _)| { - (ty, AdjustUnsafeFnPointer) - }); + return self.unify_and_identity(unsafe_a, b) + .map(|(ty, _)| (ty, AdjustUnsafeFnPointer)); } _ => {} } @@ -542,10 +534,9 @@ impl<'f, 'gcx, 'tcx> Coerce<'f, 'gcx, 'tcx> { fn_ty_a: &'tcx ty::BareFnTy<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> { - /*! - * Attempts to coerce from the type of a Rust function item - * into a closure or a `proc`. - */ + //! Attempts to coerce from the type of a Rust function item + //! into a closure or a `proc`. + //! let b = self.shallow_resolve(b); debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b); @@ -553,11 +544,9 @@ impl<'f, 'gcx, 'tcx> Coerce<'f, 'gcx, 'tcx> { match b.sty { ty::TyFnPtr(_) => { let a_fn_pointer = self.tcx.mk_fn_ptr(fn_ty_a); - self.unify_and_identity(a_fn_pointer, b).map(|(ty, _)| { - (ty, AdjustReifyFnPointer) - }) + self.unify_and_identity(a_fn_pointer, b).map(|(ty, _)| (ty, AdjustReifyFnPointer)) } - _ => self.unify_and_identity(a, b) + _ => self.unify_and_identity(a, b), } } @@ -566,9 +555,7 @@ impl<'f, 'gcx, 'tcx> Coerce<'f, 'gcx, 'tcx> { b: Ty<'tcx>, mutbl_b: hir::Mutability) -> CoerceResult<'tcx> { - debug!("coerce_unsafe_ptr(a={:?}, b={:?})", - a, - b); + debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b); let (is_ref, mt_a) = match a.sty { ty::TyRef(_, mt) => (true, mt), @@ -579,24 +566,28 @@ impl<'f, 'gcx, 'tcx> Coerce<'f, 'gcx, 'tcx> { }; // Check that the types which they point at are compatible. - let a_unsafe = self.tcx.mk_ptr(ty::TypeAndMut{ mutbl: mutbl_b, ty: mt_a.ty }); + let a_unsafe = self.tcx.mk_ptr(ty::TypeAndMut { + mutbl: mutbl_b, + ty: mt_a.ty, + }); let (ty, noop) = self.unify_and_identity(a_unsafe, b)?; coerce_mutbls(mt_a.mutbl, mutbl_b)?; // Although references and unsafe ptrs have the same // representation, we still register an AutoDerefRef so that // regionck knows that the region for `a` must be valid here. - Ok((ty, if is_ref { - AdjustDerefRef(AutoDerefRef { - autoderefs: 1, - autoref: Some(AutoUnsafe(mutbl_b)), - unsize: None - }) - } else if mt_a.mutbl != mutbl_b { - AdjustMutToConstPointer - } else { - noop - })) + Ok((ty, + if is_ref { + AdjustDerefRef(AutoDerefRef { + autoderefs: 1, + autoref: Some(AutoUnsafe(mutbl_b)), + unsize: None, + }) + } else if mt_a.mutbl != mutbl_b { + AdjustMutToConstPointer + } else { + noop + })) } } @@ -606,7 +597,8 @@ fn apply<'a, 'b, 'gcx, 'tcx, E, I>(coerce: &mut Coerce<'a, 'gcx, 'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> where E: Fn() -> I, - I: IntoIterator { + I: IntoIterator +{ let (ty, adjustment) = indent(|| coerce.coerce(exprs, a, b))?; @@ -638,12 +630,12 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { let mut coerce = Coerce::new(self, TypeOrigin::ExprAssignable(expr.span)); self.commit_if_ok(|_| { - let (ty, adjustment) = - apply(&mut coerce, &|| Some(expr), source, target)?; + let (ty, adjustment) = apply(&mut coerce, &|| Some(expr), source, target)?; if !adjustment.is_identity() { debug!("Success, coerced with {:?}", adjustment); match self.tables.borrow().adjustments.get(&expr.id) { - None | Some(&AdjustNeverToAny(..)) => (), + None | + Some(&AdjustNeverToAny(..)) => (), _ => bug!("expr already has an adjustment on it!"), }; self.write_adjustment(expr.id, adjustment); @@ -662,9 +654,9 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { new: &'b hir::Expr, new_ty: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> - // FIXME(eddyb) use copyable iterators when that becomes ergonomic. where E: Fn() -> I, - I: IntoIterator { + I: IntoIterator + { let prev_ty = self.resolve_type_vars_with_obligations(prev_ty); let new_ty = self.resolve_type_vars_with_obligations(new_ty); @@ -675,8 +667,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // Special-case that coercion alone cannot handle: // Two function item types of differing IDs or Substs. match (&prev_ty.sty, &new_ty.sty) { - (&ty::TyFnDef(a_def_id, a_substs, a_fty), - &ty::TyFnDef(b_def_id, b_substs, b_fty)) => { + (&ty::TyFnDef(a_def_id, a_substs, a_fty), &ty::TyFnDef(b_def_id, b_substs, b_fty)) => { // The signature must always match. let fty = self.lub(true, trace.clone(), &a_fty, &b_fty) .map(|InferOk { value, obligations }| { @@ -720,9 +711,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // but only if the new expression has no coercion already applied to it. let mut first_error = None; if !self.tables.borrow().adjustments.contains_key(&new.id) { - let result = self.commit_if_ok(|_| { - apply(&mut coerce, &|| Some(new), new_ty, prev_ty) - }); + let result = self.commit_if_ok(|_| apply(&mut coerce, &|| Some(new), new_ty, prev_ty)); match result { Ok((ty, adjustment)) => { if !adjustment.is_identity() { @@ -730,7 +719,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } return Ok(ty); } - Err(e) => first_error = Some(e) + Err(e) => first_error = Some(e), } } @@ -739,20 +728,20 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // previous expressions, other than noop reborrows (ignoring lifetimes). for expr in exprs() { let noop = match self.tables.borrow().adjustments.get(&expr.id) { - Some(&AdjustDerefRef(AutoDerefRef { - autoderefs: 1, - autoref: Some(AutoPtr(_, mutbl_adj)), - unsize: None - })) => match self.node_ty(expr.id).sty { - ty::TyRef(_, mt_orig) => { - // Reborrow that we can safely ignore. - mutbl_adj == mt_orig.mutbl + Some(&AdjustDerefRef(AutoDerefRef { autoderefs: 1, + autoref: Some(AutoPtr(_, mutbl_adj)), + unsize: None })) => { + match self.node_ty(expr.id).sty { + ty::TyRef(_, mt_orig) => { + // Reborrow that we can safely ignore. + mutbl_adj == mt_orig.mutbl + } + _ => false, } - _ => false - }, + } Some(&AdjustNeverToAny(_)) => true, Some(_) => false, - None => true + None => true, }; if !noop { diff --git a/src/librustc_typeck/check/compare_method.rs b/src/librustc_typeck/check/compare_method.rs index 826a88127d84e..25e9f1f522c96 100644 --- a/src/librustc_typeck/check/compare_method.rs +++ b/src/librustc_typeck/check/compare_method.rs @@ -40,8 +40,7 @@ pub fn compare_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, trait_m: &ty::Method<'tcx>, impl_trait_ref: &ty::TraitRef<'tcx>, trait_item_span: Option) { - debug!("compare_impl_method(impl_trait_ref={:?})", - impl_trait_ref); + debug!("compare_impl_method(impl_trait_ref={:?})", impl_trait_ref); debug!("compare_impl_method: impl_trait_ref (liberated) = {:?}", impl_trait_ref); @@ -58,34 +57,36 @@ pub fn compare_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, // inscrutable, particularly for cases where one method has no // self. match (&trait_m.explicit_self, &impl_m.explicit_self) { - (&ty::ExplicitSelfCategory::Static, - &ty::ExplicitSelfCategory::Static) => {} + (&ty::ExplicitSelfCategory::Static, &ty::ExplicitSelfCategory::Static) => {} (&ty::ExplicitSelfCategory::Static, _) => { - let mut err = struct_span_err!(tcx.sess, impl_m_span, E0185, - "method `{}` has a `{}` declaration in the impl, \ - but not in the trait", - trait_m.name, - impl_m.explicit_self); - err.span_label(impl_m_span, &format!("`{}` used in impl", - impl_m.explicit_self)); + let mut err = struct_span_err!(tcx.sess, + impl_m_span, + E0185, + "method `{}` has a `{}` declaration in the impl, but \ + not in the trait", + trait_m.name, + impl_m.explicit_self); + err.span_label(impl_m_span, + &format!("`{}` used in impl", impl_m.explicit_self)); if let Some(span) = tcx.map.span_if_local(trait_m.def_id) { - err.span_label(span, &format!("trait declared without `{}`", - impl_m.explicit_self)); + err.span_label(span, + &format!("trait declared without `{}`", impl_m.explicit_self)); } err.emit(); return; } (_, &ty::ExplicitSelfCategory::Static) => { - let mut err = struct_span_err!(tcx.sess, impl_m_span, E0186, - "method `{}` has a `{}` declaration in the trait, \ - but not in the impl", - trait_m.name, - trait_m.explicit_self); - err.span_label(impl_m_span, &format!("expected `{}` in impl", - trait_m.explicit_self)); + let mut err = struct_span_err!(tcx.sess, + impl_m_span, + E0186, + "method `{}` has a `{}` declaration in the trait, but \ + not in the impl", + trait_m.name, + trait_m.explicit_self); + err.span_label(impl_m_span, + &format!("expected `{}` in impl", trait_m.explicit_self)); if let Some(span) = tcx.map.span_if_local(trait_m.def_id) { - err.span_label(span, & format!("`{}` used in trait", - trait_m.explicit_self)); + err.span_label(span, &format!("`{}` used in trait", trait_m.explicit_self)); } err.emit(); return; @@ -107,17 +108,23 @@ pub fn compare_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, impl_m_span } } - _ => bug!("{:?} is not a method", impl_m) + _ => bug!("{:?} is not a method", impl_m), }; - let mut err = struct_span_err!(tcx.sess, span, E0049, - "method `{}` has {} type parameter{} \ - but its trait declaration has {} type parameter{}", - trait_m.name, - num_impl_m_type_params, - if num_impl_m_type_params == 1 {""} else {"s"}, - num_trait_m_type_params, - if num_trait_m_type_params == 1 {""} else {"s"}); + let mut err = struct_span_err!(tcx.sess, + span, + E0049, + "method `{}` has {} type parameter{} but its trait \ + declaration has {} type parameter{}", + trait_m.name, + num_impl_m_type_params, + if num_impl_m_type_params == 1 { "" } else { "s" }, + num_trait_m_type_params, + if num_trait_m_type_params == 1 { + "" + } else { + "s" + }); let mut suffix = None; @@ -154,18 +161,17 @@ pub fn compare_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, let trait_span = if let Some(trait_id) = trait_m_node_id { match tcx.map.expect_trait_item(trait_id).node { TraitItem_::MethodTraitItem(ref trait_m_sig, _) => { - if let Some(arg) = trait_m_sig.decl.inputs.get( - if trait_number_args > 0 { - trait_number_args - 1 - } else { - 0 - }) { + if let Some(arg) = trait_m_sig.decl.inputs.get(if trait_number_args > 0 { + trait_number_args - 1 + } else { + 0 + }) { Some(arg.pat.span) } else { trait_item_span } } - _ => bug!("{:?} is not a method", impl_m) + _ => bug!("{:?} is not a method", impl_m), } } else { trait_item_span @@ -173,27 +179,28 @@ pub fn compare_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, let impl_m_node_id = tcx.map.as_local_node_id(impl_m.def_id).unwrap(); let impl_span = match tcx.map.expect_impl_item(impl_m_node_id).node { ImplItemKind::Method(ref impl_m_sig, _) => { - if let Some(arg) = impl_m_sig.decl.inputs.get( - if impl_number_args > 0 { - impl_number_args - 1 - } else { - 0 - }) { + if let Some(arg) = impl_m_sig.decl.inputs.get(if impl_number_args > 0 { + impl_number_args - 1 + } else { + 0 + }) { arg.pat.span } else { impl_m_span } } - _ => bug!("{:?} is not a method", impl_m) + _ => bug!("{:?} is not a method", impl_m), }; - let mut err = struct_span_err!(tcx.sess, impl_span, E0050, - "method `{}` has {} parameter{} \ - but the declaration in trait `{}` has {}", - trait_m.name, - impl_number_args, - if impl_number_args == 1 {""} else {"s"}, - tcx.item_path_str(trait_m.def_id), - trait_number_args); + let mut err = struct_span_err!(tcx.sess, + impl_span, + E0050, + "method `{}` has {} parameter{} but the declaration in \ + trait `{}` has {}", + trait_m.name, + impl_number_args, + if impl_number_args == 1 { "" } else { "s" }, + tcx.item_path_str(trait_m.def_id), + trait_number_args); if let Some(trait_span) = trait_span { err.span_label(trait_span, &format!("trait requires {}", @@ -210,7 +217,7 @@ pub fn compare_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, } else { format!("{} parameter", trait_number_args) }, - impl_number_args)); + impl_number_args)); err.emit(); return; } @@ -287,9 +294,10 @@ pub fn compare_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, let impl_to_skol_substs = &impl_param_env.free_substs; // Create mapping from trait to skolemized. - let trait_to_skol_substs = - impl_to_skol_substs.rebase_onto(tcx, impl_m.container_id(), - trait_to_impl_substs.subst(tcx, impl_to_skol_substs)); + let trait_to_skol_substs = impl_to_skol_substs.rebase_onto(tcx, + impl_m.container_id(), + trait_to_impl_substs.subst(tcx, + impl_to_skol_substs)); debug!("compare_impl_method: trait_to_skol_substs={:?}", trait_to_skol_substs); @@ -325,31 +333,28 @@ pub fn compare_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, // // We then register the obligations from the impl_m and check to see // if all constraints hold. - hybrid_preds.predicates.extend( - trait_m.predicates.instantiate_own(tcx, trait_to_skol_substs).predicates); + hybrid_preds.predicates + .extend(trait_m.predicates.instantiate_own(tcx, trait_to_skol_substs).predicates); // Construct trait parameter environment and then shift it into the skolemized viewpoint. // The key step here is to update the caller_bounds's predicates to be // the new hybrid bounds we computed. let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_body_id); let trait_param_env = impl_param_env.with_caller_bounds(hybrid_preds.predicates); - let trait_param_env = traits::normalize_param_env_or_error(tcx, - trait_param_env, - normalize_cause.clone()); + let trait_param_env = + traits::normalize_param_env_or_error(tcx, trait_param_env, normalize_cause.clone()); // FIXME(@jroesch) this seems ugly, but is a temporary change infcx.parameter_environment = trait_param_env; debug!("compare_impl_method: caller_bounds={:?}", - infcx.parameter_environment.caller_bounds); + infcx.parameter_environment.caller_bounds); let mut selcx = traits::SelectionContext::new(&infcx); let impl_m_own_bounds = impl_m.predicates.instantiate_own(tcx, impl_to_skol_substs); - let (impl_m_own_bounds, _) = - infcx.replace_late_bound_regions_with_fresh_var( - impl_m_span, - infer::HigherRankedType, - &ty::Binder(impl_m_own_bounds.predicates)); + let (impl_m_own_bounds, _) = infcx.replace_late_bound_regions_with_fresh_var(impl_m_span, + infer::HigherRankedType, + &ty::Binder(impl_m_own_bounds.predicates)); for predicate in impl_m_own_bounds { let traits::Normalized { value: predicate, .. } = traits::normalize(&mut selcx, normalize_cause.clone(), &predicate); @@ -357,7 +362,7 @@ pub fn compare_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, let cause = traits::ObligationCause { span: impl_m_span, body_id: impl_m_body_id, - code: traits::ObligationCauseCode::CompareImplMethodObligation + code: traits::ObligationCauseCode::CompareImplMethodObligation, }; fulfillment_cx.register_predicate_obligation( @@ -382,40 +387,34 @@ pub fn compare_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, let tcx = infcx.tcx; let origin = TypeOrigin::MethodCompatCheck(impl_m_span); - let (impl_sig, _) = - infcx.replace_late_bound_regions_with_fresh_var(impl_m_span, - infer::HigherRankedType, - &impl_m.fty.sig); - let impl_sig = - impl_sig.subst(tcx, impl_to_skol_substs); - let impl_sig = - assoc::normalize_associated_types_in(&infcx, - &mut fulfillment_cx, - impl_m_span, - impl_m_body_id, - &impl_sig); + let (impl_sig, _) = infcx.replace_late_bound_regions_with_fresh_var(impl_m_span, + infer::HigherRankedType, + &impl_m.fty.sig); + let impl_sig = impl_sig.subst(tcx, impl_to_skol_substs); + let impl_sig = assoc::normalize_associated_types_in(&infcx, + &mut fulfillment_cx, + impl_m_span, + impl_m_body_id, + &impl_sig); let impl_fty = tcx.mk_fn_ptr(tcx.mk_bare_fn(ty::BareFnTy { unsafety: impl_m.fty.unsafety, abi: impl_m.fty.abi, - sig: ty::Binder(impl_sig.clone()) + sig: ty::Binder(impl_sig.clone()), })); debug!("compare_impl_method: impl_fty={:?}", impl_fty); - let trait_sig = tcx.liberate_late_bound_regions( - infcx.parameter_environment.free_id_outlive, - &trait_m.fty.sig); - let trait_sig = - trait_sig.subst(tcx, trait_to_skol_substs); - let trait_sig = - assoc::normalize_associated_types_in(&infcx, - &mut fulfillment_cx, - impl_m_span, - impl_m_body_id, - &trait_sig); + let trait_sig = tcx.liberate_late_bound_regions(infcx.parameter_environment.free_id_outlive, + &trait_m.fty.sig); + let trait_sig = trait_sig.subst(tcx, trait_to_skol_substs); + let trait_sig = assoc::normalize_associated_types_in(&infcx, + &mut fulfillment_cx, + impl_m_span, + impl_m_body_id, + &trait_sig); let trait_fty = tcx.mk_fn_ptr(tcx.mk_bare_fn(ty::BareFnTy { unsafety: trait_m.fty.unsafety, abi: trait_m.fty.abi, - sig: ty::Binder(trait_sig.clone()) + sig: ty::Binder(trait_sig.clone()), })); debug!("compare_impl_method: trait_fty={:?}", trait_fty); @@ -425,36 +424,39 @@ pub fn compare_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, impl_fty, trait_fty); - let (impl_err_span, trait_err_span) = - extract_spans_for_error_reporting(&infcx, &terr, origin, impl_m, - impl_sig, trait_m, trait_sig); + let (impl_err_span, trait_err_span) = extract_spans_for_error_reporting(&infcx, + &terr, + origin, + impl_m, + impl_sig, + trait_m, + trait_sig); let origin = TypeOrigin::MethodCompatCheck(impl_err_span); - let mut diag = struct_span_err!( - tcx.sess, origin.span(), E0053, - "method `{}` has an incompatible type for trait", trait_m.name - ); - - infcx.note_type_err( - &mut diag, - origin, - trait_err_span.map(|sp| (sp, format!("type in trait"))), - Some(infer::ValuePairs::Types(ExpectedFound { - expected: trait_fty, - found: impl_fty - })), - &terr - ); + let mut diag = struct_span_err!(tcx.sess, + origin.span(), + E0053, + "method `{}` has an incompatible type for trait", + trait_m.name); + + infcx.note_type_err(&mut diag, + origin, + trait_err_span.map(|sp| (sp, format!("type in trait"))), + Some(infer::ValuePairs::Types(ExpectedFound { + expected: trait_fty, + found: impl_fty, + })), + &terr); diag.emit(); - return + return; } // Check that all obligations are satisfied by the implementation's // version. if let Err(ref errors) = fulfillment_cx.select_all_or_error(&infcx) { infcx.report_fulfillment_errors(errors); - return + return; } // Finally, resolve all regions. This catches wily misuses of @@ -480,8 +482,7 @@ pub fn compare_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, impl_generics: &ty::Generics<'tcx>, trait_to_skol_substs: &Substs<'tcx>, impl_to_skol_substs: &Substs<'tcx>) - -> bool - { + -> bool { let trait_params = &trait_generics.regions[..]; let impl_params = &impl_generics.regions[..]; @@ -506,9 +507,12 @@ pub fn compare_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, // are zero. Since I don't quite know how to phrase things at // the moment, give a kind of vague error message. if trait_params.len() != impl_params.len() { - struct_span_err!(ccx.tcx.sess, span, E0195, - "lifetime parameters or bounds on method `{}` do \ - not match the trait declaration",impl_m.name) + struct_span_err!(ccx.tcx.sess, + span, + E0195, + "lifetime parameters or bounds on method `{}` do not match the \ + trait declaration", + impl_m.name) .span_label(span, &format!("lifetimes do not match trait")) .emit(); return false; @@ -524,40 +528,51 @@ pub fn compare_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, impl_sig: ty::FnSig<'tcx>, trait_m: &ty::Method, trait_sig: ty::FnSig<'tcx>) - -> (Span, Option) { + -> (Span, Option) { let tcx = infcx.tcx; let impl_m_node_id = tcx.map.as_local_node_id(impl_m.def_id).unwrap(); let (impl_m_output, impl_m_iter) = match tcx.map.expect_impl_item(impl_m_node_id).node { - ImplItemKind::Method(ref impl_m_sig, _) => - (&impl_m_sig.decl.output, impl_m_sig.decl.inputs.iter()), - _ => bug!("{:?} is not a method", impl_m) + ImplItemKind::Method(ref impl_m_sig, _) => { + (&impl_m_sig.decl.output, impl_m_sig.decl.inputs.iter()) + } + _ => bug!("{:?} is not a method", impl_m), }; match *terr { TypeError::Mutability => { if let Some(trait_m_node_id) = tcx.map.as_local_node_id(trait_m.def_id) { let trait_m_iter = match tcx.map.expect_trait_item(trait_m_node_id).node { - TraitItem_::MethodTraitItem(ref trait_m_sig, _) => - trait_m_sig.decl.inputs.iter(), - _ => bug!("{:?} is not a MethodTraitItem", trait_m) + TraitItem_::MethodTraitItem(ref trait_m_sig, _) => { + trait_m_sig.decl.inputs.iter() + } + _ => bug!("{:?} is not a MethodTraitItem", trait_m), }; - impl_m_iter.zip(trait_m_iter).find(|&(ref impl_arg, ref trait_arg)| { - match (&impl_arg.ty.node, &trait_arg.ty.node) { - (&Ty_::TyRptr(_, ref impl_mt), &Ty_::TyRptr(_, ref trait_mt)) | - (&Ty_::TyPtr(ref impl_mt), &Ty_::TyPtr(ref trait_mt)) => - impl_mt.mutbl != trait_mt.mutbl, - _ => false - } - }).map(|(ref impl_arg, ref trait_arg)| { - match (impl_arg.to_self(), trait_arg.to_self()) { - (Some(impl_self), Some(trait_self)) => - (impl_self.span, Some(trait_self.span)), - (None, None) => (impl_arg.ty.span, Some(trait_arg.ty.span)), - _ => bug!("impl and trait fns have different first args, \ - impl: {:?}, trait: {:?}", impl_arg, trait_arg) - } - }).unwrap_or((origin.span(), tcx.map.span_if_local(trait_m.def_id))) + impl_m_iter.zip(trait_m_iter) + .find(|&(ref impl_arg, ref trait_arg)| { + match (&impl_arg.ty.node, &trait_arg.ty.node) { + (&Ty_::TyRptr(_, ref impl_mt), &Ty_::TyRptr(_, ref trait_mt)) | + (&Ty_::TyPtr(ref impl_mt), &Ty_::TyPtr(ref trait_mt)) => { + impl_mt.mutbl != trait_mt.mutbl + } + _ => false, + } + }) + .map(|(ref impl_arg, ref trait_arg)| { + match (impl_arg.to_self(), trait_arg.to_self()) { + (Some(impl_self), Some(trait_self)) => { + (impl_self.span, Some(trait_self.span)) + } + (None, None) => (impl_arg.ty.span, Some(trait_arg.ty.span)), + _ => { + bug!("impl and trait fns have different first args, impl: \ + {:?}, trait: {:?}", + impl_arg, + trait_arg) + } + } + }) + .unwrap_or((origin.span(), tcx.map.span_if_local(trait_m.def_id))) } else { (origin.span(), tcx.map.span_if_local(trait_m.def_id)) } @@ -565,25 +580,28 @@ pub fn compare_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, TypeError::Sorts(ExpectedFound { .. }) => { if let Some(trait_m_node_id) = tcx.map.as_local_node_id(trait_m.def_id) { let (trait_m_output, trait_m_iter) = - match tcx.map.expect_trait_item(trait_m_node_id).node { - TraitItem_::MethodTraitItem(ref trait_m_sig, _) => - (&trait_m_sig.decl.output, trait_m_sig.decl.inputs.iter()), - _ => bug!("{:?} is not a MethodTraitItem", trait_m) - }; + match tcx.map.expect_trait_item(trait_m_node_id).node { + TraitItem_::MethodTraitItem(ref trait_m_sig, _) => { + (&trait_m_sig.decl.output, trait_m_sig.decl.inputs.iter()) + } + _ => bug!("{:?} is not a MethodTraitItem", trait_m), + }; let impl_iter = impl_sig.inputs.iter(); let trait_iter = trait_sig.inputs.iter(); - impl_iter.zip(trait_iter).zip(impl_m_iter).zip(trait_m_iter) + impl_iter.zip(trait_iter) + .zip(impl_m_iter) + .zip(trait_m_iter) .filter_map(|(((impl_arg_ty, trait_arg_ty), impl_arg), trait_arg)| { match infcx.sub_types(true, origin, trait_arg_ty, impl_arg_ty) { Ok(_) => None, - Err(_) => Some((impl_arg.ty.span, Some(trait_arg.ty.span))) + Err(_) => Some((impl_arg.ty.span, Some(trait_arg.ty.span))), } }) .next() .unwrap_or_else(|| { - if infcx.sub_types(false, origin, impl_sig.output, - trait_sig.output).is_err() { + if infcx.sub_types(false, origin, impl_sig.output, trait_sig.output) + .is_err() { (impl_m_output.span(), Some(trait_m_output.span())) } else { (origin.span(), tcx.map.span_if_local(trait_m.def_id)) @@ -593,7 +611,7 @@ pub fn compare_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, (origin.span(), tcx.map.span_if_local(trait_m.def_id)) } } - _ => (origin.span(), tcx.map.span_if_local(trait_m.def_id)) + _ => (origin.span(), tcx.map.span_if_local(trait_m.def_id)), } } } @@ -603,8 +621,7 @@ pub fn compare_const_impl<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, impl_c_span: Span, trait_c: &ty::AssociatedConst<'tcx>, impl_trait_ref: &ty::TraitRef<'tcx>) { - debug!("compare_const_impl(impl_trait_ref={:?})", - impl_trait_ref); + debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref); let tcx = ccx.tcx; tcx.infer_ctxt(None, None, Reveal::NotSpecializable).enter(|infcx| { @@ -626,11 +643,12 @@ pub fn compare_const_impl<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, let impl_to_skol_substs = &impl_param_env.free_substs; // Create mapping from trait to skolemized. - let trait_to_skol_substs = - impl_to_skol_substs.rebase_onto(tcx, impl_c.container.id(), - trait_to_impl_substs.subst(tcx, impl_to_skol_substs)); + let trait_to_skol_substs = impl_to_skol_substs.rebase_onto(tcx, + impl_c.container.id(), + trait_to_impl_substs.subst(tcx, + impl_to_skol_substs)); debug!("compare_const_impl: trait_to_skol_substs={:?}", - trait_to_skol_substs); + trait_to_skol_substs); // Compute skolemized form of impl and trait const tys. let impl_ty = impl_c.ty.subst(tcx, impl_to_skol_substs); @@ -639,31 +657,27 @@ pub fn compare_const_impl<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, let err = infcx.commit_if_ok(|_| { // There is no "body" here, so just pass dummy id. - let impl_ty = - assoc::normalize_associated_types_in(&infcx, - &mut fulfillment_cx, - impl_c_span, - ast::CRATE_NODE_ID, - &impl_ty); - - debug!("compare_const_impl: impl_ty={:?}", - impl_ty); - - let trait_ty = - assoc::normalize_associated_types_in(&infcx, - &mut fulfillment_cx, - impl_c_span, - ast::CRATE_NODE_ID, - &trait_ty); - - debug!("compare_const_impl: trait_ty={:?}", - trait_ty); + let impl_ty = assoc::normalize_associated_types_in(&infcx, + &mut fulfillment_cx, + impl_c_span, + ast::CRATE_NODE_ID, + &impl_ty); + + debug!("compare_const_impl: impl_ty={:?}", impl_ty); + + let trait_ty = assoc::normalize_associated_types_in(&infcx, + &mut fulfillment_cx, + impl_c_span, + ast::CRATE_NODE_ID, + &trait_ty); + + debug!("compare_const_impl: trait_ty={:?}", trait_ty); infcx.sub_types(false, origin, impl_ty, trait_ty) - .map(|InferOk { obligations, .. }| { - // FIXME(#32730) propagate obligations - assert!(obligations.is_empty()) - }) + .map(|InferOk { obligations, .. }| { + // FIXME(#32730) propagate obligations + assert!(obligations.is_empty()) + }) }); if let Err(terr) = err { @@ -674,31 +688,31 @@ pub fn compare_const_impl<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, // Locate the Span containing just the type of the offending impl match tcx.map.expect_impl_item(impl_c_node_id).node { ImplItemKind::Const(ref ty, _) => origin = TypeOrigin::Misc(ty.span), - _ => bug!("{:?} is not a impl const", impl_c) + _ => bug!("{:?} is not a impl const", impl_c), } - let mut diag = struct_span_err!( - tcx.sess, origin.span(), E0326, - "implemented const `{}` has an incompatible type for trait", - trait_c.name - ); + let mut diag = struct_span_err!(tcx.sess, + origin.span(), + E0326, + "implemented const `{}` has an incompatible type for \ + trait", + trait_c.name); // Add a label to the Span containing just the type of the item let trait_c_node_id = tcx.map.as_local_node_id(trait_c.def_id).unwrap(); let trait_c_span = match tcx.map.expect_trait_item(trait_c_node_id).node { TraitItem_::ConstTraitItem(ref ty, _) => ty.span, - _ => bug!("{:?} is not a trait const", trait_c) + _ => bug!("{:?} is not a trait const", trait_c), }; - infcx.note_type_err( - &mut diag, - origin, - Some((trait_c_span, format!("type in trait"))), - Some(infer::ValuePairs::Types(ExpectedFound { - expected: trait_ty, - found: impl_ty - })), &terr - ); + infcx.note_type_err(&mut diag, + origin, + Some((trait_c_span, format!("type in trait"))), + Some(infer::ValuePairs::Types(ExpectedFound { + expected: trait_ty, + found: impl_ty, + })), + &terr); diag.emit(); } });