diff --git a/src/librustc_typeck/check/_match.rs b/src/librustc_typeck/check/_match.rs index 0430585fe6d0b..9d597f58226a7 100644 --- a/src/librustc_typeck/check/_match.rs +++ b/src/librustc_typeck/check/_match.rs @@ -13,8 +13,8 @@ use rustc::infer::{self, InferOk, TypeOrigin}; use hir::pat_util::{PatIdMap, pat_id_map}; use hir::pat_util::{EnumerateAndAdjustIterator, pat_is_resolved_const}; use rustc::ty::subst::Substs; -use rustc::ty::{self, Ty, TypeFoldable, LvaluePreference}; -use check::{FnCtxt, Expectation}; +use rustc::ty::{self, LvaluePreference, Ty, TypeFoldable}; +use check::{Expectation, FnCtxt}; use lint; use util::nodemap::FnvHashMap; use session::Session; @@ -29,7 +29,7 @@ use syntax::ptr::P; use rustc::hir::{self, PatKind}; use rustc::hir::print as pprust; -pub struct PatCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { +pub struct PatCtxt<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> { pub fcx: &'a FnCtxt<'a, 'gcx, 'tcx>, pub map: PatIdMap, } @@ -78,7 +78,7 @@ impl<'a, 'gcx, 'tcx> PatCtxt<'a, 'gcx, 'tcx> { if let ty::TyRef(_, mt) = expected_ty.sty { if let ty::TySlice(_) = mt.ty.sty { pat_ty = tcx.mk_imm_ref(tcx.mk_region(ty::ReStatic), - tcx.mk_slice(tcx.types.u8)) + tcx.mk_slice(tcx.types.u8)) } } } @@ -122,17 +122,20 @@ impl<'a, 'gcx, 'tcx> PatCtxt<'a, 'gcx, 'tcx> { }; // Note: spacing here is intentional, we want a space before "start" and "end". - span_err!(tcx.sess, span, E0029, + span_err!(tcx.sess, + span, + E0029, "only char and numeric types are allowed in range patterns\n \ start type: {}\n end type: {}", self.ty_to_string(lhs_ty), - self.ty_to_string(rhs_ty) - ); + self.ty_to_string(rhs_ty)); return; } // Check that the types of the end-points can be unified. - let types_unify = self.require_same_types(pat.span, rhs_ty, lhs_ty, + let types_unify = self.require_same_types(pat.span, + rhs_ty, + lhs_ty, "mismatched types in range"); // It's ok to return without a message as `require_same_types` prints an error. @@ -178,7 +181,10 @@ impl<'a, 'gcx, 'tcx> PatCtxt<'a, 'gcx, 'tcx> { // then `x` is assigned a value of type `&M T` where M is the mutability // and T is the expected type. let region_var = self.next_region_var(infer::PatternRegion(pat.span)); - let mt = ty::TypeAndMut { ty: expected, mutbl: mutbl }; + let mt = ty::TypeAndMut { + ty: expected, + mutbl: mutbl, + }; let region_ty = tcx.mk_ref(tcx.mk_region(region_var), mt); // `x` is assigned a value of type `&M T`, hence `&M T <: typeof(x)` is @@ -229,21 +235,28 @@ impl<'a, 'gcx, 'tcx> PatCtxt<'a, 'gcx, 'tcx> { let sentinel = self.tcx.map.local_def_id(ast::CRATE_NODE_ID); def::PathResolution { base_def: Def::Mod(sentinel), - depth: path.segments.len() + depth: path.segments.len(), } } else { debug!("unbound path {:?}", pat); self.write_error(pat.id); return; }; - if let Some((opt_ty, segments, def)) = - self.resolve_ty_and_def_ufcs(path_res, Some(self_ty), - path, pat.span, pat.id) { + if let Some((opt_ty, segments, def)) = self.resolve_ty_and_def_ufcs(path_res, + Some(self_ty), + path, + pat.span, + pat.id) { if self.check_assoc_item_is_const(def, pat.span) { let scheme = tcx.lookup_item_type(def.def_id()); let predicates = tcx.lookup_predicates(def.def_id()); - self.instantiate_path(segments, scheme, &predicates, - opt_ty, def, pat.span, pat.id); + self.instantiate_path(segments, + scheme, + &predicates, + opt_ty, + def, + pat.span, + pat.id); let const_ty = self.node_ty(pat.id); self.demand_suptype(pat.span, expected, const_ty); } else { @@ -258,14 +271,15 @@ impl<'a, 'gcx, 'tcx> PatCtxt<'a, 'gcx, 'tcx> { let mut expected_len = elements.len(); if ddpos.is_some() { // Require known type only when `..` is present - if let ty::TyTuple(ref tys) = - self.structurally_resolved_type(pat.span, expected).sty { + if let ty::TyTuple(ref tys) = self.structurally_resolved_type(pat.span, + expected) + .sty { expected_len = tys.len(); } } let max_len = cmp::max(expected_len, elements.len()); - let element_tys: Vec<_> = (0 .. max_len).map(|_| self.next_ty_var()).collect(); + let element_tys: Vec<_> = (0..max_len).map(|_| self.next_ty_var()).collect(); let pat_ty = tcx.mk_tup(element_tys.clone()); self.write_ty(pat.id, pat_ty); self.demand_eqtype(pat.span, expected, pat_ty); @@ -301,12 +315,13 @@ impl<'a, 'gcx, 'tcx> PatCtxt<'a, 'gcx, 'tcx> { // also helps with the bad interactions of the given // hack detailed in (*) below. let (rptr_ty, inner_ty) = match expected.sty { - ty::TyRef(_, mt) if mt.mutbl == mutbl => { - (expected, mt.ty) - } + ty::TyRef(_, mt) if mt.mutbl == mutbl => (expected, mt.ty), _ => { let inner_ty = self.next_ty_var(); - let mt = ty::TypeAndMut { ty: inner_ty, mutbl: mutbl }; + let mt = ty::TypeAndMut { + ty: inner_ty, + mutbl: mutbl, + }; let region = self.next_region_var(infer::PatternRegion(pat.span)); let rptr_ty = tcx.mk_ref(tcx.mk_region(region), mt); self.demand_eqtype(pat.span, expected, rptr_ty); @@ -328,27 +343,34 @@ impl<'a, 'gcx, 'tcx> PatCtxt<'a, 'gcx, 'tcx> { let min_len = before.len() + after.len(); if slice.is_none() { if min_len != size { - span_err!(tcx.sess, pat.span, E0527, + span_err!(tcx.sess, + pat.span, + E0527, "pattern requires {} elements but array has {}", - min_len, size); + min_len, + size); } (inner_ty, tcx.types.err) } else if let Some(rest) = size.checked_sub(min_len) { (inner_ty, tcx.mk_array(inner_ty, rest)) } else { - span_err!(tcx.sess, pat.span, E0528, + span_err!(tcx.sess, + pat.span, + E0528, "pattern requires at least {} elements but array has {}", - min_len, size); + min_len, + size); (inner_ty, tcx.types.err) } } ty::TySlice(inner_ty) => (inner_ty, expected_ty), _ => { if !expected_ty.references_error() { - let mut err = struct_span_err!( - tcx.sess, pat.span, E0529, - "expected an array or slice, found `{}`", - expected_ty); + let mut err = struct_span_err!(tcx.sess, + pat.span, + E0529, + "expected an array or slice, found `{}`", + expected_ty); if let ty::TyRef(_, ty::TypeAndMut { mutbl: _, ty }) = expected_ty.sty { match ty.sty { ty::TyArray(..) | ty::TySlice(..) => { @@ -433,7 +455,9 @@ impl<'a, 'gcx, 'tcx> PatCtxt<'a, 'gcx, 'tcx> { match def { Def::AssociatedConst(..) => true, Def::Method(..) => { - span_err!(self.tcx.sess, span, E0327, + span_err!(self.tcx.sess, + span, + E0327, "associated items in match patterns must be constants"); false } @@ -449,10 +473,12 @@ impl<'a, 'gcx, 'tcx> PatCtxt<'a, 'gcx, 'tcx> { if let ty::TyTrait(..) = mt.ty.sty { // This is "x = SomeTrait" being reduced from // "let &x = &SomeTrait" or "let box x = Box", an error. - span_err!(self.tcx.sess, span, E0033, + span_err!(self.tcx.sess, + span, + E0033, "type `{}` cannot be dereferenced", self.ty_to_string(expected)); - return false + return false; } } } @@ -474,9 +500,11 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // supertype, as the "discriminant type" (issue #23116). let contains_ref_bindings = arms.iter() .filter_map(|a| tcx.arm_contains_ref_binding(a)) - .max_by_key(|m| match *m { - hir::MutMutable => 1, - hir::MutImmutable => 0, + .max_by_key(|m| { + match *m { + hir::MutMutable => 1, + hir::MutImmutable => 0, + } }); let discrim_ty; if let Some(m) = contains_ref_bindings { @@ -519,10 +547,8 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // us to give better error messages (pointing to a usually better // arm for inconsistent arms or to the whole match when a `()` type // is required). - Expectation::ExpectHasType(ety) if ety != self.tcx.mk_nil() => { - ety - } - _ => result_ty + Expectation::ExpectHasType(ety) if ety != self.tcx.mk_nil() => ety, + _ => result_ty, }; for (i, arm) in arms.iter().enumerate() { if let Some(ref e) = arm.guard { @@ -541,7 +567,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { hir::MatchSource::IfLetDesugar { contains_else_clause: false } => { i == arms.len() - 1 && arm_ty.is_nil() } - _ => false + _ => false, }; let origin = if is_if_let_fallback { @@ -584,9 +610,12 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } impl<'a, 'gcx, 'tcx> PatCtxt<'a, 'gcx, 'tcx> { - pub fn check_pat_struct(&self, pat: &'gcx hir::Pat, - path: &hir::Path, fields: &'gcx [Spanned], - etc: bool, expected: Ty<'tcx>) { + pub fn check_pat_struct(&self, + pat: &'gcx hir::Pat, + path: &hir::Path, + fields: &'gcx [Spanned], + etc: bool, + expected: Ty<'tcx>) { let tcx = self.tcx; let def = tcx.def_map.borrow().get(&pat.id).unwrap().full_def(); @@ -594,8 +623,11 @@ impl<'a, 'gcx, 'tcx> PatCtxt<'a, 'gcx, 'tcx> { Some((_, variant)) => variant, None => { let name = pprust::path_to_string(path); - span_err!(tcx.sess, pat.span, E0163, - "`{}` does not name a struct or a struct variant", name); + span_err!(tcx.sess, + pat.span, + E0163, + "`{}` does not name a struct or a struct variant", + name); self.write_error(pat.id); for field in fields { @@ -608,15 +640,13 @@ impl<'a, 'gcx, 'tcx> PatCtxt<'a, 'gcx, 'tcx> { let pat_ty = self.instantiate_type(def.def_id(), path); let item_substs = match pat_ty.sty { ty::TyStruct(_, substs) | ty::TyEnum(_, substs) => substs, - _ => span_bug!(pat.span, "struct variant is not an ADT") + _ => span_bug!(pat.span, "struct variant is not an ADT"), }; self.demand_eqtype(pat.span, expected, pat_ty); self.check_struct_pat_fields(pat.span, fields, variant, &item_substs, etc); self.write_ty(pat.id, pat_ty); - self.write_substs(pat.id, ty::ItemSubsts { - substs: item_substs - }); + self.write_substs(pat.id, ty::ItemSubsts { substs: item_substs }); } fn check_pat_enum(&self, @@ -625,8 +655,7 @@ impl<'a, 'gcx, 'tcx> PatCtxt<'a, 'gcx, 'tcx> { subpats: &'gcx [P], ddpos: Option, expected: Ty<'tcx>, - is_tuple_struct_pat: bool) - { + is_tuple_struct_pat: bool) { // Typecheck the path. let tcx = self.tcx; @@ -644,12 +673,16 @@ impl<'a, 'gcx, 'tcx> PatCtxt<'a, 'gcx, 'tcx> { }; let (opt_ty, segments, def) = match self.resolve_ty_and_def_ufcs(path_res, - None, path, - pat.span, pat.id) { + None, + path, + pat.span, + pat.id) { Some(resolution) => resolution, // Error handling done inside resolve_ty_and_def_ufcs, so if // resolution fails just return. - None => {return;} + None => { + return; + } }; // Items that were partially resolved before should have been resolved to @@ -660,7 +693,7 @@ impl<'a, 'gcx, 'tcx> PatCtxt<'a, 'gcx, 'tcx> { } let enum_def = def.variant_def_ids() - .map_or_else(|| def.def_id(), |(enum_def, _)| enum_def); + .map_or_else(|| def.def_id(), |(enum_def, _)| enum_def); let ctor_scheme = tcx.lookup_item_type(enum_def); let ctor_predicates = tcx.lookup_predicates(enum_def); @@ -673,11 +706,18 @@ impl<'a, 'gcx, 'tcx> PatCtxt<'a, 'gcx, 'tcx> { } else { ctor_scheme }; - self.instantiate_path(segments, path_scheme, &ctor_predicates, - opt_ty, def, pat.span, pat.id); + self.instantiate_path(segments, + path_scheme, + &ctor_predicates, + opt_ty, + def, + pat.span, + pat.id); let report_bad_struct_kind = |is_warning| { bad_struct_kind_err(tcx.sess, pat, path, is_warning); - if is_warning { return; } + if is_warning { + return; + } self.write_error(pat.id); for pat in subpats { self.check_pat(&pat, tcx.types.err); @@ -726,23 +766,35 @@ impl<'a, 'gcx, 'tcx> PatCtxt<'a, 'gcx, 'tcx> { (false, ty::VariantKind::Tuple) | (_, ty::VariantKind::Struct) => { report_bad_struct_kind(false); - return + return; } _ => {} } if subpats.len() == variant.fields.len() || - subpats.len() < variant.fields.len() && ddpos.is_some() { + subpats.len() < variant.fields.len() && ddpos.is_some() { for (i, subpat) in subpats.iter().enumerate_and_adjust(variant.fields.len(), ddpos) { let field_ty = self.field_ty(subpat.span, &variant.fields[i], expected_substs); self.check_pat(&subpat, field_ty); } } else { - span_err!(tcx.sess, pat.span, E0023, + span_err!(tcx.sess, + pat.span, + E0023, "this pattern has {} field{}, but the corresponding {} has {} field{}", - subpats.len(), if subpats.len() == 1 {""} else {"s"}, + subpats.len(), + if subpats.len() == 1 { + "" + } else { + "s" + }, kind_name, - variant.fields.len(), if variant.fields.len() == 1 {""} else {"s"}); + variant.fields.len(), + if variant.fields.len() == 1 { + "" + } else { + "s" + }); for pat in subpats { self.check_pat(&pat, tcx.types.err); @@ -765,9 +817,9 @@ impl<'a, 'gcx, 'tcx> PatCtxt<'a, 'gcx, 'tcx> { // Index the struct fields' types. let field_map = variant.fields - .iter() - .map(|field| (field.name, field)) - .collect::>(); + .iter() + .map(|field| (field.name, field)) + .collect::>(); // Keep track of which fields have already appeared in the pattern. let mut used_fields = FnvHashMap(); @@ -776,11 +828,14 @@ impl<'a, 'gcx, 'tcx> PatCtxt<'a, 'gcx, 'tcx> { for &Spanned { node: ref field, span } in fields { let field_ty = match used_fields.entry(field.name) { Occupied(occupied) => { - let mut err = struct_span_err!(tcx.sess, span, E0025, + let mut err = struct_span_err!(tcx.sess, + span, + E0025, "field `{}` bound multiple times \ in the pattern", field.name); - span_note!(&mut err, *occupied.get(), + span_note!(&mut err, + *occupied.get(), "field `{}` previously bound here", field.name); err.emit(); @@ -789,14 +844,16 @@ impl<'a, 'gcx, 'tcx> PatCtxt<'a, 'gcx, 'tcx> { Vacant(vacant) => { vacant.insert(span); field_map.get(&field.name) - .map(|f| self.field_ty(span, f, substs)) - .unwrap_or_else(|| { - span_err!(tcx.sess, span, E0026, - "struct `{}` does not have a field named `{}`", - tcx.item_path_str(variant.did), - field.name); - tcx.types.err - }) + .map(|f| self.field_ty(span, f, substs)) + .unwrap_or_else(|| { + span_err!(tcx.sess, + span, + E0026, + "struct `{}` does not have a field named `{}`", + tcx.item_path_str(variant.did), + field.name); + tcx.types.err + }) } }; @@ -806,11 +863,13 @@ impl<'a, 'gcx, 'tcx> PatCtxt<'a, 'gcx, 'tcx> { // Report an error if not all the fields were specified. if !etc { for field in variant.fields - .iter() - .filter(|field| !used_fields.contains_key(&field.name)) { - span_err!(tcx.sess, span, E0027, - "pattern does not mention field `{}`", - field.name); + .iter() + .filter(|field| !used_fields.contains_key(&field.name)) { + span_err!(tcx.sess, + span, + E0027, + "pattern does not mention field `{}`", + field.name); } } } diff --git a/src/librustc_typeck/check/assoc.rs b/src/librustc_typeck/check/assoc.rs index 04b0248ccdac2..db51577170e6e 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, MiscObligation, Normalized, ObligationCause, + SelectionContext}; use rustc::ty::fold::TypeFoldable; use syntax::ast; use syntax::codemap::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 9e2b7cd034652..3c5101daa4a97 100644 --- a/src/librustc_typeck/check/autoderef.rs +++ b/src/librustc_typeck/check/autoderef.rs @@ -13,7 +13,7 @@ use astconv::AstConv; use super::FnCtxt; use rustc::traits; -use rustc::ty::{self, Ty, TraitRef}; +use rustc::ty::{self, TraitRef, Ty}; use rustc::ty::{ToPredicate, TypeFoldable}; use rustc::ty::{MethodCall, MethodCallee}; use rustc::ty::subst::Substs; @@ -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,7 +55,9 @@ 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. - span_err!(tcx.sess, self.span, E0055, + span_err!(tcx.sess, + self.span, + E0055, "reached the recursion limit while auto-dereferencing {:?}", self.cur_ty); return None; @@ -70,7 +73,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, } }; @@ -79,8 +82,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())) @@ -97,9 +102,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: tcx.mk_substs(Substs::new_trait(vec![], vec![], self.cur_ty)) + substs: tcx.mk_substs(Substs::new_trait(vec![], vec![], self.cur_ty)), }; let cause = traits::ObligationCause::misc(self.span, self.fcx.body_id); @@ -111,15 +116,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); @@ -132,17 +135,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(); - - debug!("finalize({:?}) - {:?},{:?}", pref, methods, self.obligations); + 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); for expr in exprs { debug!("finalize - finalizing #{} - {:?}", expr.id, expr); @@ -161,18 +170,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, } } @@ -181,28 +186,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 417b2fafecfd3..690f6f95e428c 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 middle::cstore::LOCAL_CRATE; @@ -45,10 +44,12 @@ pub fn check_legal_trait_for_method_call(ccx: &CrateCtxt, span: Span, trait_id: } else if did == li.fn_once_trait() { "call_once" } else { - return // not a closure method, everything is OK. + return; // not a closure method, everything is OK. }; - struct_span_err!(tcx.sess, span, E0174, + struct_span_err!(tcx.sess, + span, + E0174, "explicit use of unboxed closure method `{}` is experimental", method) .help("add `#![feature(unboxed_closures)]` to the crate \ @@ -60,7 +61,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> { @@ -68,15 +69,16 @@ 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>) - { + expected: Expectation<'tcx>) { self.check_expr(callee_expr); let original_callee_ty = self.expr_ty(callee_expr); let mut autoderef = self.autoderef(callee_expr.span, original_callee_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)); @@ -95,8 +97,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); } } } @@ -106,8 +111,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, @@ -127,20 +131,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)); } } @@ -169,14 +173,14 @@ 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, @@ -204,19 +208,20 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { call_expr: &hir::Expr, callee_ty: Ty<'tcx>, arg_exprs: &'gcx [P], - expected: Expectation<'tcx>) - { + expected: Expectation<'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, None); + let mut err = self.type_error_struct(call_expr.span, + |actual| { + format!("expected function, found `{}`", + actual) + }, + callee_ty, + None); if let hir::ExprCall(ref expr, _) = call_expr.node { let tcx = self.tcx; @@ -237,7 +242,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { error_fn_sig = ty::Binder(ty::FnSig { inputs: self.err_args(arg_exprs.len()), output: ty::FnConverging(self.tcx.types.err), - variadic: false + variadic: false, }); &error_fn_sig @@ -249,12 +254,11 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // renormalize the associated types at this point, since they // 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); + 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); // Call the generic checker. let expected_arg_tys = self.expected_types_for_fn_args(call_expr.span, @@ -275,18 +279,16 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { call_expr: &hir::Expr, arg_exprs: &'gcx [P], expected: Expectation<'tcx>, - fn_sig: ty::FnSig<'tcx>) - { + fn_sig: ty::FnSig<'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, @@ -303,15 +305,13 @@ 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>) - { - 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>) { + let output_type = self.check_method_argument_types(call_expr.span, + method_callee.ty, + callee_expr, + arg_exprs, + TupleArgumentsFlag::TupleArguments, + expected); self.write_call(call_expr, output_type); self.write_overloaded_call_method_map(call_expr, method_callee); @@ -337,16 +337,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 @@ -356,15 +357,15 @@ 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) - { + for (&method_arg_ty, &self_arg_ty) in method_sig.inputs[1..] + .iter() + .zip(&self.fn_sig.inputs) { fcx.demand_eqtype(self.call_expr.span, self_arg_ty, method_arg_ty); } @@ -376,9 +377,8 @@ impl<'gcx, 'tcx> DeferredCallResolution<'gcx, 'tcx> for CallResolution<'gcx, 'tc 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 690250edb8cb4..3f6c00fcea2a6 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,19 +143,23 @@ 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, None) - .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(); + fcx.type_error_struct(self.span, + |actual| { + format!("casting `{}` as `{}` is invalid", + actual, + fcx.ty_to_string(self.cast_ty)) + }, + self.expr_ty, + None) + .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 => { struct_span_err!(fcx.tcx.sess, self.span, E0054, "cannot cast as `bool`") @@ -165,23 +167,33 @@ 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, None); + fcx.type_error_message(self.span, + |actual| { + format!("only `u8` can be cast as `char`, not `{}`", + actual) + }, + self.expr_ty, + None); } 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, None); + fcx.type_error_message(self.span, + |actual| { + format!("non-scalar cast: `{}` as `{}`", + actual, + fcx.ty_to_string(self.cast_ty)) + }, + self.expr_ty, + None); } 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, None); + fcx.type_error_message(self.span, + |actual| { + format!("casting `{}` as `{}` is invalid", + actual, + fcx.ty_to_string(self.cast_ty)) + }, + self.expr_ty, + None); } CastError::SizedUnsizedCast => { fcx.type_error_message(self.span, |actual| { @@ -191,34 +203,39 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> { }, self.expr_ty, None) } 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, None) - .note("vtable kinds may not match") - .emit(); + fcx.type_error_struct(self.span, + |actual| { + format!("casting `{}` as `{}` is invalid", + actual, + fcx.ty_to_string(self.cast_ty)) + }, + self.expr_ty, + None) + .note("vtable kinds may not match") + .emit(); } } } 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, None); + let mut err = fcx.type_error_struct(self.span, + |actual| { + format!("cast to unsized type: `{}` as `{}`", + actual, + tstr) + }, + self.expr_ty, + None); 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) { @@ -226,15 +243,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(..) => { @@ -243,13 +262,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"); } } @@ -285,7 +304,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) { @@ -295,15 +316,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 @@ -329,9 +351,7 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> { return Err(CastError::NonScalar); } } - _ => { - return Err(CastError::NonScalar) - } + _ => return Err(CastError::NonScalar), }; match (t_from, t_cast) { @@ -346,10 +366,12 @@ 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 @@ -379,10 +401,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 @@ -398,15 +418,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) { @@ -419,8 +438,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) { @@ -434,8 +452,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 { @@ -459,29 +476,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.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 d3396eb4c1baf..ef79ca137eac2 100644 --- a/src/librustc_typeck/check/closure.rs +++ b/src/librustc_typeck/check/closure.rs @@ -10,7 +10,7 @@ //! Code for type-checking closure expressions. -use super::{check_fn, Expectation, FnCtxt}; +use super::{Expectation, FnCtxt, check_fn}; use astconv::AstConv; use rustc::ty::subst; @@ -33,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) } @@ -65,18 +65,27 @@ 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); + self.parameter_environment.free_substs, + upvar_tys); self.write_ty(expr.id, closure_type); - 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.tcx.liberate_late_bound_regions(self.tcx + .region_maps + .call_site_extent(expr.id, body.id), + &fn_ty.sig); - check_fn(self, hir::Unsafety::Normal, expr.id, &fn_sig, decl, expr.id, &body); + 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. @@ -89,14 +98,17 @@ 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 => {} } } - 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); @@ -110,18 +122,15 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { 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. @@ -154,36 +163,41 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // 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() - .iter() - .map(|obligation| &obligation.obligation) - .filter_map(|obligation| { - let opt_trait_ref = match obligation.predicate { - ty::Predicate::Projection(ref data) => Some(data.to_poly_trait_ref()), - ty::Predicate::Trait(ref data) => Some(data.to_poly_trait_ref()), - ty::Predicate::Equate(..) => None, - ty::Predicate::RegionOutlives(..) => None, - ty::Predicate::TypeOutlives(..) => None, - ty::Predicate::WellFormed(..) => None, - ty::Predicate::ObjectSafe(..) => None, - ty::Predicate::Rfc1592(..) => None, - - // NB: This predicate is created by breaking down a - // `ClosureType: FnFoo()` predicate, where - // `ClosureType` represents some `TyClosure`. It can't - // possibly be referring to the current closure, - // because we haven't produced the `TyClosure` for - // this closure yet; this is exactly why the other - // code is looking for a self type of a unresolved - // inference variable. - ty::Predicate::ClosureKind(..) => None, - }; - 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)))); + fulfillment_cx.pending_obligations() + .iter() + .map(|obligation| &obligation.obligation) + .filter_map(|obligation| { + let opt_trait_ref = match obligation.predicate { + ty::Predicate::Projection(ref data) => { + Some(data.to_poly_trait_ref()) + } + ty::Predicate::Trait(ref data) => Some(data.to_poly_trait_ref()), + ty::Predicate::Equate(..) => None, + ty::Predicate::RegionOutlives(..) => None, + ty::Predicate::TypeOutlives(..) => None, + ty::Predicate::WellFormed(..) => None, + ty::Predicate::ObjectSafe(..) => None, + ty::Predicate::Rfc1592(..) => None, + + // NB: This predicate is created by breaking down a + // `ClosureType: FnFoo()` predicate, where + // `ClosureType` represents some `TyClosure`. It can't + // possibly be referring to the current closure, + // because we haven't produced the `TyClosure` for + // this closure yet; this is exactly why the other + // code is looking for a self type of a unresolved + // inference variable. + ty::Predicate::ClosureKind(..) => None, + }; + 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)))); (expected_sig, expected_kind) } @@ -191,13 +205,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(); @@ -207,22 +219,26 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { let arg_param_ty = *trait_ref.substs().types.get(subst::TypeSpace, 0); 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: ty::FnConverging(ret_param_ty), - variadic: false + variadic: false, }; debug!("deduce_sig_from_projection: fn_sig {:?}", fn_sig); @@ -230,10 +246,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/compare_method.rs b/src/librustc_typeck/check/compare_method.rs index 20f82271b9cd6..51ff892fa2ece 100644 --- a/src/librustc_typeck/check/compare_method.rs +++ b/src/librustc_typeck/check/compare_method.rs @@ -37,8 +37,7 @@ pub fn compare_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, impl_m_body_id: ast::NodeId, trait_m: &ty::Method<'tcx>, impl_trait_ref: &ty::TraitRef<'tcx>) { - 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); @@ -55,22 +54,25 @@ 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, _) => { - span_err!(tcx.sess, impl_m_span, E0185, - "method `{}` has a `{}` declaration in the impl, \ + 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); + trait_m.name, + impl_m.explicit_self); return; } (_, &ty::ExplicitSelfCategory::Static) => { - span_err!(tcx.sess, impl_m_span, E0186, - "method `{}` has a `{}` declaration in the trait, \ + 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); + trait_m.name, + trait_m.explicit_self); return; } _ => { @@ -81,26 +83,42 @@ pub fn compare_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, let num_impl_m_type_params = impl_m.generics.types.len(subst::FnSpace); let num_trait_m_type_params = trait_m.generics.types.len(subst::FnSpace); if num_impl_m_type_params != num_trait_m_type_params { - span_err!(tcx.sess, impl_m_span, E0049, - "method `{}` has {} type parameter{} \ + span_err!(tcx.sess, + impl_m_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"}); + 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" + }); return; } if impl_m.fty.sig.0.inputs.len() != trait_m.fty.sig.0.inputs.len() { - span_err!(tcx.sess, impl_m_span, E0050, - "method `{}` has {} parameter{} \ + span_err!(tcx.sess, + impl_m_span, + E0050, + "method `{}` has {} parameter{} \ but the declaration in trait `{}` has {}", - trait_m.name, - impl_m.fty.sig.0.inputs.len(), - if impl_m.fty.sig.0.inputs.len() == 1 {""} else {"s"}, - tcx.item_path_str(trait_m.def_id), - trait_m.fty.sig.0.inputs.len()); + trait_m.name, + impl_m.fty.sig.0.inputs.len(), + if impl_m.fty.sig.0.inputs.len() == 1 { + "" + } else { + "s" + }, + tcx.item_path_str(trait_m.def_id), + trait_m.fty.sig.0.inputs.len()); return; } @@ -177,10 +195,14 @@ pub fn compare_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, // Create mapping from trait to skolemized. let trait_to_skol_substs = - trait_to_impl_substs - .subst(tcx, impl_to_skol_substs).clone() - .with_method(impl_to_skol_substs.types.get_slice(subst::FnSpace).to_vec(), - impl_to_skol_substs.regions.get_slice(subst::FnSpace).to_vec()); + trait_to_impl_substs.subst(tcx, impl_to_skol_substs) + .clone() + .with_method(impl_to_skol_substs.types + .get_slice(subst::FnSpace) + .to_vec(), + impl_to_skol_substs.regions + .get_slice(subst::FnSpace) + .to_vec()); debug!("compare_impl_method: trait_to_skol_substs={:?}", trait_to_skol_substs); @@ -207,8 +229,7 @@ pub fn compare_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, // environment. We can't just use `impl_env.caller_bounds`, // however, because we want to replace all late-bound regions with // region variables. - let impl_bounds = - impl_m.predicates.instantiate(tcx, impl_to_skol_substs); + let impl_bounds = impl_m.predicates.instantiate(tcx, impl_to_skol_substs); debug!("compare_impl_method: impl_bounds={:?}", impl_bounds); @@ -223,11 +244,7 @@ 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. - let hybrid_preds = VecPerParamSpace::new( - impl_pred.types, - impl_pred.selfs, - trait_pred.fns - ); + let hybrid_preds = VecPerParamSpace::new(impl_pred.types, impl_pred.selfs, trait_pred.fns); // 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 @@ -241,15 +258,14 @@ pub fn compare_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, infcx.parameter_environment = trait_param_env; debug!("compare_impl_method: trait_bounds={:?}", - infcx.parameter_environment.caller_bounds); + infcx.parameter_environment.caller_bounds); let mut selcx = traits::SelectionContext::new(&infcx); let (impl_pred_fns, _) = - infcx.replace_late_bound_regions_with_fresh_var( - impl_m_span, - infer::HigherRankedType, - &ty::Binder(impl_pred.fns)); + infcx.replace_late_bound_regions_with_fresh_var(impl_m_span, + infer::HigherRankedType, + &ty::Binder(impl_pred.fns)); for predicate in impl_pred_fns { let traits::Normalized { value: predicate, .. } = traits::normalize(&mut selcx, normalize_cause.clone(), &predicate); @@ -257,12 +273,11 @@ 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( - &infcx, - traits::Obligation::new(cause, predicate)); + fulfillment_cx.register_predicate_obligation(&infcx, + traits::Obligation::new(cause, predicate)); } // We now need to check that the signature of the impl method is @@ -286,36 +301,32 @@ pub fn compare_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, 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 = 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) + sig: ty::Binder(impl_sig), })); 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) + sig: ty::Binder(trait_sig), })); debug!("compare_impl_method: trait_fty={:?}", trait_fty); @@ -324,18 +335,20 @@ pub fn compare_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, debug!("sub_types failed: impl ty {:?}, trait ty {:?}", impl_fty, trait_fty); - span_err!(tcx.sess, impl_m_span, E0053, + span_err!(tcx.sess, + impl_m_span, + E0053, "method `{}` has an incompatible type for trait: {}", trait_m.name, terr); - 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 @@ -348,8 +361,8 @@ pub fn compare_impl_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, // anyway, so it shouldn't be needed there either. Anyway, we can // always add more relations later (it's backwards compat). let mut free_regions = FreeRegionMap::new(); - free_regions.relate_free_regions_from_predicates( - &infcx.parameter_environment.caller_bounds); + free_regions.relate_free_regions_from_predicates(&infcx.parameter_environment + .caller_bounds); infcx.resolve_regions_and_report_errors(&free_regions, impl_m_body_id); }); @@ -361,8 +374,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.get_slice(subst::FnSpace); let impl_params = impl_generics.regions.get_slice(subst::FnSpace); @@ -387,10 +399,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() { - span_err!(ccx.tcx.sess, span, E0195, - "lifetime parameters or bounds on method `{}` do \ + span_err!(ccx.tcx.sess, + span, + E0195, + "lifetime parameters or bounds on method `{}` do \ not match the trait declaration", - impl_m.name); + impl_m.name); return false; } @@ -403,8 +417,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, ProjectionMode::AnyFinal).enter(|infcx| { @@ -427,12 +440,16 @@ pub fn compare_const_impl<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, // Create mapping from trait to skolemized. let trait_to_skol_substs = - trait_to_impl_substs - .subst(tcx, impl_to_skol_substs).clone() - .with_method(impl_to_skol_substs.types.get_slice(subst::FnSpace).to_vec(), - impl_to_skol_substs.regions.get_slice(subst::FnSpace).to_vec()); + trait_to_impl_substs.subst(tcx, impl_to_skol_substs) + .clone() + .with_method(impl_to_skol_substs.types + .get_slice(subst::FnSpace) + .to_vec(), + impl_to_skol_substs.regions + .get_slice(subst::FnSpace) + .to_vec()); 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); @@ -442,38 +459,36 @@ pub fn compare_const_impl<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, let origin = TypeOrigin::Misc(impl_c_span); // 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, - 0, - &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, - 0, - &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, + 0, + &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, + 0, + &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()) - }) + // FIXME(#32730) propagate obligations + assert!(obligations.is_empty()) + }) }); if let Err(terr) = err { debug!("checking associated const for compatibility: impl ty {:?}, trait ty {:?}", impl_ty, trait_ty); - span_err!(tcx.sess, impl_c_span, E0326, + span_err!(tcx.sess, + impl_c_span, + E0326, "implemented const `{}` has an incompatible type for \ trait: {}", trait_c.name, diff --git a/src/librustc_typeck/check/demand.rs b/src/librustc_typeck/check/demand.rs index 7c8eb62b0e749..00c46fcccd33c 100644 --- a/src/librustc_typeck/check/demand.rs +++ b/src/librustc_typeck/check/demand.rs @@ -25,7 +25,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { Ok(InferOk { obligations, .. }) => { // FIXME(#32730) propagate obligations assert!(obligations.is_empty()); - }, + } Err(e) => { self.report_mismatched_types(origin, expected, actual, e); } @@ -38,7 +38,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { Ok(InferOk { obligations, .. }) => { // FIXME(#32730) propagate obligations assert!(obligations.is_empty()); - }, + } Err(e) => { self.report_mismatched_types(origin, expected, actual, e); } @@ -55,8 +55,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } } - pub fn require_same_types(&self, span: Span, t1: Ty<'tcx>, t2: Ty<'tcx>, msg: &str) - -> bool { + pub fn require_same_types(&self, span: Span, t1: Ty<'tcx>, t2: Ty<'tcx>, msg: &str) -> bool { if let Err(err) = self.eq_types(false, TypeOrigin::Misc(span), t1, t2) { let found_ty = self.resolve_type_vars_if_possible(&t1); let expected_ty = self.resolve_type_vars_if_possible(&t2); diff --git a/src/librustc_typeck/check/intrinsic.rs b/src/librustc_typeck/check/intrinsic.rs index f120e38630b8a..20ee337874965 100644 --- a/src/librustc_typeck/check/intrinsic.rs +++ b/src/librustc_typeck/check/intrinsic.rs @@ -17,7 +17,7 @@ use rustc::ty::FnSig; use rustc::ty::{self, Ty}; use {CrateCtxt, require_same_types}; -use std::collections::{HashMap}; +use std::collections::HashMap; use syntax::abi::Abi; use syntax::ast; use syntax::codemap::Span; @@ -38,28 +38,28 @@ fn equate_intrinsic_type<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, let mut substs = Substs::empty(); substs.types = i_ty.generics.types.map(|def| tcx.mk_param_from_def(def)); - let fty = tcx.mk_fn_def(def_id, tcx.mk_substs(substs), + let fty = tcx.mk_fn_def(def_id, + tcx.mk_substs(substs), tcx.mk_bare_fn(ty::BareFnTy { - unsafety: hir::Unsafety::Unsafe, - abi: abi, - sig: ty::Binder(FnSig { - inputs: inputs, - output: output, - variadic: false, - }), - })); + unsafety: hir::Unsafety::Unsafe, + abi: abi, + sig: ty::Binder(FnSig { + inputs: inputs, + output: output, + variadic: false, + }), + })); let i_n_tps = i_ty.generics.types.len(subst::FnSpace); if i_n_tps != n_tps { - span_err!(tcx.sess, it.span, E0094, - "intrinsic has wrong number of type \ + span_err!(tcx.sess, + it.span, + E0094, + "intrinsic has wrong number of type \ parameters: found {}, expected {}", - i_n_tps, n_tps); + i_n_tps, + n_tps); } else { - require_same_types(ccx, - it.span, - i_ty.ty, - fty, - "intrinsic has wrong type"); + require_same_types(ccx, it.span, i_ty.ty, fty, "intrinsic has wrong type"); } } @@ -74,31 +74,37 @@ pub fn check_intrinsic_type(ccx: &CrateCtxt, it: &hir::ForeignItem) { let tcx = ccx.tcx; let name = it.name.as_str(); let (n_tps, inputs, output) = if name.starts_with("atomic_") { - let split : Vec<&str> = name.split('_').collect(); + let split: Vec<&str> = name.split('_').collect(); assert!(split.len() >= 2, "Atomic intrinsic not correct format"); - //We only care about the operation here + // We only care about the operation here let (n_tps, inputs, output) = match split[1] { - "cxchg" | "cxchgweak" => (1, vec!(tcx.mk_mut_ptr(param(ccx, 0)), - param(ccx, 0), - param(ccx, 0)), - tcx.mk_tup(vec!(param(ccx, 0), tcx.types.bool))), - "load" => (1, vec!(tcx.mk_imm_ptr(param(ccx, 0))), - param(ccx, 0)), - "store" => (1, vec!(tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0)), - tcx.mk_nil()), - - "xchg" | "xadd" | "xsub" | "and" | "nand" | "or" | "xor" | "max" | - "min" | "umax" | "umin" => { - (1, vec!(tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0)), - param(ccx, 0)) - } - "fence" | "singlethreadfence" => { - (0, Vec::new(), tcx.mk_nil()) + "cxchg" | "cxchgweak" => { + (1, + vec![tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0), param(ccx, 0)], + tcx.mk_tup(vec![param(ccx, 0), tcx.types.bool])) } + "load" => (1, vec![tcx.mk_imm_ptr(param(ccx, 0))], param(ccx, 0)), + "store" => (1, vec![tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0)], tcx.mk_nil()), + + "xchg" | + "xadd" | + "xsub" | + "and" | + "nand" | + "or" | + "xor" | + "max" | + "min" | + "umax" | + "umin" => (1, vec![tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0)], param(ccx, 0)), + "fence" | "singlethreadfence" => (0, Vec::new(), tcx.mk_nil()), op => { - span_err!(tcx.sess, it.span, E0092, - "unrecognized atomic operation function: `{}`", op); + span_err!(tcx.sess, + it.span, + E0092, + "unrecognized atomic operation function: `{}`", + op); return; } }; @@ -109,51 +115,43 @@ pub fn check_intrinsic_type(ccx: &CrateCtxt, it: &hir::ForeignItem) { let (n_tps, inputs, output) = match &name[..] { "breakpoint" => (0, Vec::new(), tcx.mk_nil()), "size_of" | - "pref_align_of" | "min_align_of" => (1, Vec::new(), ccx.tcx.types.usize), - "size_of_val" | "min_align_of_val" => { - (1, vec![ - tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::DebruijnIndex::new(1), - ty::BrAnon(0))), - param(ccx, 0)) - ], ccx.tcx.types.usize) + "pref_align_of" | + "min_align_of" => (1, Vec::new(), ccx.tcx.types.usize), + "size_of_val" | "min_align_of_val" => { + (1, + vec![tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::DebruijnIndex::new(1), + ty::BrAnon(0))), + param(ccx, 0))], + ccx.tcx.types.usize) } "rustc_peek" => (1, vec![param(ccx, 0)], param(ccx, 0)), "init" | "init_dropped" => (1, Vec::new(), param(ccx, 0)), "uninit" => (1, Vec::new(), param(ccx, 0)), - "forget" => (1, vec!( param(ccx, 0) ), tcx.mk_nil()), - "transmute" => (2, vec!( param(ccx, 0) ), param(ccx, 1)), + "forget" => (1, vec![param(ccx, 0)], tcx.mk_nil()), + "transmute" => (2, vec![param(ccx, 0)], param(ccx, 1)), "move_val_init" => { - (1, - vec!( - tcx.mk_mut_ptr(param(ccx, 0)), - param(ccx, 0) - ), - tcx.mk_nil()) - } - "drop_in_place" => { - (1, vec![tcx.mk_mut_ptr(param(ccx, 0))], tcx.mk_nil()) + (1, vec![tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0)], tcx.mk_nil()) } + "drop_in_place" => (1, vec![tcx.mk_mut_ptr(param(ccx, 0))], tcx.mk_nil()), "needs_drop" => (1, Vec::new(), ccx.tcx.types.bool), "type_name" => (1, Vec::new(), tcx.mk_static_str()), "type_id" => (1, Vec::new(), ccx.tcx.types.u64), "offset" | "arith_offset" => { - (1, - vec!( - tcx.mk_ptr(ty::TypeAndMut { - ty: param(ccx, 0), - mutbl: hir::MutImmutable - }), - ccx.tcx.types.isize - ), - tcx.mk_ptr(ty::TypeAndMut { - ty: param(ccx, 0), - mutbl: hir::MutImmutable - })) + (1, + vec![tcx.mk_ptr(ty::TypeAndMut { + ty: param(ccx, 0), + mutbl: hir::MutImmutable, + }), + ccx.tcx.types.isize], + tcx.mk_ptr(ty::TypeAndMut { + ty: param(ccx, 0), + mutbl: hir::MutImmutable, + })) } "copy" | "copy_nonoverlapping" => { - (1, - vec!( + (1, + vec!( tcx.mk_ptr(ty::TypeAndMut { ty: param(ccx, 0), mutbl: hir::MutImmutable @@ -164,11 +162,11 @@ pub fn check_intrinsic_type(ccx: &CrateCtxt, it: &hir::ForeignItem) { }), tcx.types.usize, ), - tcx.mk_nil()) + tcx.mk_nil()) } "volatile_copy_memory" | "volatile_copy_nonoverlapping_memory" => { - (1, - vec!( + (1, + vec!( tcx.mk_ptr(ty::TypeAndMut { ty: param(ccx, 0), mutbl: hir::MutMutable @@ -179,11 +177,11 @@ pub fn check_intrinsic_type(ccx: &CrateCtxt, it: &hir::ForeignItem) { }), tcx.types.usize, ), - tcx.mk_nil()) + tcx.mk_nil()) } "write_bytes" | "volatile_set_memory" => { - (1, - vec!( + (1, + vec!( tcx.mk_ptr(ty::TypeAndMut { ty: param(ccx, 0), mutbl: hir::MutMutable @@ -191,98 +189,82 @@ pub fn check_intrinsic_type(ccx: &CrateCtxt, it: &hir::ForeignItem) { tcx.types.u8, tcx.types.usize, ), - tcx.mk_nil()) - } - "sqrtf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "sqrtf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), - "powif32" => { - (0, - vec!( tcx.types.f32, tcx.types.i32 ), - tcx.types.f32) - } - "powif64" => { - (0, - vec!( tcx.types.f64, tcx.types.i32 ), - tcx.types.f64) - } - "sinf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "sinf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), - "cosf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "cosf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), - "powf32" => { - (0, - vec!( tcx.types.f32, tcx.types.f32 ), - tcx.types.f32) + tcx.mk_nil()) } - "powf64" => { - (0, - vec!( tcx.types.f64, tcx.types.f64 ), - tcx.types.f64) - } - "expf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "expf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), - "exp2f32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "exp2f64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), - "logf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "logf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), - "log10f32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "log10f64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), - "log2f32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "log2f64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), - "fmaf32" => { - (0, - vec!( tcx.types.f32, tcx.types.f32, tcx.types.f32 ), - tcx.types.f32) - } - "fmaf64" => { - (0, - vec!( tcx.types.f64, tcx.types.f64, tcx.types.f64 ), - tcx.types.f64) - } - "fabsf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "fabsf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), - "copysignf32" => (0, vec!( tcx.types.f32, tcx.types.f32 ), tcx.types.f32), - "copysignf64" => (0, vec!( tcx.types.f64, tcx.types.f64 ), tcx.types.f64), - "floorf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "floorf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), - "ceilf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "ceilf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), - "truncf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "truncf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), - "rintf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "rintf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), - "nearbyintf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "nearbyintf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), - "roundf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32), - "roundf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64), + "sqrtf32" => (0, vec![tcx.types.f32], tcx.types.f32), + "sqrtf64" => (0, vec![tcx.types.f64], tcx.types.f64), + "powif32" => (0, vec![tcx.types.f32, tcx.types.i32], tcx.types.f32), + "powif64" => (0, vec![tcx.types.f64, tcx.types.i32], tcx.types.f64), + "sinf32" => (0, vec![tcx.types.f32], tcx.types.f32), + "sinf64" => (0, vec![tcx.types.f64], tcx.types.f64), + "cosf32" => (0, vec![tcx.types.f32], tcx.types.f32), + "cosf64" => (0, vec![tcx.types.f64], tcx.types.f64), + "powf32" => (0, vec![tcx.types.f32, tcx.types.f32], tcx.types.f32), + "powf64" => (0, vec![tcx.types.f64, tcx.types.f64], tcx.types.f64), + "expf32" => (0, vec![tcx.types.f32], tcx.types.f32), + "expf64" => (0, vec![tcx.types.f64], tcx.types.f64), + "exp2f32" => (0, vec![tcx.types.f32], tcx.types.f32), + "exp2f64" => (0, vec![tcx.types.f64], tcx.types.f64), + "logf32" => (0, vec![tcx.types.f32], tcx.types.f32), + "logf64" => (0, vec![tcx.types.f64], tcx.types.f64), + "log10f32" => (0, vec![tcx.types.f32], tcx.types.f32), + "log10f64" => (0, vec![tcx.types.f64], tcx.types.f64), + "log2f32" => (0, vec![tcx.types.f32], tcx.types.f32), + "log2f64" => (0, vec![tcx.types.f64], tcx.types.f64), + "fmaf32" => (0, vec![tcx.types.f32, tcx.types.f32, tcx.types.f32], tcx.types.f32), + "fmaf64" => (0, vec![tcx.types.f64, tcx.types.f64, tcx.types.f64], tcx.types.f64), + "fabsf32" => (0, vec![tcx.types.f32], tcx.types.f32), + "fabsf64" => (0, vec![tcx.types.f64], tcx.types.f64), + "copysignf32" => (0, vec![tcx.types.f32, tcx.types.f32], tcx.types.f32), + "copysignf64" => (0, vec![tcx.types.f64, tcx.types.f64], tcx.types.f64), + "floorf32" => (0, vec![tcx.types.f32], tcx.types.f32), + "floorf64" => (0, vec![tcx.types.f64], tcx.types.f64), + "ceilf32" => (0, vec![tcx.types.f32], tcx.types.f32), + "ceilf64" => (0, vec![tcx.types.f64], tcx.types.f64), + "truncf32" => (0, vec![tcx.types.f32], tcx.types.f32), + "truncf64" => (0, vec![tcx.types.f64], tcx.types.f64), + "rintf32" => (0, vec![tcx.types.f32], tcx.types.f32), + "rintf64" => (0, vec![tcx.types.f64], tcx.types.f64), + "nearbyintf32" => (0, vec![tcx.types.f32], tcx.types.f32), + "nearbyintf64" => (0, vec![tcx.types.f64], tcx.types.f64), + "roundf32" => (0, vec![tcx.types.f32], tcx.types.f32), + "roundf64" => (0, vec![tcx.types.f64], tcx.types.f64), - "volatile_load" => - (1, vec!( tcx.mk_imm_ptr(param(ccx, 0)) ), param(ccx, 0)), - "volatile_store" => - (1, vec!( tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0) ), tcx.mk_nil()), + "volatile_load" => (1, vec![tcx.mk_imm_ptr(param(ccx, 0))], param(ccx, 0)), + "volatile_store" => { + (1, vec![tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0)], tcx.mk_nil()) + } - "ctpop" | "ctlz" | "cttz" | "bswap" => (1, vec!(param(ccx, 0)), param(ccx, 0)), + "ctpop" | "ctlz" | "cttz" | "bswap" => (1, vec![param(ccx, 0)], param(ccx, 0)), - "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => - (1, vec!(param(ccx, 0), param(ccx, 0)), - tcx.mk_tup(vec!(param(ccx, 0), tcx.types.bool))), + "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => { + (1, + vec![param(ccx, 0), param(ccx, 0)], + tcx.mk_tup(vec![param(ccx, 0), tcx.types.bool])) + } - "unchecked_div" | "unchecked_rem" => - (1, vec![param(ccx, 0), param(ccx, 0)], param(ccx, 0)), + "unchecked_div" | "unchecked_rem" => { + (1, vec![param(ccx, 0), param(ccx, 0)], param(ccx, 0)) + } - "overflowing_add" | "overflowing_sub" | "overflowing_mul" => - (1, vec![param(ccx, 0), param(ccx, 0)], param(ccx, 0)), - "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => - (1, vec![param(ccx, 0), param(ccx, 0)], param(ccx, 0)), + "overflowing_add" | "overflowing_sub" | "overflowing_mul" => { + (1, vec![param(ccx, 0), param(ccx, 0)], param(ccx, 0)) + } + "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => { + (1, vec![param(ccx, 0), param(ccx, 0)], param(ccx, 0)) + } "return_address" => (0, vec![], tcx.mk_imm_ptr(tcx.types.u8)), "assume" => (0, vec![tcx.types.bool], tcx.mk_nil()), - "discriminant_value" => (1, vec![ - tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::DebruijnIndex::new(1), - ty::BrAnon(0))), - param(ccx, 0))], tcx.types.u64), + "discriminant_value" => { + (1, + vec![tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::DebruijnIndex::new(1), + ty::BrAnon(0))), + param(ccx, 0))], + tcx.types.u64) + } "try" => { let mut_u8 = tcx.mk_mut_ptr(tcx.types.u8); @@ -299,8 +281,11 @@ pub fn check_intrinsic_type(ccx: &CrateCtxt, it: &hir::ForeignItem) { } ref other => { - span_err!(tcx.sess, it.span, E0093, - "unrecognized intrinsic function: `{}`", *other); + span_err!(tcx.sess, + it.span, + E0093, + "unrecognized intrinsic function: `{}`", + *other); return; } }; @@ -310,8 +295,7 @@ pub fn check_intrinsic_type(ccx: &CrateCtxt, it: &hir::ForeignItem) { } /// Type-check `extern "platform-intrinsic" { ... }` functions. -pub fn check_platform_intrinsic_type(ccx: &CrateCtxt, - it: &hir::ForeignItem) { +pub fn check_platform_intrinsic_type(ccx: &CrateCtxt, it: &hir::ForeignItem) { let param = |n| { let name = token::intern(&format!("P{}", n)); ccx.tcx.mk_param(subst::FnSpace, n, name) @@ -326,25 +310,31 @@ pub fn check_platform_intrinsic_type(ccx: &CrateCtxt, "simd_eq" | "simd_ne" | "simd_lt" | "simd_le" | "simd_gt" | "simd_ge" => { (2, vec![param(0), param(0)], param(1)) } - "simd_add" | "simd_sub" | "simd_mul" | - "simd_div" | "simd_shl" | "simd_shr" | - "simd_and" | "simd_or" | "simd_xor" => { - (1, vec![param(0), param(0)], param(0)) - } + "simd_add" | + "simd_sub" | + "simd_mul" | + "simd_div" | + "simd_shl" | + "simd_shr" | + "simd_and" | + "simd_or" | + "simd_xor" => (1, vec![param(0), param(0)], param(0)), "simd_insert" => (2, vec![param(0), tcx.types.u32, param(1)], param(0)), "simd_extract" => (2, vec![param(0), tcx.types.u32], param(1)), "simd_cast" => (2, vec![param(0)], param(1)), name if name.starts_with("simd_shuffle") => { match name["simd_shuffle".len()..].parse() { Ok(n) => { - let params = vec![param(0), param(0), - tcx.mk_ty(ty::TyArray(tcx.types.u32, n))]; + let params = vec![param(0), param(0), tcx.mk_ty(ty::TyArray(tcx.types.u32, n))]; (2, params, param(1)) } Err(_) => { - span_err!(tcx.sess, it.span, E0439, - "invalid `simd_shuffle`, needs length: `{}`", name); - return + span_err!(tcx.sess, + it.span, + E0439, + "invalid `simd_shuffle`, needs length: `{}`", + name); + return; } } } @@ -353,99 +343,141 @@ pub fn check_platform_intrinsic_type(ccx: &CrateCtxt, Some(intr) => { // this function is a platform specific intrinsic if i_n_tps != 0 { - span_err!(tcx.sess, it.span, E0440, + span_err!(tcx.sess, + it.span, + E0440, "platform-specific intrinsic has wrong number of type \ parameters: found {}, expected 0", i_n_tps); - return + return; } let mut structural_to_nomimal = HashMap::new(); let sig = tcx.no_late_bound_regions(i_ty.ty.fn_sig()).unwrap(); if intr.inputs.len() != sig.inputs.len() { - span_err!(tcx.sess, it.span, E0444, + span_err!(tcx.sess, + it.span, + E0444, "platform-specific intrinsic has invalid number of \ arguments: found {}, expected {}", - intr.inputs.len(), sig.inputs.len()); - return + intr.inputs.len(), + sig.inputs.len()); + return; } let input_pairs = intr.inputs.iter().zip(&sig.inputs); for (i, (expected_arg, arg)) in input_pairs.enumerate() { - match_intrinsic_type_to_type(ccx, &format!("argument {}", i + 1), it.span, - &mut structural_to_nomimal, expected_arg, arg); + match_intrinsic_type_to_type(ccx, + &format!("argument {}", i + 1), + it.span, + &mut structural_to_nomimal, + expected_arg, + arg); } - match_intrinsic_type_to_type(ccx, "return value", it.span, + match_intrinsic_type_to_type(ccx, + "return value", + it.span, &mut structural_to_nomimal, - &intr.output, sig.output.unwrap()); - return + &intr.output, + sig.output.unwrap()); + return; } None => { - span_err!(tcx.sess, it.span, E0441, - "unrecognized platform-specific intrinsic function: `{}`", name); + span_err!(tcx.sess, + it.span, + E0441, + "unrecognized platform-specific intrinsic function: `{}`", + name); return; } } } }; - equate_intrinsic_type(ccx, it, n_tps, Abi::PlatformIntrinsic, - inputs, ty::FnConverging(output)) + equate_intrinsic_type(ccx, + it, + n_tps, + Abi::PlatformIntrinsic, + inputs, + ty::FnConverging(output)) } // walk the expected type and the actual type in lock step, checking they're // the same, in a kinda-structural way, i.e. `Vector`s have to be simd structs with // exactly the right element type -fn match_intrinsic_type_to_type<'tcx, 'a>( - ccx: &CrateCtxt<'a, 'tcx>, - position: &str, - span: Span, - structural_to_nominal: &mut HashMap<&'a intrinsics::Type, ty::Ty<'tcx>>, - expected: &'a intrinsics::Type, t: ty::Ty<'tcx>) -{ +fn match_intrinsic_type_to_type<'tcx, 'a>(ccx: &CrateCtxt<'a, 'tcx>, + position: &str, + span: Span, + structural_to_nominal: &mut HashMap<&'a intrinsics::Type, + ty::Ty<'tcx>>, + expected: &'a intrinsics::Type, + t: ty::Ty<'tcx>) { use intrinsics::Type::*; let simple_error = |real: &str, expected: &str| { - span_err!(ccx.tcx.sess, span, E0442, + span_err!(ccx.tcx.sess, + span, + E0442, "intrinsic {} has wrong type: found {}, expected {}", - position, real, expected) + position, + real, + expected) }; match *expected { - Void => match t.sty { - ty::TyTuple(ref v) if v.is_empty() => {}, - _ => simple_error(&format!("`{}`", t), "()"), - }, + Void => { + match t.sty { + ty::TyTuple(ref v) if v.is_empty() => {} + _ => simple_error(&format!("`{}`", t), "()"), + } + } // (The width we pass to LLVM doesn't concern the type checker.) - Integer(signed, bits, _llvm_width) => match (signed, bits, &t.sty) { - (true, 8, &ty::TyInt(ast::IntTy::I8)) | - (false, 8, &ty::TyUint(ast::UintTy::U8)) | - (true, 16, &ty::TyInt(ast::IntTy::I16)) | - (false, 16, &ty::TyUint(ast::UintTy::U16)) | - (true, 32, &ty::TyInt(ast::IntTy::I32)) | - (false, 32, &ty::TyUint(ast::UintTy::U32)) | - (true, 64, &ty::TyInt(ast::IntTy::I64)) | - (false, 64, &ty::TyUint(ast::UintTy::U64)) => {}, - _ => simple_error(&format!("`{}`", t), - &format!("`{}{n}`", - if signed {"i"} else {"u"}, - n = bits)), - }, - Float(bits) => match (bits, &t.sty) { - (32, &ty::TyFloat(ast::FloatTy::F32)) | - (64, &ty::TyFloat(ast::FloatTy::F64)) => {}, - _ => simple_error(&format!("`{}`", t), - &format!("`f{n}`", n = bits)), - }, + Integer(signed, bits, _llvm_width) => { + match (signed, bits, &t.sty) { + (true, 8, &ty::TyInt(ast::IntTy::I8)) | + (false, 8, &ty::TyUint(ast::UintTy::U8)) | + (true, 16, &ty::TyInt(ast::IntTy::I16)) | + (false, 16, &ty::TyUint(ast::UintTy::U16)) | + (true, 32, &ty::TyInt(ast::IntTy::I32)) | + (false, 32, &ty::TyUint(ast::UintTy::U32)) | + (true, 64, &ty::TyInt(ast::IntTy::I64)) | + (false, 64, &ty::TyUint(ast::UintTy::U64)) => {} + _ => { + simple_error(&format!("`{}`", t), + &format!("`{}{n}`", + if signed { + "i" + } else { + "u" + }, + n = bits)) + } + } + } + Float(bits) => { + match (bits, &t.sty) { + (32, &ty::TyFloat(ast::FloatTy::F32)) | + (64, &ty::TyFloat(ast::FloatTy::F64)) => {} + _ => simple_error(&format!("`{}`", t), &format!("`f{n}`", n = bits)), + } + } Pointer(ref inner_expected, ref _llvm_type, const_) => { match t.sty { ty::TyRawPtr(ty::TypeAndMut { ty, mutbl }) => { if (mutbl == hir::MutImmutable) != const_ { simple_error(&format!("`{}`", t), - if const_ {"const pointer"} else {"mut pointer"}) + if const_ { + "const pointer" + } else { + "mut pointer" + }) } - match_intrinsic_type_to_type(ccx, position, span, structural_to_nominal, - inner_expected, ty) + match_intrinsic_type_to_type(ccx, + position, + span, + structural_to_nominal, + inner_expected, + ty) } _ => simple_error(&format!("`{}`", t), "raw pointer"), } @@ -467,7 +499,9 @@ fn match_intrinsic_type_to_type<'tcx, 'a>( let previous = structural_to_nominal.entry(expected).or_insert(t); if *previous != t { // this gets its own error code because it is non-trivial - span_err!(ccx.tcx.sess, span, E0443, + span_err!(ccx.tcx.sess, + span, + E0443, "intrinsic {} has wrong type: found `{}`, expected `{}` which \ was used for this vector type previously in this signature", position, @@ -489,15 +523,18 @@ fn match_intrinsic_type_to_type<'tcx, 'a>( if contents.len() != expected_contents.len() { simple_error(&format!("tuple with length {}", contents.len()), &format!("tuple with length {}", expected_contents.len())); - return + return; } for (e, c) in expected_contents.iter().zip(contents) { - match_intrinsic_type_to_type(ccx, position, span, structural_to_nominal, - e, c) + match_intrinsic_type_to_type(ccx, + position, + span, + structural_to_nominal, + e, + c) } } - _ => simple_error(&format!("`{}`", t), - &format!("tuple")), + _ => simple_error(&format!("`{}`", t), &format!("tuple")), } } } diff --git a/src/librustc_typeck/check/regionck.rs b/src/librustc_typeck/check/regionck.rs index a8cb21126c079..e13504420b837 100644 --- a/src/librustc_typeck/check/regionck.rs +++ b/src/librustc_typeck/check/regionck.rs @@ -90,7 +90,7 @@ use middle::mem_categorization::Categorization; use middle::region::{self, CodeExtent}; use rustc::ty::subst::Substs; use rustc::traits; -use rustc::ty::{self, Ty, MethodCall, TypeFoldable}; +use rustc::ty::{self, MethodCall, Ty, TypeFoldable}; use rustc::infer::{self, GenericKind, InferOk, SubregionOrigin, TypeOrigin, VerifyBound}; use hir::pat_util; use rustc::ty::adjustment; @@ -110,8 +110,8 @@ macro_rules! ignore_err { ($e:expr) => (match $e { Ok(e) => e, Err(_) => return () }) } -/////////////////////////////////////////////////////////////////////////// -// PUBLIC ENTRY POINTS +/// //////////////////////////////////////////////////////////////////////// +/// PUBLIC ENTRY POINTS impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { pub fn regionck_expr(&self, e: &hir::Expr) { @@ -126,14 +126,11 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { /// Region checking during the WF phase for items. `wf_tys` are the /// types from which we should derive implied bounds, if any. - pub fn regionck_item(&self, - item_id: ast::NodeId, - span: Span, - wf_tys: &[Ty<'tcx>]) { + pub fn regionck_item(&self, item_id: ast::NodeId, span: Span, wf_tys: &[Ty<'tcx>]) { debug!("regionck_item(item.id={:?}, wf_tys={:?}", item_id, wf_tys); let mut rcx = RegionCtxt::new(self, RepeatingScope(item_id), item_id, Subject(item_id)); - rcx.free_region_map.relate_free_regions_from_predicates( - &self.parameter_environment.caller_bounds); + rcx.free_region_map + .relate_free_regions_from_predicates(&self.parameter_environment.caller_bounds); rcx.relate_free_regions(wf_tys, item_id, span); rcx.visit_region_obligations(item_id); rcx.resolve_regions_and_report_errors(); @@ -152,8 +149,8 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { rcx.visit_fn_body(fn_id, decl, blk, fn_span); } - rcx.free_region_map.relate_free_regions_from_predicates( - &self.parameter_environment.caller_bounds); + rcx.free_region_map + .relate_free_regions_from_predicates(&self.parameter_environment.caller_bounds); rcx.resolve_regions_and_report_errors(); @@ -164,10 +161,10 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } } -/////////////////////////////////////////////////////////////////////////// -// INTERNALS +/// //////////////////////////////////////////////////////////////////////// +/// INTERNALS -pub struct RegionCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { +pub struct RegionCtxt<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> { pub fcx: &'a FnCtxt<'a, 'gcx, 'tcx>, region_bound_pairs: Vec<(ty::Region, GenericKind<'tcx>)>, @@ -185,7 +182,6 @@ pub struct RegionCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { // id of AST node being analyzed (the subject of the analysis). subject: SubjectNode, - } impl<'a, 'gcx, 'tcx> Deref for RegionCtxt<'a, 'gcx, 'tcx> { @@ -196,13 +192,17 @@ impl<'a, 'gcx, 'tcx> Deref for RegionCtxt<'a, 'gcx, 'tcx> { } pub struct RepeatingScope(ast::NodeId); -pub enum SubjectNode { Subject(ast::NodeId), None } +pub enum SubjectNode { + Subject(ast::NodeId), + None, +} impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { pub fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>, initial_repeating_scope: RepeatingScope, initial_body_id: ast::NodeId, - subject: SubjectNode) -> RegionCtxt<'a, 'gcx, 'tcx> { + subject: SubjectNode) + -> RegionCtxt<'a, 'gcx, 'tcx> { let RepeatingScope(initial_repeating_scope) = initial_repeating_scope; RegionCtxt { fcx: fcx, @@ -261,8 +261,11 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { } fn resolve_method_type(&self, method_call: MethodCall) -> Option> { - let method_ty = self.tables.borrow().method_map - .get(&method_call).map(|method| method.ty); + let method_ty = self.tables + .borrow() + .method_map + .get(&method_call) + .map(|method| method.ty); method_ty.map(|method_ty| self.resolve_type(method_ty)) } @@ -272,10 +275,11 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { if ty_unadjusted.references_error() { ty_unadjusted } else { - ty_unadjusted.adjust( - self.tcx, expr.span, expr.id, - self.tables.borrow().adjustments.get(&expr.id), - |method_call| self.resolve_method_type(method_call)) + ty_unadjusted.adjust(self.tcx, + expr.span, + expr.id, + self.tables.borrow().adjustments.get(&expr.id), + |method_call| self.resolve_method_type(method_call)) } } @@ -283,13 +287,16 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { id: ast::NodeId, // the id of the fn itself fn_decl: &hir::FnDecl, body: &hir::Block, - span: Span) - { + span: Span) { // When we enter a function, we can derive debug!("visit_fn_body(id={})", id); - let call_site = self.tcx.region_maps.lookup_code_extent( - region::CodeExtentData::CallSiteScope { fn_id: id, body_id: body.id }); + let call_site = self.tcx + .region_maps + .lookup_code_extent(region::CodeExtentData::CallSiteScope { + fn_id: id, + body_id: body.id, + }); let old_call_site_scope = self.set_call_site_scope(Some(call_site)); let fn_sig = { @@ -309,11 +316,11 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { // because it will have no effect. // // FIXME(#27579) return types should not be implied bounds - let fn_sig_tys: Vec<_> = - fn_sig.inputs.iter() - .cloned() - .chain(Some(fn_sig.output.unwrap_or(self.tcx.types.bool))) - .collect(); + let fn_sig_tys: Vec<_> = fn_sig.inputs + .iter() + .cloned() + .chain(Some(fn_sig.output.unwrap_or(self.tcx.types.bool))) + .collect(); let old_body_id = self.set_body_id(body.id); self.relate_free_regions(&fn_sig_tys[..], body.id, span); @@ -324,7 +331,8 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { let call_site_scope = self.call_site_scope.unwrap(); debug!("visit_fn_body body.id {} call_site_scope: {:?}", - body.id, call_site_scope); + body.id, + call_site_scope); self.type_of_node_must_outlive(infer::CallReturn(span), body.id, ty::ReScope(call_site_scope)); @@ -335,8 +343,7 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { self.set_call_site_scope(old_call_site_scope); } - fn visit_region_obligations(&mut self, node_id: ast::NodeId) - { + fn visit_region_obligations(&mut self, node_id: ast::NodeId) { debug!("visit_region_obligations: node_id={}", node_id); // region checking can introduce new pending obligations @@ -346,15 +353,15 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { // Make a copy of the region obligations vec because we'll need // to be able to borrow the fulfillment-cx below when projecting. - let region_obligations = - self.fulfillment_cx - .borrow() - .region_obligations(node_id) - .to_vec(); + let region_obligations = self.fulfillment_cx + .borrow() + .region_obligations(node_id) + .to_vec(); for r_o in ®ion_obligations { debug!("visit_region_obligations: r_o={:?} cause={:?}", - r_o, r_o.cause); + r_o, + r_o.cause); let sup_type = self.resolve_type(r_o.sup_type); let origin = self.code_to_origin(r_o.cause.span, sup_type, &r_o.cause.code); self.type_must_outlive(origin, sup_type, r_o.sub_region); @@ -371,10 +378,10 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { code: &traits::ObligationCauseCode<'tcx>) -> SubregionOrigin<'tcx> { match *code { - traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => - infer::ReferenceOutlivesReferent(ref_type, span), - _ => - infer::RelateParamBound(span, sup_type), + traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => { + infer::ReferenceOutlivesReferent(ref_type, span) + } + _ => infer::RelateParamBound(span, sup_type), } } @@ -388,10 +395,7 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { /// is well-formed. /// /// Tests: `src/test/compile-fail/regions-free-region-ordering-*.rs` - fn relate_free_regions(&mut self, - fn_sig_tys: &[Ty<'tcx>], - body_id: ast::NodeId, - span: Span) { + fn relate_free_regions(&mut self, fn_sig_tys: &[Ty<'tcx>], body_id: ast::NodeId, span: Span) { debug!("relate_free_regions >>"); for &ty in fn_sig_tys { @@ -408,8 +412,7 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { for implication in implied_bounds { debug!("implication: {:?}", implication); match implication { - ImpliedBound::RegionSubRegion(ty::ReFree(free_a), - ty::ReVar(vid_b)) => { + ImpliedBound::RegionSubRegion(ty::ReFree(free_a), ty::ReVar(vid_b)) => { self.add_given(free_a, vid_b); } ImpliedBound::RegionSubParam(r_a, param_b) => { @@ -445,8 +448,7 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { } }; - self.fcx.resolve_regions_and_report_errors(&self.free_region_map, - subject_node_id); + self.fcx.resolve_regions_and_report_errors(&self.free_region_map, subject_node_id); } fn constrain_bindings_in_pat(&mut self, pat: &hir::Pat) { @@ -496,12 +498,16 @@ impl<'a, 'gcx, 'tcx, 'v> Visitor<'v> for RegionCtxt<'a, 'gcx, 'tcx> { // hierarchy, and in particular the relationships between free // regions, until regionck, as described in #3238. - fn visit_fn(&mut self, _fk: intravisit::FnKind<'v>, fd: &'v hir::FnDecl, - b: &'v hir::Block, span: Span, id: ast::NodeId) { + fn visit_fn(&mut self, + _fk: intravisit::FnKind<'v>, + fd: &'v hir::FnDecl, + b: &'v hir::Block, + span: Span, + id: ast::NodeId) { self.visit_fn_body(id, fd, b, span) } - //visit_pat: visit_pat, // (..) see above + // visit_pat: visit_pat, // (..) see above fn visit_arm(&mut self, arm: &hir::Arm) { // see above @@ -520,7 +526,8 @@ impl<'a, 'gcx, 'tcx, 'v> Visitor<'v> for RegionCtxt<'a, 'gcx, 'tcx> { fn visit_expr(&mut self, expr: &hir::Expr) { debug!("regionck::visit_expr(e={:?}, repeating_scope={})", - expr, self.repeating_scope); + expr, + self.repeating_scope); // No matter what, the type of each expression must outlive the // scope of that expression. This also guarantees basic WF. @@ -528,7 +535,8 @@ impl<'a, 'gcx, 'tcx, 'v> Visitor<'v> for RegionCtxt<'a, 'gcx, 'tcx> { // the region corresponding to this expression let expr_region = ty::ReScope(self.tcx.region_maps.node_extent(expr.id)); self.type_must_outlive(infer::ExprTypeIsNotInScope(expr_ty, expr.span), - expr_ty, expr_region); + expr_ty, + expr_region); let method_call = MethodCall::expr(expr.id); let opt_method_callee = self.tables.borrow().method_map.get(&method_call).cloned(); @@ -540,17 +548,17 @@ impl<'a, 'gcx, 'tcx, 'v> Visitor<'v> for RegionCtxt<'a, 'gcx, 'tcx> { // provided as arguments outlive the call. if let Some(callee) = opt_method_callee { let origin = match expr.node { - hir::ExprMethodCall(..) => - infer::ParameterOrigin::MethodCall, - hir::ExprUnary(op, _) if op == hir::UnDeref => - infer::ParameterOrigin::OverloadedDeref, - _ => - infer::ParameterOrigin::OverloadedOperator + hir::ExprMethodCall(..) => infer::ParameterOrigin::MethodCall, + hir::ExprUnary(op, _) if op == hir::UnDeref => { + infer::ParameterOrigin::OverloadedDeref + } + _ => infer::ParameterOrigin::OverloadedOperator, }; self.substs_wf_in_scope(origin, &callee.substs, expr.span, expr_region); self.type_must_outlive(infer::ExprTypeIsNotInScope(callee.ty, expr.span), - callee.ty, expr_region); + callee.ty, + expr_region); } // Check any autoderefs or autorefs that appear. @@ -595,8 +603,7 @@ impl<'a, 'gcx, 'tcx, 'v> Visitor<'v> for RegionCtxt<'a, 'gcx, 'tcx> { }; match cmt_result { Ok(head_cmt) => { - self.check_safety_of_rvalue_destructor_if_necessary(head_cmt, - expr.span); + self.check_safety_of_rvalue_destructor_if_necessary(head_cmt, expr.span); } Err(..) => { self.tcx.sess.delay_span_bug(expr.span, "cat_expr_unadjusted Errd"); @@ -620,7 +627,8 @@ impl<'a, 'gcx, 'tcx, 'v> Visitor<'v> for RegionCtxt<'a, 'gcx, 'tcx> { } debug!("regionck::visit_expr(e={:?}, repeating_scope={}) - visiting subexprs", - expr, self.repeating_scope); + expr, + self.repeating_scope); match expr.node { hir::ExprPath(..) => { self.fcx.opt_node_ty_substs(expr.id, |item_substs| { @@ -631,39 +639,34 @@ impl<'a, 'gcx, 'tcx, 'v> Visitor<'v> for RegionCtxt<'a, 'gcx, 'tcx> { hir::ExprCall(ref callee, ref args) => { if has_method_map { - self.constrain_call(expr, Some(&callee), - args.iter().map(|e| &**e), false); + self.constrain_call(expr, Some(&callee), args.iter().map(|e| &**e), false); } else { self.constrain_callee(callee.id, expr, &callee); - self.constrain_call(expr, None, - args.iter().map(|e| &**e), false); + self.constrain_call(expr, None, args.iter().map(|e| &**e), false); } intravisit::walk_expr(self, expr); } hir::ExprMethodCall(_, _, ref args) => { - self.constrain_call(expr, Some(&args[0]), - args[1..].iter().map(|e| &**e), false); + self.constrain_call(expr, Some(&args[0]), args[1..].iter().map(|e| &**e), false); intravisit::walk_expr(self, expr); } hir::ExprAssignOp(_, ref lhs, ref rhs) => { if has_method_map { - self.constrain_call(expr, Some(&lhs), - Some(&**rhs).into_iter(), false); + self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter(), false); } intravisit::walk_expr(self, expr); } hir::ExprIndex(ref lhs, ref rhs) if has_method_map => { - self.constrain_call(expr, Some(&lhs), - Some(&**rhs).into_iter(), true); + self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter(), true); intravisit::walk_expr(self, expr); - }, + } hir::ExprBinary(op, ref lhs, ref rhs) if has_method_map => { let implicitly_ref_args = !op.node.is_by_value(); @@ -672,8 +675,10 @@ impl<'a, 'gcx, 'tcx, 'v> Visitor<'v> for RegionCtxt<'a, 'gcx, 'tcx> { // overloaded op. Note that we (sadly) currently use an // implicit "by ref" sort of passing style here. This // should be converted to an adjustment! - self.constrain_call(expr, Some(&lhs), - Some(&**rhs).into_iter(), implicitly_ref_args); + self.constrain_call(expr, + Some(&lhs), + Some(&**rhs).into_iter(), + implicitly_ref_args); intravisit::walk_expr(self, expr); } @@ -684,8 +689,7 @@ impl<'a, 'gcx, 'tcx, 'v> Visitor<'v> for RegionCtxt<'a, 'gcx, 'tcx> { let lhs_ty = self.resolve_expr_type_adjusted(&lhs); let rhs_ty = self.resolve_expr_type_adjusted(&rhs); for &ty in &[lhs_ty, rhs_ty] { - self.type_must_outlive(infer::Operand(expr.span), - ty, expr_region); + self.type_must_outlive(infer::Operand(expr.span), ty, expr_region); } intravisit::walk_expr(self, expr); } @@ -694,8 +698,10 @@ impl<'a, 'gcx, 'tcx, 'v> Visitor<'v> for RegionCtxt<'a, 'gcx, 'tcx> { let implicitly_ref_args = !op.is_by_value(); // As above. - self.constrain_call(expr, Some(&lhs), - None::.iter(), implicitly_ref_args); + self.constrain_call(expr, + Some(&lhs), + None::.iter(), + implicitly_ref_args); intravisit::walk_expr(self, expr); } @@ -705,13 +711,12 @@ impl<'a, 'gcx, 'tcx, 'v> Visitor<'v> for RegionCtxt<'a, 'gcx, 'tcx> { let method_call = MethodCall::expr(expr.id); let base_ty = match self.tables.borrow().method_map.get(&method_call) { Some(method) => { - self.constrain_call(expr, Some(&base), - None::.iter(), true); + self.constrain_call(expr, Some(&base), None::.iter(), true); // late-bound regions in overloaded method calls are instantiated let fn_ret = self.tcx.no_late_bound_regions(&method.ty.fn_ret()); fn_ret.unwrap().unwrap() } - None => self.resolve_node_type(base.id) + None => self.resolve_node_type(base.id), }; if let ty::TyRef(r_ptr, _) = base_ty.sty { self.mk_subregion_due_to_dereference(expr.span, expr_region, *r_ptr); @@ -780,7 +785,8 @@ impl<'a, 'gcx, 'tcx, 'v> Visitor<'v> for RegionCtxt<'a, 'gcx, 'tcx> { hir::ExprRet(Some(ref ret_expr)) => { let call_site_scope = self.call_site_scope; debug!("visit_expr ExprRet ret_expr.id {} call_site_scope: {:?}", - ret_expr.id, call_site_scope); + ret_expr.id, + call_site_scope); self.type_of_node_must_outlive(infer::CallReturn(ret_expr.span), ret_expr.id, ty::ReScope(call_site_scope.unwrap())); @@ -795,10 +801,7 @@ impl<'a, 'gcx, 'tcx, 'v> Visitor<'v> for RegionCtxt<'a, 'gcx, 'tcx> { } impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { - fn constrain_cast(&mut self, - cast_expr: &hir::Expr, - source_expr: &hir::Expr) - { + fn constrain_cast(&mut self, cast_expr: &hir::Expr, source_expr: &hir::Expr) { debug!("constrain_cast(cast_expr={:?}, source_expr={:?})", cast_expr, source_expr); @@ -809,41 +812,41 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { self.walk_cast(cast_expr, source_ty, target_ty); } - fn walk_cast(&mut self, - cast_expr: &hir::Expr, - from_ty: Ty<'tcx>, - to_ty: Ty<'tcx>) { - debug!("walk_cast(from_ty={:?}, to_ty={:?})", - from_ty, - to_ty); + fn walk_cast(&mut self, cast_expr: &hir::Expr, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) { + debug!("walk_cast(from_ty={:?}, to_ty={:?})", from_ty, to_ty); match (&from_ty.sty, &to_ty.sty) { - /*From:*/ (&ty::TyRef(from_r, ref from_mt), - /*To: */ &ty::TyRef(to_r, ref to_mt)) => { + // From: + (&ty::TyRef(from_r, ref from_mt), + // To: + &ty::TyRef(to_r, ref to_mt)) => { // Target cannot outlive source, naturally. self.sub_regions(infer::Reborrow(cast_expr.span), *to_r, *from_r); self.walk_cast(cast_expr, from_mt.ty, to_mt.ty); } - /*From:*/ (_, - /*To: */ &ty::TyTrait(box ty::TraitTy { ref bounds, .. })) => { + // From: + (_, + // To: + &ty::TyTrait(box ty::TraitTy { ref bounds, .. })) => { // When T is existentially quantified as a trait // `Foo+'to`, it must outlive the region bound `'to`. self.type_must_outlive(infer::RelateObjectBound(cast_expr.span), - from_ty, bounds.region_bound); + from_ty, + bounds.region_bound); } - /*From:*/ (&ty::TyBox(from_referent_ty), - /*To: */ &ty::TyBox(to_referent_ty)) => { + // From: + (&ty::TyBox(from_referent_ty), + // To: + &ty::TyBox(to_referent_ty)) => { self.walk_cast(cast_expr, from_referent_ty, to_referent_ty); } - _ => { } + _ => {} } } - fn check_expr_fn_block(&mut self, - expr: &hir::Expr, - body: &hir::Block) { + fn check_expr_fn_block(&mut self, expr: &hir::Expr, body: &hir::Block) { let repeating_scope = self.set_repeating_scope(body.id); intravisit::walk_expr(self, expr); self.set_repeating_scope(repeating_scope); @@ -855,7 +858,7 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { _callee_expr: &hir::Expr) { let callee_ty = self.resolve_node_type(callee_id); match callee_ty.sty { - ty::TyFnDef(..) | ty::TyFnPtr(_) => { } + ty::TyFnDef(..) | ty::TyFnPtr(_) => {} _ => { // this should not happen, but it does if the program is // erroneous @@ -868,11 +871,11 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { } } - fn constrain_call<'b, I: Iterator>(&mut self, - call_expr: &hir::Expr, - receiver: Option<&hir::Expr>, - arg_exprs: I, - implicitly_ref_args: bool) { + fn constrain_call<'b, I: Iterator>(&mut self, + call_expr: &hir::Expr, + receiver: Option<&hir::Expr>, + arg_exprs: I, + implicitly_ref_args: bool) { //! Invoked on every call site (i.e., normal calls, method calls, //! and overloaded operators). Constrains the regions which appear //! in the type of the function. Also constrains the regions that @@ -881,9 +884,9 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { debug!("constrain_call(call_expr={:?}, \ receiver={:?}, \ implicitly_ref_args={})", - call_expr, - receiver, - implicitly_ref_args); + call_expr, + receiver, + implicitly_ref_args); // `callee_region` is the scope representing the time in which the // call occurs. @@ -900,7 +903,8 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { // ensure that any regions appearing in the argument type are // valid for at least the lifetime of the function: self.type_of_node_must_outlive(infer::CallArg(arg_expr.span), - arg_expr.id, callee_region); + arg_expr.id, + callee_region); // unfortunately, there are two means of taking implicit // references, and we need to propagate constraints as a @@ -914,8 +918,7 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { // as loop above, but for receiver if let Some(r) = receiver { debug!("receiver: {:?}", r); - self.type_of_node_must_outlive(infer::CallRcvr(r.span), - r.id, callee_region); + self.type_of_node_must_outlive(infer::CallRcvr(r.span), r.id, callee_region); if implicitly_ref_args { self.link_by_ref(&r, callee_scope); } @@ -927,8 +930,7 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { fn constrain_autoderefs(&mut self, deref_expr: &hir::Expr, derefs: usize, - mut derefd_ty: Ty<'tcx>) - { + mut derefd_ty: Ty<'tcx>) { debug!("constrain_autoderefs(deref_expr={:?}, derefs={}, derefd_ty={:?})", deref_expr, derefs, @@ -938,14 +940,17 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { let r_deref_expr = ty::ReScope(s_deref_expr); for i in 0..derefs { let method_call = MethodCall::autoderef(deref_expr.id, i as u32); - debug!("constrain_autoderefs: method_call={:?} (of {:?} total)", method_call, derefs); + debug!("constrain_autoderefs: method_call={:?} (of {:?} total)", + method_call, + derefs); let method = self.tables.borrow().method_map.get(&method_call).map(|m| m.clone()); derefd_ty = match method { Some(method) => { debug!("constrain_autoderefs: #{} is overloaded, method={:?}", - i, method); + i, + method); let origin = infer::ParameterOrigin::OverloadedDeref; self.substs_wf_in_scope(origin, method.substs, deref_expr.span, r_deref_expr); @@ -959,50 +964,46 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { let (m, r) = match self_ty.sty { ty::TyRef(r, ref m) => (m.mutbl, r), _ => { - span_bug!( - deref_expr.span, - "bad overloaded deref type {:?}", - method.ty) + span_bug!(deref_expr.span, "bad overloaded deref type {:?}", method.ty) } }; - debug!("constrain_autoderefs: receiver r={:?} m={:?}", - r, m); + debug!("constrain_autoderefs: receiver r={:?} m={:?}", r, m); { let mc = mc::MemCategorizationContext::new(self); let self_cmt = ignore_err!(mc.cat_expr_autoderefd(deref_expr, i)); - debug!("constrain_autoderefs: self_cmt={:?}", - self_cmt); - self.link_region(deref_expr.span, r, - ty::BorrowKind::from_mutbl(m), self_cmt); + debug!("constrain_autoderefs: self_cmt={:?}", self_cmt); + self.link_region(deref_expr.span, + r, + ty::BorrowKind::from_mutbl(m), + self_cmt); } // Specialized version of constrain_call. - self.type_must_outlive(infer::CallRcvr(deref_expr.span), - self_ty, r_deref_expr); + self.type_must_outlive(infer::CallRcvr(deref_expr.span), self_ty, r_deref_expr); match fn_sig.output { ty::FnConverging(return_type) => { self.type_must_outlive(infer::CallReturn(deref_expr.span), - return_type, r_deref_expr); + return_type, + r_deref_expr); return_type } - ty::FnDiverging => bug!() + ty::FnDiverging => bug!(), } } - None => derefd_ty + None => derefd_ty, }; - if let ty::TyRef(r_ptr, _) = derefd_ty.sty { - self.mk_subregion_due_to_dereference(deref_expr.span, - r_deref_expr, *r_ptr); + if let ty::TyRef(r_ptr, _) = derefd_ty.sty { + self.mk_subregion_due_to_dereference(deref_expr.span, r_deref_expr, *r_ptr); } match derefd_ty.builtin_deref(true, ty::NoPreference) { Some(mt) => derefd_ty = mt.ty, - /* if this type can't be dereferenced, then there's already an error - in the session saying so. Just bail out for now */ - None => break + // if this type can't be dereferenced, then there's already an error + // in the session saying so. Just bail out for now + None => break, } } } @@ -1012,12 +1013,11 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { minimum_lifetime: ty::Region, maximum_lifetime: ty::Region) { self.sub_regions(infer::DerefPointer(deref_span), - minimum_lifetime, maximum_lifetime) + minimum_lifetime, + maximum_lifetime) } - fn check_safety_of_rvalue_destructor_if_necessary(&mut self, - cmt: mc::cmt<'tcx>, - span: Span) { + fn check_safety_of_rvalue_destructor_if_necessary(&mut self, cmt: mc::cmt<'tcx>, span: Span) { match cmt.cat { Categorization::Rvalue(region) => { match region { @@ -1043,10 +1043,7 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { /// Invoked on any index expression that occurs. Checks that if this is a slice /// being indexed, the lifetime of the pointer includes the deref expr. - fn constrain_index(&mut self, - index_expr: &hir::Expr, - indexed_ty: Ty<'tcx>) - { + fn constrain_index(&mut self, index_expr: &hir::Expr, indexed_ty: Ty<'tcx>) { debug!("constrain_index(index_expr=?, indexed_ty={}", self.ty_to_string(indexed_ty)); @@ -1054,8 +1051,7 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { if let ty::TyRef(r_ptr, mt) = indexed_ty.sty { match mt.ty.sty { ty::TySlice(_) | ty::TyStr => { - self.sub_regions(infer::IndexSlice(index_expr.span), - r_index_expr, *r_ptr); + self.sub_regions(infer::IndexSlice(index_expr.span), r_index_expr, *r_ptr); } _ => {} } @@ -1065,30 +1061,32 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { /// Guarantees that any lifetimes which appear in the type of the node `id` (after applying /// adjustments) are valid for at least `minimum_lifetime` fn type_of_node_must_outlive(&mut self, - origin: infer::SubregionOrigin<'tcx>, - id: ast::NodeId, - minimum_lifetime: ty::Region) - { + origin: infer::SubregionOrigin<'tcx>, + id: ast::NodeId, + minimum_lifetime: ty::Region) { let tcx = self.tcx; // Try to resolve the type. If we encounter an error, then typeck // is going to fail anyway, so just stop here and let typeck // report errors later on in the writeback phase. let ty0 = self.resolve_node_type(id); - let ty = ty0.adjust(tcx, origin.span(), id, + let ty = ty0.adjust(tcx, + origin.span(), + id, self.tables.borrow().adjustments.get(&id), |method_call| self.resolve_method_type(method_call)); debug!("constrain_regions_in_type_of_node(\ ty={}, ty0={}, id={}, minimum_lifetime={:?})", - ty, ty0, - id, minimum_lifetime); + ty, + ty0, + id, + minimum_lifetime); self.type_must_outlive(origin, ty, minimum_lifetime); } /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the /// resulting pointer is linked to the lifetime of its guarantor (if any). - fn link_addr_of(&mut self, expr: &hir::Expr, - mutability: hir::Mutability, base: &hir::Expr) { + fn link_addr_of(&mut self, expr: &hir::Expr, mutability: hir::Mutability, base: &hir::Expr) { debug!("link_addr_of(expr={:?}, base={:?})", expr, base); let cmt = { @@ -1107,7 +1105,9 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { fn link_local(&self, local: &hir::Local) { debug!("regionck::for_local()"); let init_expr = match local.init { - None => { return; } + None => { + return; + } Some(ref expr) => &**expr, }; let mc = mc::MemCategorizationContext::new(self); @@ -1140,10 +1140,7 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { let arg_ty = self.node_ty(arg.id); let re_scope = ty::ReScope(body_scope); let arg_cmt = mc.cat_rvalue(arg.id, arg.ty.span, re_scope, arg_ty); - debug!("arg_ty={:?} arg_cmt={:?} arg={:?}", - arg_ty, - arg_cmt, - arg); + debug!("arg_ty={:?} arg_cmt={:?} arg={:?}", arg_ty, arg_cmt, arg); self.link_pattern(mc, arg_cmt, &arg.pat); } } @@ -1157,25 +1154,20 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { debug!("link_pattern(discr_cmt={:?}, root_pat={:?})", discr_cmt, root_pat); - let _ = mc.cat_pattern(discr_cmt, root_pat, |_, sub_cmt, sub_pat| { - match sub_pat.node { - // `ref x` pattern - PatKind::Binding(hir::BindByRef(mutbl), _, _) => { - self.link_region_from_node_type(sub_pat.span, sub_pat.id, - mutbl, sub_cmt); - } - _ => {} + let _ = mc.cat_pattern(discr_cmt, root_pat, |_, sub_cmt, sub_pat| { + match sub_pat.node { + // `ref x` pattern + PatKind::Binding(hir::BindByRef(mutbl), _, _) => { + self.link_region_from_node_type(sub_pat.span, sub_pat.id, mutbl, sub_cmt); } - }); + _ => {} + } + }); } /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being /// autoref'd. - fn link_autoref(&self, - expr: &hir::Expr, - autoderefs: usize, - autoref: &adjustment::AutoRef) - { + fn link_autoref(&self, expr: &hir::Expr, autoderefs: usize, autoref: &adjustment::AutoRef) { debug!("link_autoref(autoref={:?})", autoref); let mc = mc::MemCategorizationContext::new(self); let expr_cmt = ignore_err!(mc.cat_expr_autoderefd(expr, autoderefs)); @@ -1183,8 +1175,7 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { match *autoref { adjustment::AutoPtr(r, m) => { - self.link_region(expr.span, r, - ty::BorrowKind::from_mutbl(m), expr_cmt); + self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m), expr_cmt); } adjustment::AutoUnsafe(m) => { @@ -1196,11 +1187,10 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { /// Computes the guarantor for cases where the `expr` is being passed by implicit reference and /// must outlive `callee_scope`. - fn link_by_ref(&self, - expr: &hir::Expr, - callee_scope: CodeExtent) { + fn link_by_ref(&self, expr: &hir::Expr, callee_scope: CodeExtent) { debug!("link_by_ref(expr={:?}, callee_scope={:?})", - expr, callee_scope); + expr, + callee_scope); let mc = mc::MemCategorizationContext::new(self); let expr_cmt = ignore_err!(mc.cat_expr(expr)); let borrow_region = ty::ReScope(callee_scope); @@ -1215,13 +1205,14 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { mutbl: hir::Mutability, cmt_borrowed: mc::cmt<'tcx>) { debug!("link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={:?})", - id, mutbl, cmt_borrowed); + id, + mutbl, + cmt_borrowed); let rptr_ty = self.resolve_node_type(id); if let ty::TyRef(&r, _) = rptr_ty.sty { - debug!("rptr_ty={}", rptr_ty); - self.link_region(span, &r, ty::BorrowKind::from_mutbl(mutbl), - cmt_borrowed); + debug!("rptr_ty={}", rptr_ty); + self.link_region(span, &r, ty::BorrowKind::from_mutbl(mutbl), cmt_borrowed); } } @@ -1246,13 +1237,14 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { borrow_kind, borrow_cmt); match borrow_cmt.cat.clone() { - Categorization::Deref(ref_cmt, _, - mc::Implicit(ref_kind, ref_region)) | - Categorization::Deref(ref_cmt, _, - mc::BorrowedPtr(ref_kind, ref_region)) => { + Categorization::Deref(ref_cmt, _, mc::Implicit(ref_kind, ref_region)) | + Categorization::Deref(ref_cmt, _, mc::BorrowedPtr(ref_kind, ref_region)) => { match self.link_reborrowed_region(span, - borrow_region, borrow_kind, - ref_cmt, ref_region, ref_kind, + borrow_region, + borrow_kind, + ref_cmt, + ref_region, + ref_kind, borrow_cmt.note) { Some((c, k)) => { borrow_cmt = c; @@ -1334,8 +1326,7 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { ref_region: ty::Region, mut ref_kind: ty::BorrowKind, note: mc::Note) - -> Option<(mc::cmt<'tcx>, ty::BorrowKind)> - { + -> Option<(mc::cmt<'tcx>, ty::BorrowKind)> { // Possible upvar ID we may need later to create an entry in the // maybe link map. @@ -1352,7 +1343,7 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { infer::ReborrowUpvar(span, *upvar_id) } _ => { - span_bug!( span, "Illegal upvar id: {:?}", upvar_id); + span_bug!(span, "Illegal upvar id: {:?}", upvar_id); } } } @@ -1362,9 +1353,7 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { // link infer::ReborrowUpvar(span, *upvar_id) } - _ => { - infer::Reborrow(span) - } + _ => infer::Reborrow(span), }; debug!("link_reborrowed_region: {:?} <= {:?}", @@ -1381,10 +1370,8 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { // borrowck requires a unique path to the `&mut` reference but not // necessarily a *mutable* path. let new_borrow_kind = match borrow_kind { - ty::ImmBorrow => - ty::ImmBorrow, - ty::MutBorrow | ty::UniqueImmBorrow => - ty::UniqueImmBorrow + ty::ImmBorrow => ty::ImmBorrow, + ty::MutBorrow | ty::UniqueImmBorrow => ty::UniqueImmBorrow, }; // Decide whether we need to recurse and link any regions within @@ -1447,7 +1434,10 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { expr_region={:?}, \ origin={:?}, \ expr_span={:?})", - substs, expr_region, origin, expr_span); + substs, + expr_region, + origin, + expr_span); let origin = infer::ParameterInScope(origin, expr_span); @@ -1467,8 +1457,7 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { pub fn type_must_outlive(&self, origin: infer::SubregionOrigin<'tcx>, ty: Ty<'tcx>, - region: ty::Region) - { + region: ty::Region) { let ty = self.resolve_type(ty); debug!("type_must_outlive(ty={:?}, region={:?}, origin={:?})", @@ -1485,8 +1474,7 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { fn components_must_outlive(&self, origin: infer::SubregionOrigin<'tcx>, components: Vec>, - region: ty::Region) - { + region: ty::Region) { for component in components { let origin = origin.clone(); match component { @@ -1519,7 +1507,9 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { region: ty::Region, param_ty: ty::ParamTy) { debug!("param_ty_must_outlive(region={:?}, param_ty={:?}, origin={:?})", - region, param_ty, origin); + region, + param_ty, + origin); let verify_bound = self.param_bound(param_ty); let generic = GenericKind::Param(param_ty); @@ -1529,10 +1519,11 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { fn projection_must_outlive(&self, origin: infer::SubregionOrigin<'tcx>, region: ty::Region, - projection_ty: ty::ProjectionTy<'tcx>) - { + projection_ty: ty::ProjectionTy<'tcx>) { debug!("projection_must_outlive(region={:?}, projection_ty={:?}, origin={:?})", - region, projection_ty, origin); + region, + projection_ty, + origin); // This case is thorny for inference. The fundamental problem is // that there are many cases where we have choice, and inference @@ -1553,8 +1544,7 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { // regions in this list. let env_bounds = self.projection_declared_bounds(origin.span(), projection_ty); - debug!("projection_must_outlive: env_bounds={:?}", - env_bounds); + debug!("projection_must_outlive: env_bounds={:?}", env_bounds); // If we know that the projection outlives 'static, then we're // done here. @@ -1579,7 +1569,7 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { // edges, which winds up enforcing the same condition. let needs_infer = { projection_ty.trait_ref.substs.types.iter().any(|t| t.needs_infer()) || - projection_ty.trait_ref.substs.regions.iter().any(|r| r.needs_infer()) + projection_ty.trait_ref.substs.regions.iter().any(|r| r.needs_infer()) }; if env_bounds.is_empty() && needs_infer { debug!("projection_must_outlive: no declared bounds"); @@ -1605,11 +1595,13 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { // other conditions if !env_bounds.is_empty() && env_bounds[1..].iter().all(|b| *b == env_bounds[0]) { let unique_bound = env_bounds[0]; - debug!("projection_must_outlive: unique declared bound = {:?}", unique_bound); - if projection_ty.trait_ref.substs.regions - .iter() - .any(|r| env_bounds.contains(r)) - { + debug!("projection_must_outlive: unique declared bound = {:?}", + unique_bound); + if projection_ty.trait_ref + .substs + .regions + .iter() + .any(|r| env_bounds.contains(r)) { debug!("projection_must_outlive: unique declared bound appears in trait ref"); self.sub_regions(origin.clone(), region, unique_bound); return; @@ -1628,24 +1620,19 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { fn type_bound(&self, span: Span, ty: Ty<'tcx>) -> VerifyBound { match ty.sty { - ty::TyParam(p) => { - self.param_bound(p) - } + ty::TyParam(p) => self.param_bound(p), ty::TyProjection(data) => { let declared_bounds = self.projection_declared_bounds(span, data); self.projection_bound(span, declared_bounds, data) } - _ => { - self.recursive_type_bound(span, ty) - } + _ => self.recursive_type_bound(span, ty), } } fn param_bound(&self, param_ty: ty::ParamTy) -> VerifyBound { let param_env = &self.parameter_environment; - debug!("param_bound(param_ty={:?})", - param_ty); + debug!("param_bound(param_ty={:?})", param_ty); let mut param_bounds = self.declared_generic_bounds_from_env(GenericKind::Param(param_ty)); @@ -1659,8 +1646,7 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { fn projection_declared_bounds(&self, span: Span, projection_ty: ty::ProjectionTy<'tcx>) - -> Vec - { + -> Vec { // First assemble bounds from where clauses and traits. let mut declared_bounds = @@ -1678,7 +1664,8 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { projection_ty: ty::ProjectionTy<'tcx>) -> VerifyBound { debug!("projection_bound(declared_bounds={:?}, projection_ty={:?})", - declared_bounds, projection_ty); + declared_bounds, + projection_ty); // see the extensive comment in projection_must_outlive @@ -1709,9 +1696,7 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { } } - fn declared_generic_bounds_from_env(&self, generic: GenericKind<'tcx>) - -> Vec - { + fn declared_generic_bounds_from_env(&self, generic: GenericKind<'tcx>) -> Vec { let param_env = &self.parameter_environment; // To start, collect bounds from user: @@ -1730,9 +1715,7 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { // well-formed, then, A must be lower-generic by `'a`, but we // don't know that this holds from first principles. for &(r, p) in &self.region_bound_pairs { - debug!("generic={:?} p={:?}", - generic, - p); + debug!("generic={:?} p={:?}", generic, p); if generic == p { param_bounds.push(r); } @@ -1744,13 +1727,10 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { fn declared_projection_bounds_from_trait(&self, span: Span, projection_ty: ty::ProjectionTy<'tcx>) - -> Vec - { - debug!("projection_bounds(projection_ty={:?})", - projection_ty); + -> Vec { + debug!("projection_bounds(projection_ty={:?})", projection_ty); - let ty = self.tcx.mk_projection(projection_ty.trait_ref.clone(), - projection_ty.item_name); + let ty = self.tcx.mk_projection(projection_ty.trait_ref.clone(), projection_ty.item_name); // Say we have a projection `>::SomeType`. We are interested // in looking for a trait definition like: @@ -1769,19 +1749,19 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { // we're only interesting in `T : 'a` style predicates: let outlives = match predicate { ty::Predicate::TypeOutlives(data) => data, - _ => { return None; } + _ => { + return None; + } }; - debug!("projection_bounds: outlives={:?} (1)", - outlives); + debug!("projection_bounds: outlives={:?} (1)", outlives); // apply the substitutions (and normalize any projected types) let outlives = self.instantiate_type_scheme(span, projection_ty.trait_ref.substs, &outlives); - debug!("projection_bounds: outlives={:?} (2)", - outlives); + debug!("projection_bounds: outlives={:?} (2)", outlives); let region_result = self.commit_if_ok(|_| { let (outlives, _) = @@ -1790,8 +1770,7 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { infer::AssocTypeProjection(projection_ty.item_name), &outlives); - debug!("projection_bounds: outlives={:?} (3)", - outlives); + debug!("projection_bounds: outlives={:?} (3)", outlives); // check whether this predicate applies to our current projection match self.eq_types(false, TypeOrigin::Misc(span), ty, outlives.0) { @@ -1800,12 +1779,11 @@ impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> { assert!(obligations.is_empty()); Ok(outlives.1) } - Err(_) => { Err(()) } + Err(_) => Err(()), } }); - debug!("projection_bounds: region_result={:?}", - region_result); + debug!("projection_bounds: region_result={:?}", region_result); region_result.ok() }) diff --git a/src/librustc_typeck/check/upvar.rs b/src/librustc_typeck/check/upvar.rs index 19964d736f592..a66eabd367608 100644 --- a/src/librustc_typeck/check/upvar.rs +++ b/src/librustc_typeck/check/upvar.rs @@ -53,8 +53,8 @@ use syntax::codemap::Span; use rustc::hir; use rustc::hir::intravisit::{self, Visitor}; -/////////////////////////////////////////////////////////////////////////// -// PUBLIC ENTRY POINTS +/// //////////////////////////////////////////////////////////////////////// +/// PUBLIC ENTRY POINTS impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { pub fn closure_analyze_fn(&self, body: &hir::Block) { @@ -82,10 +82,10 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } } -/////////////////////////////////////////////////////////////////////////// -// SEED BORROW KIND +/// //////////////////////////////////////////////////////////////////////// +/// SEED BORROW KIND -struct SeedBorrowKind<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { +struct SeedBorrowKind<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> { fcx: &'a FnCtxt<'a, 'gcx, 'tcx>, closures_with_inferred_kinds: HashSet, } @@ -97,7 +97,7 @@ impl<'a, 'gcx, 'tcx, 'v> Visitor<'v> for SeedBorrowKind<'a, 'gcx, 'tcx> { self.check_closure(expr, cc, &body); } - _ => { } + _ => {} } intravisit::walk_expr(self, expr); @@ -106,19 +106,24 @@ impl<'a, 'gcx, 'tcx, 'v> Visitor<'v> for SeedBorrowKind<'a, 'gcx, 'tcx> { impl<'a, 'gcx, 'tcx> SeedBorrowKind<'a, 'gcx, 'tcx> { fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>) -> SeedBorrowKind<'a, 'gcx, 'tcx> { - SeedBorrowKind { fcx: fcx, closures_with_inferred_kinds: HashSet::new() } + SeedBorrowKind { + fcx: fcx, + closures_with_inferred_kinds: HashSet::new(), + } } fn check_closure(&mut self, expr: &hir::Expr, capture_clause: hir::CaptureClause, - _body: &hir::Block) - { + _body: &hir::Block) { let closure_def_id = self.fcx.tcx.map.local_def_id(expr.id); if !self.fcx.tables.borrow().closure_kinds.contains_key(&closure_def_id) { self.closures_with_inferred_kinds.insert(expr.id); - self.fcx.tables.borrow_mut().closure_kinds - .insert(closure_def_id, ty::ClosureKind::Fn); + self.fcx + .tables + .borrow_mut() + .closure_kinds + .insert(closure_def_id, ty::ClosureKind::Fn); debug!("check_closure: adding closure_id={:?} to closures_with_inferred_kinds", closure_def_id); } @@ -126,19 +131,21 @@ impl<'a, 'gcx, 'tcx> SeedBorrowKind<'a, 'gcx, 'tcx> { self.fcx.tcx.with_freevars(expr.id, |freevars| { for freevar in freevars { let var_node_id = freevar.def.var_id(); - let upvar_id = ty::UpvarId { var_id: var_node_id, - closure_expr_id: expr.id }; + let upvar_id = ty::UpvarId { + var_id: var_node_id, + closure_expr_id: expr.id, + }; debug!("seed upvar_id {:?}", upvar_id); let capture_kind = match capture_clause { - hir::CaptureByValue => { - ty::UpvarCapture::ByValue - } + hir::CaptureByValue => ty::UpvarCapture::ByValue, hir::CaptureByRef => { let origin = UpvarRegion(upvar_id, expr.span); let freevar_region = self.fcx.next_region_var(origin); - let upvar_borrow = ty::UpvarBorrow { kind: ty::ImmBorrow, - region: freevar_region }; + let upvar_borrow = ty::UpvarBorrow { + kind: ty::ImmBorrow, + region: freevar_region, + }; ty::UpvarCapture::ByRef(upvar_borrow) } }; @@ -149,10 +156,10 @@ impl<'a, 'gcx, 'tcx> SeedBorrowKind<'a, 'gcx, 'tcx> { } } -/////////////////////////////////////////////////////////////////////////// -// ADJUST BORROW KIND +/// //////////////////////////////////////////////////////////////////////// +/// ADJUST BORROW KIND -struct AdjustBorrowKind<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { +struct AdjustBorrowKind<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> { fcx: &'a FnCtxt<'a, 'gcx, 'tcx>, closures_with_inferred_kinds: &'a HashSet, } @@ -161,7 +168,10 @@ impl<'a, 'gcx, 'tcx> AdjustBorrowKind<'a, 'gcx, 'tcx> { fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>, closures_with_inferred_kinds: &'a HashSet) -> AdjustBorrowKind<'a, 'gcx, 'tcx> { - AdjustBorrowKind { fcx: fcx, closures_with_inferred_kinds: closures_with_inferred_kinds } + AdjustBorrowKind { + fcx: fcx, + closures_with_inferred_kinds: closures_with_inferred_kinds, + } } fn analyze_closure(&mut self, @@ -169,9 +179,8 @@ impl<'a, 'gcx, 'tcx> AdjustBorrowKind<'a, 'gcx, 'tcx> { span: Span, decl: &hir::FnDecl, body: &hir::Block) { - /*! - * Analysis starting point. - */ + //! Analysis starting point. + //! debug!("analyze_closure(id={:?}, body.id={:?})", id, body.id); @@ -196,17 +205,19 @@ impl<'a, 'gcx, 'tcx> AdjustBorrowKind<'a, 'gcx, 'tcx> { let closure_substs = match self.fcx.node_ty(id).sty { ty::TyClosure(_, ref substs) => substs, ref t => { - span_bug!( - span, - "type of closure expr {:?} is not a closure {:?}", - id, t); + span_bug!(span, + "type of closure expr {:?} is not a closure {:?}", + id, + t); } }; // Equate the type variables with the actual types. let final_upvar_tys = self.final_upvar_tys(id); debug!("analyze_closure: id={:?} closure_substs={:?} final_upvar_tys={:?}", - id, closure_substs, final_upvar_tys); + id, + closure_substs, + final_upvar_tys); for (&upvar_ty, final_upvar_ty) in closure_substs.upvar_tys.iter().zip(final_upvar_tys) { self.fcx.demand_eqtype(span, final_upvar_ty, upvar_ty); } @@ -238,38 +249,41 @@ impl<'a, 'gcx, 'tcx> AdjustBorrowKind<'a, 'gcx, 'tcx> { let freevar_ty = self.fcx.node_ty(freevar_node_id); let upvar_id = ty::UpvarId { var_id: freevar_node_id, - closure_expr_id: closure_id + closure_expr_id: closure_id, }; let capture = self.fcx.upvar_capture(upvar_id).unwrap(); debug!("freevar_node_id={:?} freevar_ty={:?} capture={:?}", - freevar_node_id, freevar_ty, capture); + freevar_node_id, + freevar_ty, + capture); match capture { ty::UpvarCapture::ByValue => freevar_ty, - ty::UpvarCapture::ByRef(borrow) => + ty::UpvarCapture::ByRef(borrow) => { tcx.mk_ref(tcx.mk_region(borrow.region), ty::TypeAndMut { ty: freevar_ty, mutbl: borrow.kind.to_mutbl_lossy(), - }), + }) + } } }) .collect() - }) + }) } - fn adjust_upvar_borrow_kind_for_consume(&self, - cmt: mc::cmt<'tcx>, - mode: euv::ConsumeMode) - { + fn adjust_upvar_borrow_kind_for_consume(&self, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) { debug!("adjust_upvar_borrow_kind_for_consume(cmt={:?}, mode={:?})", - cmt, mode); + cmt, + mode); // we only care about moves match mode { - euv::Copy => { return; } - euv::Move(_) => { } + euv::Copy => { + return; + } + euv::Move(_) => {} } // watch out for a move of the deref of a borrowed pointer; @@ -288,11 +302,9 @@ impl<'a, 'gcx, 'tcx> AdjustBorrowKind<'a, 'gcx, 'tcx> { upvar_id); // to move out of an upvar, this must be a FnOnce closure - self.adjust_closure_kind(upvar_id.closure_expr_id, - ty::ClosureKind::FnOnce); + self.adjust_closure_kind(upvar_id.closure_expr_id, ty::ClosureKind::FnOnce); - let upvar_capture_map = - &mut self.fcx.tables.borrow_mut().upvar_capture_map; + let upvar_capture_map = &mut self.fcx.tables.borrow_mut().upvar_capture_map; upvar_capture_map.insert(upvar_id, ty::UpvarCapture::ByValue); } mc::NoteClosureEnv(upvar_id) => { @@ -302,14 +314,12 @@ impl<'a, 'gcx, 'tcx> AdjustBorrowKind<'a, 'gcx, 'tcx> { // must still adjust the kind of the closure // to be a FnOnce closure to permit moves out // of the environment. - self.adjust_closure_kind(upvar_id.closure_expr_id, - ty::ClosureKind::FnOnce); - } - mc::NoteNone => { + self.adjust_closure_kind(upvar_id.closure_expr_id, ty::ClosureKind::FnOnce); } + mc::NoteNone => {} } } - _ => { } + _ => {} } } @@ -317,8 +327,7 @@ impl<'a, 'gcx, 'tcx> AdjustBorrowKind<'a, 'gcx, 'tcx> { /// to). If cmt contains any by-ref upvars, this implies that /// those upvars must be borrowed using an `&mut` borrow. fn adjust_upvar_borrow_kind_for_mut(&mut self, cmt: mc::cmt<'tcx>) { - debug!("adjust_upvar_borrow_kind_for_mut(cmt={:?})", - cmt); + debug!("adjust_upvar_borrow_kind_for_mut(cmt={:?})", cmt); match cmt.cat.clone() { Categorization::Deref(base, _, mc::Unique) | @@ -351,8 +360,7 @@ impl<'a, 'gcx, 'tcx> AdjustBorrowKind<'a, 'gcx, 'tcx> { } fn adjust_upvar_borrow_kind_for_unique(&self, cmt: mc::cmt<'tcx>) { - debug!("adjust_upvar_borrow_kind_for_unique(cmt={:?})", - cmt); + debug!("adjust_upvar_borrow_kind_for_unique(cmt={:?})", cmt); match cmt.cat.clone() { Categorization::Deref(base, _, mc::Unique) | @@ -376,16 +384,11 @@ impl<'a, 'gcx, 'tcx> AdjustBorrowKind<'a, 'gcx, 'tcx> { Categorization::StaticItem | Categorization::Rvalue(_) | Categorization::Local(_) | - Categorization::Upvar(..) => { - } + Categorization::Upvar(..) => {} } } - fn try_adjust_upvar_deref(&self, - note: &mc::Note, - borrow_kind: ty::BorrowKind) - -> bool - { + fn try_adjust_upvar_deref(&self, note: &mc::Note, borrow_kind: ty::BorrowKind) -> bool { assert!(match borrow_kind { ty::MutBorrow => true, ty::UniqueImmBorrow => true, @@ -419,9 +422,7 @@ impl<'a, 'gcx, 'tcx> AdjustBorrowKind<'a, 'gcx, 'tcx> { true } - mc::NoteNone => { - false - } + mc::NoteNone => false, } } @@ -435,7 +436,9 @@ impl<'a, 'gcx, 'tcx> AdjustBorrowKind<'a, 'gcx, 'tcx> { upvar_capture: &mut ty::UpvarCapture, kind: ty::BorrowKind) { debug!("adjust_upvar_borrow_kind(upvar_id={:?}, upvar_capture={:?}, kind={:?})", - upvar_id, upvar_capture, kind); + upvar_id, + upvar_capture, + kind); match *upvar_capture { ty::UpvarCapture::ByValue => { @@ -453,18 +456,16 @@ impl<'a, 'gcx, 'tcx> AdjustBorrowKind<'a, 'gcx, 'tcx> { (ty::ImmBorrow, ty::ImmBorrow) | (ty::UniqueImmBorrow, ty::ImmBorrow) | (ty::UniqueImmBorrow, ty::UniqueImmBorrow) | - (ty::MutBorrow, _) => { - } + (ty::MutBorrow, _) => {} } } } } - fn adjust_closure_kind(&self, - closure_id: ast::NodeId, - new_kind: ty::ClosureKind) { + fn adjust_closure_kind(&self, closure_id: ast::NodeId, new_kind: ty::ClosureKind) { debug!("adjust_closure_kind(closure_id={}, new_kind={:?})", - closure_id, new_kind); + closure_id, + new_kind); if !self.closures_with_inferred_kinds.contains(&closure_id) { return; @@ -475,7 +476,9 @@ impl<'a, 'gcx, 'tcx> AdjustBorrowKind<'a, 'gcx, 'tcx> { let existing_kind = *closure_kinds.get(&closure_def_id).unwrap(); debug!("adjust_closure_kind: closure_id={}, existing_kind={:?}, new_kind={:?}", - closure_id, existing_kind, new_kind); + closure_id, + existing_kind, + new_kind); match (existing_kind, new_kind) { (ty::ClosureKind::Fn, ty::ClosureKind::Fn) | @@ -501,8 +504,7 @@ impl<'a, 'gcx, 'tcx, 'v> Visitor<'v> for AdjustBorrowKind<'a, 'gcx, 'tcx> { decl: &'v hir::FnDecl, body: &'v hir::Block, span: Span, - id: ast::NodeId) - { + id: ast::NodeId) { intravisit::walk_fn(self, fn_kind, decl, body, span); self.analyze_closure(id, span, decl, body); } @@ -513,8 +515,7 @@ impl<'a, 'gcx, 'tcx> euv::Delegate<'tcx> for AdjustBorrowKind<'a, 'gcx, 'tcx> { _consume_id: ast::NodeId, _consume_span: Span, cmt: mc::cmt<'tcx>, - mode: euv::ConsumeMode) - { + mode: euv::ConsumeMode) { debug!("consume(cmt={:?},mode={:?})", cmt, mode); self.adjust_upvar_borrow_kind_for_consume(cmt, mode); } @@ -522,14 +523,13 @@ impl<'a, 'gcx, 'tcx> euv::Delegate<'tcx> for AdjustBorrowKind<'a, 'gcx, 'tcx> { fn matched_pat(&mut self, _matched_pat: &hir::Pat, _cmt: mc::cmt<'tcx>, - _mode: euv::MatchMode) - {} + _mode: euv::MatchMode) { + } fn consume_pat(&mut self, _consume_pat: &hir::Pat, cmt: mc::cmt<'tcx>, - mode: euv::ConsumeMode) - { + mode: euv::ConsumeMode) { debug!("consume_pat(cmt={:?},mode={:?})", cmt, mode); self.adjust_upvar_borrow_kind_for_consume(cmt, mode); } @@ -540,13 +540,14 @@ impl<'a, 'gcx, 'tcx> euv::Delegate<'tcx> for AdjustBorrowKind<'a, 'gcx, 'tcx> { cmt: mc::cmt<'tcx>, _loan_region: ty::Region, bk: ty::BorrowKind, - _loan_cause: euv::LoanCause) - { + _loan_cause: euv::LoanCause) { debug!("borrow(borrow_id={}, cmt={:?}, bk={:?})", - borrow_id, cmt, bk); + borrow_id, + cmt, + bk); match bk { - ty::ImmBorrow => { } + ty::ImmBorrow => {} ty::UniqueImmBorrow => { self.adjust_upvar_borrow_kind_for_unique(cmt); } @@ -556,19 +557,14 @@ impl<'a, 'gcx, 'tcx> euv::Delegate<'tcx> for AdjustBorrowKind<'a, 'gcx, 'tcx> { } } - fn decl_without_init(&mut self, - _id: ast::NodeId, - _span: Span) - {} + fn decl_without_init(&mut self, _id: ast::NodeId, _span: Span) {} fn mutate(&mut self, _assignment_id: ast::NodeId, _assignment_span: Span, assignee_cmt: mc::cmt<'tcx>, - _mode: euv::MutateMode) - { - debug!("mutate(assignee_cmt={:?})", - assignee_cmt); + _mode: euv::MutateMode) { + debug!("mutate(assignee_cmt={:?})", assignee_cmt); self.adjust_upvar_borrow_kind_for_mut(assignee_cmt); } diff --git a/src/librustc_typeck/check/wfcheck.rs b/src/librustc_typeck/check/wfcheck.rs index e0a34189773b1..4ec8af3b71358 100644 --- a/src/librustc_typeck/check/wfcheck.rs +++ b/src/librustc_typeck/check/wfcheck.rs @@ -9,23 +9,23 @@ // except according to those terms. use check::FnCtxt; -use constrained_type_params::{identify_constrained_type_params, Parameter}; +use constrained_type_params::{Parameter, identify_constrained_type_params}; use CrateCtxt; use hir::def_id::DefId; -use middle::region::{CodeExtent}; -use rustc::ty::subst::{self, TypeSpace, FnSpace, ParamSpace, SelfSpace}; +use middle::region::CodeExtent; +use rustc::ty::subst::{self, FnSpace, ParamSpace, SelfSpace, TypeSpace}; use rustc::traits; use rustc::ty::{self, Ty, TyCtxt}; use std::collections::HashSet; use syntax::ast; -use syntax::codemap::{Span}; +use syntax::codemap::Span; use syntax::errors::DiagnosticBuilder; use syntax::parse::token::keywords; use rustc::hir::intravisit::{self, Visitor}; use rustc::hir; -pub struct CheckTypeWellFormedVisitor<'ccx, 'tcx:'ccx> { +pub struct CheckTypeWellFormedVisitor<'ccx, 'tcx: 'ccx> { ccx: &'ccx CrateCtxt<'ccx, 'tcx>, code: traits::ObligationCauseCode<'tcx>, } @@ -33,27 +33,29 @@ pub struct CheckTypeWellFormedVisitor<'ccx, 'tcx:'ccx> { /// Helper type of a temporary returned by .for_item(...). /// Necessary because we can't write the following bound: /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(FnCtxt<'b, 'gcx, 'tcx>). -struct CheckWfFcxBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { +struct CheckWfFcxBuilder<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> { inherited: super::InheritedBuilder<'a, 'gcx, 'tcx>, code: traits::ObligationCauseCode<'gcx>, id: ast::NodeId, - span: Span + span: Span, } impl<'a, 'gcx, 'tcx> CheckWfFcxBuilder<'a, 'gcx, 'tcx> { - fn with_fcx(&'tcx mut self, f: F) where - F: for<'b> FnOnce(&FnCtxt<'b, 'gcx, 'tcx>, - &mut CheckTypeWellFormedVisitor<'b, 'gcx>) -> Vec> + fn with_fcx(&'tcx mut self, f: F) + where F: for<'b> FnOnce(&FnCtxt<'b, 'gcx, 'tcx>, + &mut CheckTypeWellFormedVisitor<'b, 'gcx>) + -> Vec> { let code = self.code.clone(); let id = self.id; let span = self.span; self.inherited.enter(|inh| { let fcx = FnCtxt::new(&inh, ty::FnDiverging, id); - let wf_tys = f(&fcx, &mut CheckTypeWellFormedVisitor { - ccx: fcx.ccx, - code: code - }); + let wf_tys = f(&fcx, + &mut CheckTypeWellFormedVisitor { + ccx: fcx.ccx, + code: code, + }); fcx.select_all_obligations_or_error(); fcx.regionck_item(id, span, &wf_tys); }); @@ -61,11 +63,10 @@ impl<'a, 'gcx, 'tcx> CheckWfFcxBuilder<'a, 'gcx, 'tcx> { } impl<'ccx, 'gcx> CheckTypeWellFormedVisitor<'ccx, 'gcx> { - pub fn new(ccx: &'ccx CrateCtxt<'ccx, 'gcx>) - -> CheckTypeWellFormedVisitor<'ccx, 'gcx> { + pub fn new(ccx: &'ccx CrateCtxt<'ccx, 'gcx>) -> CheckTypeWellFormedVisitor<'ccx, 'gcx> { CheckTypeWellFormedVisitor { ccx: ccx, - code: traits::ObligationCauseCode::MiscObligation + code: traits::ObligationCauseCode::MiscObligation, } } @@ -108,8 +109,7 @@ impl<'ccx, 'gcx> CheckTypeWellFormedVisitor<'ccx, 'gcx> { /// /// won't be allowed unless there's an *explicit* implementation of `Send` /// for `T` - hir::ItemImpl(_, hir::ImplPolarity::Positive, _, - ref trait_ref, ref self_ty, _) => { + hir::ItemImpl(_, hir::ImplPolarity::Positive, _, ref trait_ref, ref self_ty, _) => { self.check_impl(item, self_ty, trait_ref); } hir::ItemImpl(_, hir::ImplPolarity::Negative, _, Some(_), _, _) => { @@ -136,16 +136,12 @@ impl<'ccx, 'gcx> CheckTypeWellFormedVisitor<'ccx, 'gcx> { self.check_item_type(item); } hir::ItemStruct(ref struct_def, ref ast_generics) => { - self.check_type_defn(item, |fcx| { - vec![fcx.struct_variant(struct_def)] - }); + self.check_type_defn(item, |fcx| vec![fcx.struct_variant(struct_def)]); self.check_variances_for_type_defn(item, ast_generics); } hir::ItemEnum(ref enum_def, ref ast_generics) => { - self.check_type_defn(item, |fcx| { - fcx.enum_variants(enum_def) - }); + self.check_type_defn(item, |fcx| fcx.enum_variants(enum_def)); self.check_variances_for_type_defn(item, ast_generics); } @@ -166,8 +162,9 @@ impl<'ccx, 'gcx> CheckTypeWellFormedVisitor<'ccx, 'gcx> { let (mut implied_bounds, self_ty) = match item.container() { ty::TraitContainer(_) => (vec![], fcx.tcx.mk_self_type()), - ty::ImplContainer(def_id) => (fcx.impl_implied_bounds(def_id, span), - fcx.tcx.lookup_item_type(def_id).ty) + ty::ImplContainer(def_id) => { + (fcx.impl_implied_bounds(def_id, span), fcx.tcx.lookup_item_type(def_id).ty) + } }; match item { @@ -179,10 +176,13 @@ impl<'ccx, 'gcx> CheckTypeWellFormedVisitor<'ccx, 'gcx> { reject_shadowing_type_parameters(fcx.tcx, span, &method.generics); let method_ty = fcx.instantiate_type_scheme(span, free_substs, &method.fty); let predicates = fcx.instantiate_bounds(span, free_substs, &method.predicates); - this.check_fn_or_method(fcx, span, &method_ty, &predicates, - free_id_outlive, &mut implied_bounds); - this.check_method_receiver(fcx, span, &method, - free_id_outlive, self_ty); + this.check_fn_or_method(fcx, + span, + &method_ty, + &predicates, + free_id_outlive, + &mut implied_bounds); + this.check_method_receiver(fcx, span, &method, free_id_outlive, self_ty); } ty::TypeTraitItem(assoc_type) => { if let Some(ref ty) = assoc_type.ty { @@ -196,26 +196,23 @@ impl<'ccx, 'gcx> CheckTypeWellFormedVisitor<'ccx, 'gcx> { }) } - fn for_item<'tcx>(&self, item: &hir::Item) - -> CheckWfFcxBuilder<'ccx, 'gcx, 'tcx> { + fn for_item<'tcx>(&self, item: &hir::Item) -> CheckWfFcxBuilder<'ccx, 'gcx, 'tcx> { self.for_id(item.id, item.span) } - fn for_id<'tcx>(&self, id: ast::NodeId, span: Span) - -> CheckWfFcxBuilder<'ccx, 'gcx, 'tcx> { + fn for_id<'tcx>(&self, id: ast::NodeId, span: Span) -> CheckWfFcxBuilder<'ccx, 'gcx, 'tcx> { let param_env = ty::ParameterEnvironment::for_item(self.ccx.tcx, id); CheckWfFcxBuilder { inherited: self.ccx.inherited(Some(param_env)), code: self.code.clone(), id: id, - span: span + span: span, } } /// In a type definition, we check that to ensure that the types of the fields are well-formed. - fn check_type_defn(&mut self, item: &hir::Item, mut lookup_fields: F) where - F: for<'fcx, 'tcx> FnMut(&FnCtxt<'fcx, 'gcx, 'tcx>) - -> Vec> + fn check_type_defn(&mut self, item: &hir::Item, mut lookup_fields: F) + where F: for<'fcx, 'tcx> FnMut(&FnCtxt<'fcx, 'gcx, 'tcx>) -> Vec> { self.for_item(item).with_fcx(|fcx, this| { let variants = lookup_fields(fcx); @@ -248,10 +245,7 @@ impl<'ccx, 'gcx> CheckTypeWellFormedVisitor<'ccx, 'gcx> { }); } - fn check_trait(&mut self, - item: &hir::Item, - items: &[hir::TraitItem]) - { + fn check_trait(&mut self, item: &hir::Item, items: &[hir::TraitItem]) { let trait_def_id = self.tcx().map.local_def_id(item.id); if self.tcx().trait_has_default_impl(trait_def_id) { @@ -269,10 +263,7 @@ impl<'ccx, 'gcx> CheckTypeWellFormedVisitor<'ccx, 'gcx> { }); } - fn check_item_fn(&mut self, - item: &hir::Item, - body: &hir::Block) - { + fn check_item_fn(&mut self, item: &hir::Item, body: &hir::Block) { self.for_item(item).with_fcx(|fcx, this| { let free_substs = &fcx.parameter_environment.free_substs; let type_scheme = fcx.tcx.lookup_item_type(fcx.tcx.map.local_def_id(item.id)); @@ -289,15 +280,17 @@ impl<'ccx, 'gcx> CheckTypeWellFormedVisitor<'ccx, 'gcx> { let mut implied_bounds = vec![]; let free_id_outlive = fcx.tcx.region_maps.call_site_extent(item.id, body.id); - this.check_fn_or_method(fcx, item.span, bare_fn_ty, &predicates, - free_id_outlive, &mut implied_bounds); + this.check_fn_or_method(fcx, + item.span, + bare_fn_ty, + &predicates, + free_id_outlive, + &mut implied_bounds); implied_bounds }) } - fn check_item_type(&mut self, - item: &hir::Item) - { + fn check_item_type(&mut self, item: &hir::Item) { debug!("check_item_type: {:?}", item); self.for_item(item).with_fcx(|fcx, this| { @@ -316,8 +309,7 @@ impl<'ccx, 'gcx> CheckTypeWellFormedVisitor<'ccx, 'gcx> { fn check_impl(&mut self, item: &hir::Item, ast_self_ty: &hir::Ty, - ast_trait_ref: &Option) - { + ast_trait_ref: &Option) { debug!("check_impl: {:?}", item); self.for_item(item).with_fcx(|fcx, this| { @@ -327,14 +319,13 @@ impl<'ccx, 'gcx> CheckTypeWellFormedVisitor<'ccx, 'gcx> { match *ast_trait_ref { Some(ref ast_trait_ref) => { let trait_ref = fcx.tcx.impl_trait_ref(item_def_id).unwrap(); - let trait_ref = - fcx.instantiate_type_scheme( - ast_trait_ref.path.span, free_substs, &trait_ref); - let obligations = - ty::wf::trait_obligations(fcx, - fcx.body_id, - &trait_ref, - ast_trait_ref.path.span); + let trait_ref = fcx.instantiate_type_scheme(ast_trait_ref.path.span, + free_substs, + &trait_ref); + let obligations = ty::wf::trait_obligations(fcx, + fcx.body_id, + &trait_ref, + ast_trait_ref.path.span); for obligation in obligations { fcx.register_predicate(obligation); } @@ -357,15 +348,12 @@ impl<'ccx, 'gcx> CheckTypeWellFormedVisitor<'ccx, 'gcx> { fn check_where_clauses<'fcx, 'tcx>(&mut self, fcx: &FnCtxt<'fcx, 'gcx, 'tcx>, span: Span, - predicates: &ty::InstantiatedPredicates<'tcx>) - { - let obligations = - predicates.predicates - .iter() - .flat_map(|p| ty::wf::predicate_obligations(fcx, - fcx.body_id, - p, - span)); + predicates: &ty::InstantiatedPredicates<'tcx>) { + let obligations = predicates.predicates + .iter() + .flat_map(|p| { + ty::wf::predicate_obligations(fcx, fcx.body_id, p, span) + }); for obligation in obligations { fcx.register_predicate(obligation); @@ -378,8 +366,7 @@ impl<'ccx, 'gcx> CheckTypeWellFormedVisitor<'ccx, 'gcx> { fty: &'tcx ty::BareFnTy<'tcx>, predicates: &ty::InstantiatedPredicates<'tcx>, free_id_outlive: CodeExtent, - implied_bounds: &mut Vec>) - { + implied_bounds: &mut Vec>) { let free_substs = &fcx.parameter_environment.free_substs; let fty = fcx.instantiate_type_scheme(span, free_substs, &fty); let sig = fcx.tcx.liberate_late_bound_regions(free_id_outlive, &fty.sig); @@ -396,7 +383,7 @@ impl<'ccx, 'gcx> CheckTypeWellFormedVisitor<'ccx, 'gcx> { // FIXME(#25759) return types should not be implied bounds implied_bounds.push(output); } - ty::FnDiverging => { } + ty::FnDiverging => {} } self.check_where_clauses(fcx, span, predicates); @@ -407,8 +394,7 @@ impl<'ccx, 'gcx> CheckTypeWellFormedVisitor<'ccx, 'gcx> { span: Span, method: &ty::Method<'tcx>, free_id_outlive: CodeExtent, - self_ty: ty::Ty<'tcx>) - { + self_ty: ty::Ty<'tcx>) { // check that the type of the method's receiver matches the // method's first parameter. @@ -417,44 +403,48 @@ impl<'ccx, 'gcx> CheckTypeWellFormedVisitor<'ccx, 'gcx> { let sig = fcx.tcx.liberate_late_bound_regions(free_id_outlive, &fty.sig); debug!("check_method_receiver({:?},cat={:?},self_ty={:?},sig={:?})", - method.name, method.explicit_self, self_ty, sig); + method.name, + method.explicit_self, + self_ty, + sig); let rcvr_ty = match method.explicit_self { ty::ExplicitSelfCategory::Static => return, ty::ExplicitSelfCategory::ByValue => self_ty, ty::ExplicitSelfCategory::ByReference(region, mutability) => { - fcx.tcx.mk_ref(fcx.tcx.mk_region(region), ty::TypeAndMut { - ty: self_ty, - mutbl: mutability - }) + fcx.tcx.mk_ref(fcx.tcx.mk_region(region), + ty::TypeAndMut { + ty: self_ty, + mutbl: mutability, + }) } - ty::ExplicitSelfCategory::ByBox => fcx.tcx.mk_box(self_ty) + ty::ExplicitSelfCategory::ByBox => fcx.tcx.mk_box(self_ty), }; let rcvr_ty = fcx.instantiate_type_scheme(span, free_substs, &rcvr_ty); - let rcvr_ty = fcx.tcx.liberate_late_bound_regions(free_id_outlive, - &ty::Binder(rcvr_ty)); + let rcvr_ty = fcx.tcx.liberate_late_bound_regions(free_id_outlive, &ty::Binder(rcvr_ty)); debug!("check_method_receiver: receiver ty = {:?}", rcvr_ty); - fcx.require_same_types(span, sig.inputs[0], rcvr_ty, - "mismatched method receiver"); + fcx.require_same_types(span, sig.inputs[0], rcvr_ty, "mismatched method receiver"); } - fn check_variances_for_type_defn(&self, - item: &hir::Item, - ast_generics: &hir::Generics) - { + fn check_variances_for_type_defn(&self, item: &hir::Item, ast_generics: &hir::Generics) { let item_def_id = self.tcx().map.local_def_id(item.id); let ty_predicates = self.tcx().lookup_predicates(item_def_id); let variances = self.tcx().item_variances(item_def_id); - let mut constrained_parameters: HashSet<_> = - variances.types - .iter_enumerated() - .filter(|&(_, _, &variance)| variance != ty::Bivariant) - .map(|(space, index, _)| self.param_ty(ast_generics, space, index)) - .map(|p| Parameter::Type(p)) - .collect(); + let mut constrained_parameters: HashSet<_> = variances.types + .iter_enumerated() + .filter(|&(_, _, &variance)| { + variance != ty::Bivariant + }) + .map(|(space, index, _)| { + self.param_ty(ast_generics, + space, + index) + }) + .map(|p| Parameter::Type(p)) + .collect(); identify_constrained_type_params(ty_predicates.predicates.as_slice(), None, @@ -485,15 +475,18 @@ impl<'ccx, 'gcx> CheckTypeWellFormedVisitor<'ccx, 'gcx> { ast_generics: &hir::Generics, space: ParamSpace, index: usize) - -> ty::ParamTy - { + -> ty::ParamTy { let name = match space { TypeSpace => ast_generics.ty_params[index].name, SelfSpace => keywords::SelfType.name(), FnSpace => bug!("Fn space occupied?"), }; - ty::ParamTy { space: space, idx: index as u32, name: name } + ty::ParamTy { + space: space, + idx: index as u32, + name: name, + } } fn ty_param_span(&self, @@ -501,8 +494,7 @@ impl<'ccx, 'gcx> CheckTypeWellFormedVisitor<'ccx, 'gcx> { item: &hir::Item, space: ParamSpace, index: usize) - -> Span - { + -> Span { match space { TypeSpace => ast_generics.ty_params[index].span, SelfSpace => item.span, @@ -510,19 +502,15 @@ impl<'ccx, 'gcx> CheckTypeWellFormedVisitor<'ccx, 'gcx> { } } - fn report_bivariance(&self, - span: Span, - param_name: ast::Name) - { + fn report_bivariance(&self, span: Span, param_name: ast::Name) { let mut err = error_392(self.ccx, span, param_name); let suggested_marker_id = self.tcx().lang_items.phantom_data(); match suggested_marker_id { Some(def_id) => { - err.help( - &format!("consider removing `{}` or using a marker such as `{}`", - param_name, - self.tcx().item_path_str(def_id))); + err.help(&format!("consider removing `{}` or using a marker such as `{}`", + param_name, + self.tcx().item_path_str(def_id))); } None => { // no lang items, no help! @@ -533,8 +521,11 @@ impl<'ccx, 'gcx> CheckTypeWellFormedVisitor<'ccx, 'gcx> { } fn reject_shadowing_type_parameters(tcx: TyCtxt, span: Span, generics: &ty::Generics) { - let impl_params = generics.types.get_slice(subst::TypeSpace).iter() - .map(|tp| tp.name).collect::>(); + let impl_params = generics.types + .get_slice(subst::TypeSpace) + .iter() + .map(|tp| tp.name) + .collect::>(); for method_param in generics.types.get_slice(subst::FnSpace) { if impl_params.contains(&method_param.name) { @@ -563,8 +554,8 @@ impl<'ccx, 'tcx, 'v> Visitor<'v> for CheckTypeWellFormedVisitor<'ccx, 'tcx> { } } -/////////////////////////////////////////////////////////////////////////// -// ADT +/// //////////////////////////////////////////////////////////////////////// +/// ADT struct AdtVariant<'tcx> { fields: Vec>, @@ -577,24 +568,29 @@ struct AdtField<'tcx> { impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { fn struct_variant(&self, struct_def: &hir::VariantData) -> AdtVariant<'tcx> { - let fields = - struct_def.fields().iter() - .map(|field| { - let field_ty = self.tcx.node_id_to_type(field.id); - let field_ty = self.instantiate_type_scheme(field.span, - &self.parameter_environment - .free_substs, - &field_ty); - AdtField { ty: field_ty, span: field.span } - }) - .collect(); + let fields = struct_def.fields() + .iter() + .map(|field| { + let field_ty = self.tcx.node_id_to_type(field.id); + let field_ty = + self.instantiate_type_scheme(field.span, + &self.parameter_environment + .free_substs, + &field_ty); + AdtField { + ty: field_ty, + span: field.span, + } + }) + .collect(); AdtVariant { fields: fields } } fn enum_variants(&self, enum_def: &hir::EnumDef) -> Vec> { - enum_def.variants.iter() - .map(|variant| self.struct_variant(&variant.node.data)) - .collect() + enum_def.variants + .iter() + .map(|variant| self.struct_variant(&variant.node.data)) + .collect() } fn impl_implied_bounds(&self, impl_def_id: DefId, span: Span) -> Vec> { @@ -618,25 +614,36 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } fn error_192(ccx: &CrateCtxt, span: Span) { - span_err!(ccx.tcx.sess, span, E0192, + span_err!(ccx.tcx.sess, + span, + E0192, "negative impls are only allowed for traits with \ default impls (e.g., `Send` and `Sync`)") } fn error_380(ccx: &CrateCtxt, span: Span) { - span_err!(ccx.tcx.sess, span, E0380, + span_err!(ccx.tcx.sess, + span, + E0380, "traits with default impls (`e.g. unsafe impl \ Trait for ..`) must have no methods or associated items") } -fn error_392<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, span: Span, param_name: ast::Name) +fn error_392<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, + span: Span, + param_name: ast::Name) -> DiagnosticBuilder<'tcx> { - struct_span_err!(ccx.tcx.sess, span, E0392, - "parameter `{}` is never used", param_name) + struct_span_err!(ccx.tcx.sess, + span, + E0392, + "parameter `{}` is never used", + param_name) } fn error_194(tcx: TyCtxt, span: Span, name: ast::Name) { - span_err!(tcx.sess, span, E0194, + span_err!(tcx.sess, + span, + E0194, "type parameter `{}` shadows another type parameter of the same name", name); }