diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index 11c893a7cb6d9..fc64b9c15de85 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -465,12 +465,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { }; // sort the errors by span, for better error message stability. - errors.sort_by_key(|u| match *u { - RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(), - RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(), - RegionResolutionError::SubSupConflict(_, ref rvo, _, _, _, _, _) => rvo.span(), - RegionResolutionError::UpperBoundUniverseConflict(_, ref rvo, _, _, _) => rvo.span(), - }); + errors.sort_by_key(|u| u.span()); errors } diff --git a/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs b/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs index 0f341a947ad35..5ce9a2ff2a4af 100644 --- a/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs +++ b/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs @@ -81,7 +81,7 @@ pub enum RegionResolutionError<'tcx> { /// `o` requires that `a <= b`, but this does not hold ConcreteFailure(SubregionOrigin<'tcx>, Region<'tcx>, Region<'tcx>), - /// `GenericBoundFailure(p, s, a) + /// `GenericBoundFailure(p, s, a)`: /// /// The parameter/associated-type `p` must be known to outlive the lifetime /// `a` (but none of the known bounds are sufficient). @@ -113,6 +113,30 @@ pub enum RegionResolutionError<'tcx> { ), } +impl<'tcx> RegionResolutionError<'tcx> { + pub fn span(&self) -> Span { + match self { + RegionResolutionError::ConcreteFailure(sro, _, _) => sro.span(), + RegionResolutionError::GenericBoundFailure(sro, _, _) => sro.span(), + RegionResolutionError::SubSupConflict(_, rvo, _, _, _, _, _) => rvo.span(), + RegionResolutionError::UpperBoundUniverseConflict(_, rvo, _, _, _) => rvo.span(), + } + } +} + +impl<'tcx> RegionResolutionError<'tcx> { + pub fn as_bound(&self) -> String { + match self { + RegionResolutionError::ConcreteFailure(_, a, b) => format!("{}: {}", b, a), + RegionResolutionError::GenericBoundFailure(_, a, b) => format!("{}: {}", b, a), + RegionResolutionError::SubSupConflict(_, _, _, sub_r, _, sup_r, _) => { + format!("{}: {}", sup_r, sub_r) + } + RegionResolutionError::UpperBoundUniverseConflict(_, _, _, _, _) => unimplemented!(), + } + } +} + struct RegionAndOrigin<'tcx> { region: Region<'tcx>, origin: SubregionOrigin<'tcx>, diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index 809e7ce2e745b..a9d6f019b0daa 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -650,6 +650,10 @@ impl<'tcx> TyCtxt<'tcx> { ty::EarlyBinder(self.type_of(def_id)) } + pub fn bound_param_env(self, def_id: DefId) -> ty::EarlyBinder> { + ty::EarlyBinder(self.param_env(def_id)) + } + pub fn bound_fn_sig(self, def_id: DefId) -> ty::EarlyBinder> { ty::EarlyBinder(self.fn_sig(def_id)) } diff --git a/compiler/rustc_typeck/src/check/dropck.rs b/compiler/rustc_typeck/src/check/dropck.rs index 307064327c5a3..1af4198584795 100644 --- a/compiler/rustc_typeck/src/check/dropck.rs +++ b/compiler/rustc_typeck/src/check/dropck.rs @@ -1,18 +1,24 @@ +use std::iter; + use crate::check::regionck::RegionCtxt; +use crate::check::Inherited; use crate::hir; -use crate::hir::def_id::{DefId, LocalDefId}; use rustc_errors::{struct_span_err, ErrorGuaranteed}; -use rustc_middle::ty::error::TypeError; -use rustc_middle::ty::relate::{Relate, RelateResult, TypeRelation}; -use rustc_middle::ty::subst::SubstsRef; +use rustc_hir::def_id::{DefId, LocalDefId}; +use rustc_hir::CRATE_HIR_ID; +use rustc_infer::infer::outlives::env::OutlivesEnvironment; +use rustc_infer::infer::RegionckMode; +use rustc_infer::infer::TyCtxtInferExt; +use rustc_infer::traits::Obligation; +use rustc_middle::ty::subst::{Subst, SubstsRef}; use rustc_middle::ty::util::IgnoreRegions; -use rustc_middle::ty::{self, Predicate, Ty, TyCtxt}; +use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_span::Span; use rustc_trait_selection::traits::query::dropck_outlives::AtExt; use rustc_trait_selection::traits::ObligationCause; /// This function confirms that the `Drop` implementation identified by -/// `drop_impl_did` is not any more specialized than the type it is +/// `drop_impl_def_id` is not any more specialized than the type it is /// attached to (Issue #8142). /// /// This means: @@ -28,30 +34,30 @@ use rustc_trait_selection::traits::ObligationCause; /// struct/enum definition for the nominal type itself (i.e. /// cannot do `struct S; impl Drop for S { ... }`). /// -pub fn check_drop_impl(tcx: TyCtxt<'_>, drop_impl_did: DefId) -> Result<(), ErrorGuaranteed> { - let dtor_self_type = tcx.type_of(drop_impl_did); - let dtor_predicates = tcx.predicates_of(drop_impl_did); +pub fn check_drop_impl(tcx: TyCtxt<'_>, drop_impl_def_id: DefId) -> Result<(), ErrorGuaranteed> { + let drop_impl_def_id = drop_impl_def_id.expect_local(); + let dtor_self_type = tcx.type_of(drop_impl_def_id); match dtor_self_type.kind() { ty::Adt(adt_def, self_to_impl_substs) => { ensure_drop_params_and_item_params_correspond( tcx, - drop_impl_did.expect_local(), + drop_impl_def_id, adt_def.did(), self_to_impl_substs, )?; - ensure_drop_predicates_are_implied_by_item_defn( + drop_bounds_implied_by_item_definition( tcx, - dtor_predicates, + drop_impl_def_id, adt_def.did().expect_local(), self_to_impl_substs, ) } _ => { - // Destructors only work on nominal types. This was + // Destructors only work on nominal types. This was // already checked by coherence, but compilation may // not have been terminated. - let span = tcx.def_span(drop_impl_did); + let span = tcx.def_span(drop_impl_def_id); let reported = tcx.sess.delay_span_bug( span, &format!("should have been rejected by coherence check: {dtor_self_type}"), @@ -63,7 +69,7 @@ pub fn check_drop_impl(tcx: TyCtxt<'_>, drop_impl_did: DefId) -> Result<(), Erro fn ensure_drop_params_and_item_params_correspond<'tcx>( tcx: TyCtxt<'tcx>, - drop_impl_did: LocalDefId, + drop_impl_def_id: LocalDefId, self_type_did: DefId, drop_impl_substs: SubstsRef<'tcx>, ) -> Result<(), ErrorGuaranteed> { @@ -71,7 +77,7 @@ fn ensure_drop_params_and_item_params_correspond<'tcx>( return Ok(()) }; - let drop_impl_span = tcx.def_span(drop_impl_did); + let drop_impl_span = tcx.def_span(drop_impl_def_id); let item_span = tcx.def_span(self_type_did); let self_descr = tcx.def_kind(self_type_did).descr(self_type_did); let mut err = @@ -94,138 +100,81 @@ fn ensure_drop_params_and_item_params_correspond<'tcx>( Err(err.emit()) } -/// Confirms that every predicate imposed by dtor_predicates is -/// implied by assuming the predicates attached to self_type_did. -fn ensure_drop_predicates_are_implied_by_item_defn<'tcx>( +/// Confirms that the bounds of the `Drop` impl are implied +/// by the bounds of the struct definition. +fn drop_bounds_implied_by_item_definition<'tcx>( tcx: TyCtxt<'tcx>, - dtor_predicates: ty::GenericPredicates<'tcx>, - self_type_did: LocalDefId, - self_to_impl_substs: SubstsRef<'tcx>, + drop_impl_def_id: LocalDefId, + self_ty_def_id: LocalDefId, + impl_substs: SubstsRef<'tcx>, ) -> Result<(), ErrorGuaranteed> { - let mut result = Ok(()); - - // Here is an example, analogous to that from - // `compare_impl_method`. - // - // Consider a struct type: - // - // struct Type<'c, 'b:'c, 'a> { - // x: &'a Contents // (contents are irrelevant; - // y: &'c Cell<&'b Contents>, // only the bounds matter for our purposes.) - // } - // - // and a Drop impl: - // - // impl<'z, 'y:'z, 'x:'y> Drop for P<'z, 'y, 'x> { - // fn drop(&mut self) { self.y.set(self.x); } // (only legal if 'x: 'y) - // } - // - // We start out with self_to_impl_substs, that maps the generic - // parameters of Type to that of the Drop impl. - // - // self_to_impl_substs = {'c => 'z, 'b => 'y, 'a => 'x} - // - // Applying this to the predicates (i.e., assumptions) provided by the item - // definition yields the instantiated assumptions: - // - // ['y : 'z] - // - // We then check all of the predicates of the Drop impl: - // - // ['y:'z, 'x:'y] - // - // and ensure each is in the list of instantiated - // assumptions. Here, `'y:'z` is present, but `'x:'y` is - // absent. So we report an error that the Drop impl injected a - // predicate that is not present on the struct definition. - - // We can assume the predicates attached to struct/enum definition - // hold. - let generic_assumptions = tcx.predicates_of(self_type_did); - - let assumptions_in_impl_context = generic_assumptions.instantiate(tcx, &self_to_impl_substs); - let assumptions_in_impl_context = assumptions_in_impl_context.predicates; - - let self_param_env = tcx.param_env(self_type_did); - - // An earlier version of this code attempted to do this checking - // via the traits::fulfill machinery. However, it ran into trouble - // since the fulfill machinery merely turns outlives-predicates - // 'a:'b and T:'b into region inference constraints. It is simpler - // just to look for all the predicates directly. - - assert_eq!(dtor_predicates.parent, None); - for &(predicate, predicate_sp) in dtor_predicates.predicates { - // (We do not need to worry about deep analysis of type - // expressions etc because the Drop impls are already forced - // to take on a structure that is roughly an alpha-renaming of - // the generic parameters of the item definition.) - - // This path now just checks *all* predicates via an instantiation of - // the `SimpleEqRelation`, which simply forwards to the `relate` machinery - // after taking care of anonymizing late bound regions. - // - // However, it may be more efficient in the future to batch - // the analysis together via the fulfill (see comment above regarding - // the usage of the fulfill machinery), rather than the - // repeated `.iter().any(..)` calls. - - // This closure is a more robust way to check `Predicate` equality - // than simple `==` checks (which were the previous implementation). - // It relies on `ty::relate` for `TraitPredicate`, `ProjectionPredicate`, - // `ConstEvaluatable` and `TypeOutlives` (which implement the Relate trait), - // while delegating on simple equality for the other `Predicate`. - // This implementation solves (Issue #59497) and (Issue #58311). - // It is unclear to me at the moment whether the approach based on `relate` - // could be extended easily also to the other `Predicate`. - let predicate_matches_closure = |p: Predicate<'tcx>| { - let mut relator: SimpleEqRelation<'tcx> = SimpleEqRelation::new(tcx, self_param_env); - let predicate = predicate.kind(); - let p = p.kind(); - match (predicate.skip_binder(), p.skip_binder()) { - (ty::PredicateKind::Trait(a), ty::PredicateKind::Trait(b)) => { - // Since struct predicates cannot have ~const, project the impl predicate - // onto one that ignores the constness. This is equivalent to saying that - // we match a `Trait` bound on the struct with a `Trait` or `~const Trait` - // in the impl. - let non_const_a = - ty::TraitPredicate { constness: ty::BoundConstness::NotConst, ..a }; - relator.relate(predicate.rebind(non_const_a), p.rebind(b)).is_ok() - } - (ty::PredicateKind::Projection(a), ty::PredicateKind::Projection(b)) => { - relator.relate(predicate.rebind(a), p.rebind(b)).is_ok() - } - ( - ty::PredicateKind::ConstEvaluatable(a), - ty::PredicateKind::ConstEvaluatable(b), - ) => tcx.try_unify_abstract_consts(self_param_env.and((a, b))), - ( - ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty_a, lt_a)), - ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty_b, lt_b)), - ) => { - relator.relate(predicate.rebind(ty_a), p.rebind(ty_b)).is_ok() - && relator.relate(predicate.rebind(lt_a), p.rebind(lt_b)).is_ok() - } - _ => predicate == p, - } - }; + let self_ty_hir_id = tcx.hir().local_def_id_to_hir_id(self_ty_def_id); + tcx.infer_ctxt().enter(|infcx| { + let inh = Inherited::new(infcx, self_ty_def_id); + let infcx = &inh.infcx; + + // The bounds of the `Drop` impl have to hold given the bounds + // of the type definition. + let param_env = tcx.bound_param_env(self_ty_def_id.to_def_id()).subst(tcx, impl_substs); + + // We now simply emit obligations for each predicate of the impl. + let dtor_predicates = tcx.predicates_of(drop_impl_def_id).instantiate_identity(tcx); + for (pred, span) in iter::zip(dtor_predicates.predicates, dtor_predicates.spans) { + let cause = ObligationCause::misc(span, self_ty_hir_id); + let obligation = Obligation::new(cause, param_env, pred); + inh.register_predicate(obligation); + } - if !assumptions_in_impl_context.iter().copied().any(predicate_matches_closure) { - let item_span = tcx.def_span(self_type_did); - let self_descr = tcx.def_kind(self_type_did).descr(self_type_did.to_def_id()); + let errors = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx); + let mut result = Ok(()); + for error in errors { + let item_span = tcx.def_span(self_ty_def_id); + let self_descr = tcx.def_kind(self_ty_def_id).descr(self_ty_def_id.to_def_id()); let reported = struct_span_err!( tcx.sess, - predicate_sp, + error.obligation.cause.span, E0367, - "`Drop` impl requires `{predicate}` but the {self_descr} it is implemented for does not", + "`Drop` impl requires `{}` but the {self_descr} it is implemented for does not", + error.obligation.predicate, ) .span_note(item_span, "the implementor must specify the same requirement") .emit(); result = Err(reported); } - } - - result + result?; + + let mut outlives_env = OutlivesEnvironment::new(param_env); + outlives_env.save_implied_bounds(CRATE_HIR_ID); + + infcx.process_registered_region_obligations( + outlives_env.region_bound_pairs_map(), + Some(tcx.lifetimes.re_root_empty), + param_env, + ); + + // This `DefId` isn't actually used. + let errors = infcx.resolve_regions( + drop_impl_def_id.to_def_id(), + &outlives_env, + RegionckMode::default(), + ); + let mut result = Ok(()); + for error in errors { + let item_span = tcx.def_span(self_ty_def_id); + let self_descr = tcx.def_kind(self_ty_def_id).descr(self_ty_def_id.to_def_id()); + let reported = struct_span_err!( + tcx.sess, + error.span(), + E0367, + "`Drop` impl requires `{}` but the {self_descr} it is implemented for does not", + error.as_bound() + ) + .span_note(item_span, "the implementor must specify the same requirement") + .emit(); + result = Err(reported); + } + result + }) } /// This function is not only checking that the dropck obligations are met for @@ -244,100 +193,3 @@ pub(crate) fn check_drop_obligations<'a, 'tcx>( debug!("dropck_outlives = {:#?}", infer_ok); rcx.fcx.register_infer_ok_obligations(infer_ok); } - -// This is an implementation of the TypeRelation trait with the -// aim of simply comparing for equality (without side-effects). -// It is not intended to be used anywhere else other than here. -pub(crate) struct SimpleEqRelation<'tcx> { - tcx: TyCtxt<'tcx>, - param_env: ty::ParamEnv<'tcx>, -} - -impl<'tcx> SimpleEqRelation<'tcx> { - fn new(tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> SimpleEqRelation<'tcx> { - SimpleEqRelation { tcx, param_env } - } -} - -impl<'tcx> TypeRelation<'tcx> for SimpleEqRelation<'tcx> { - fn tcx(&self) -> TyCtxt<'tcx> { - self.tcx - } - - fn param_env(&self) -> ty::ParamEnv<'tcx> { - self.param_env - } - - fn tag(&self) -> &'static str { - "dropck::SimpleEqRelation" - } - - fn a_is_expected(&self) -> bool { - true - } - - fn relate_with_variance>( - &mut self, - _: ty::Variance, - _info: ty::VarianceDiagInfo<'tcx>, - a: T, - b: T, - ) -> RelateResult<'tcx, T> { - // Here we ignore variance because we require drop impl's types - // to be *exactly* the same as to the ones in the struct definition. - self.relate(a, b) - } - - fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> { - debug!("SimpleEqRelation::tys(a={:?}, b={:?})", a, b); - ty::relate::super_relate_tys(self, a, b) - } - - fn regions( - &mut self, - a: ty::Region<'tcx>, - b: ty::Region<'tcx>, - ) -> RelateResult<'tcx, ty::Region<'tcx>> { - debug!("SimpleEqRelation::regions(a={:?}, b={:?})", a, b); - - // We can just equate the regions because LBRs have been - // already anonymized. - if a == b { - Ok(a) - } else { - // I'm not sure is this `TypeError` is the right one, but - // it should not matter as it won't be checked (the dropck - // will emit its own, more informative and higher-level errors - // in case anything goes wrong). - Err(TypeError::RegionsPlaceholderMismatch) - } - } - - fn consts( - &mut self, - a: ty::Const<'tcx>, - b: ty::Const<'tcx>, - ) -> RelateResult<'tcx, ty::Const<'tcx>> { - debug!("SimpleEqRelation::consts(a={:?}, b={:?})", a, b); - ty::relate::super_relate_consts(self, a, b) - } - - fn binders( - &mut self, - a: ty::Binder<'tcx, T>, - b: ty::Binder<'tcx, T>, - ) -> RelateResult<'tcx, ty::Binder<'tcx, T>> - where - T: Relate<'tcx>, - { - debug!("SimpleEqRelation::binders({:?}: {:?}", a, b); - - // Anonymizing the LBRs is necessary to solve (Issue #59497). - // After we do so, it should be totally fine to skip the binders. - let anon_a = self.tcx.anonymize_late_bound_regions(a); - let anon_b = self.tcx.anonymize_late_bound_regions(b); - self.relate(anon_a.skip_binder(), anon_b.skip_binder())?; - - Ok(a) - } -} diff --git a/src/test/ui/dropck/assoc-ty-param.rs b/src/test/ui/dropck/assoc-ty-param.rs new file mode 100644 index 0000000000000..1ff65b928c084 --- /dev/null +++ b/src/test/ui/dropck/assoc-ty-param.rs @@ -0,0 +1,21 @@ +struct Foo +where + T: Iterator, + T::Item: Send, +{ + t: T, +} + +impl Drop for Foo +//~^ ERROR `Drop` impl requires `I: Sized` +where + T: Iterator, + //~^ ERROR `Drop` impl requires `::Item == I` + I: Send, + //~^ ERROR `Drop` impl requires `I: Send` + +{ + fn drop(&mut self) { } +} + +fn main() { } \ No newline at end of file diff --git a/src/test/ui/dropck/assoc-ty-param.stderr b/src/test/ui/dropck/assoc-ty-param.stderr new file mode 100644 index 0000000000000..81d14a86c3d5b --- /dev/null +++ b/src/test/ui/dropck/assoc-ty-param.stderr @@ -0,0 +1,57 @@ +error[E0367]: `Drop` impl requires `::Item == I` but the struct it is implemented for does not + --> $DIR/assoc-ty-param.rs:12:17 + | +LL | T: Iterator, + | ^^^^^^^^ + | +note: the implementor must specify the same requirement + --> $DIR/assoc-ty-param.rs:1:1 + | +LL | / struct Foo +LL | | where +LL | | T: Iterator, +LL | | T::Item: Send, +LL | | { +LL | | t: T, +LL | | } + | |_^ + +error[E0367]: `Drop` impl requires `I: Sized` but the struct it is implemented for does not + --> $DIR/assoc-ty-param.rs:9:9 + | +LL | impl Drop for Foo + | ^ + | +note: the implementor must specify the same requirement + --> $DIR/assoc-ty-param.rs:1:1 + | +LL | / struct Foo +LL | | where +LL | | T: Iterator, +LL | | T::Item: Send, +LL | | { +LL | | t: T, +LL | | } + | |_^ + +error[E0367]: `Drop` impl requires `I: Send` but the struct it is implemented for does not + --> $DIR/assoc-ty-param.rs:14:8 + | +LL | I: Send, + | ^^^^ + | +note: the implementor must specify the same requirement + --> $DIR/assoc-ty-param.rs:1:1 + | +LL | / struct Foo +LL | | where +LL | | T: Iterator, +LL | | T::Item: Send, +LL | | { +LL | | t: T, +LL | | } + | |_^ + +error: aborting due to 3 previous errors + +For more information about this error, try `rustc --explain E0367`. diff --git a/src/test/ui/dropck/reject-specialized-drops-8142.stderr b/src/test/ui/dropck/reject-specialized-drops-8142.stderr index 7f50cf5ab15d2..f46273d567fd4 100644 --- a/src/test/ui/dropck/reject-specialized-drops-8142.stderr +++ b/src/test/ui/dropck/reject-specialized-drops-8142.stderr @@ -60,18 +60,6 @@ note: the implementor must specify the same requirement LL | struct Q { x: *const Tq } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error[E0367]: `Drop` impl requires `AddsRBnd: 'rbnd` but the struct it is implemented for does not - --> $DIR/reject-specialized-drops-8142.rs:45:21 - | -LL | impl<'rbnd,AddsRBnd:'rbnd> Drop for R { fn drop(&mut self) { } } // REJECT - | ^^^^^ - | -note: the implementor must specify the same requirement - --> $DIR/reject-specialized-drops-8142.rs:11:1 - | -LL | struct R { x: *const Tr } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - error[E0366]: `Drop` impls cannot be specialized --> $DIR/reject-specialized-drops-8142.rs:54:1 | @@ -160,7 +148,7 @@ note: the implementor must specify the same requirement LL | union Union { f: T } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: aborting due to 13 previous errors +error: aborting due to 12 previous errors Some errors have detailed explanations: E0366, E0367. For more information about an error, try `rustc --explain E0366`.