Skip to content

partially move type outlives handling into trait solving #97641

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
171 changes: 171 additions & 0 deletions compiler/rustc_infer/src/infer/outlives/obligations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,15 @@
use crate::infer::outlives::components::{push_outlives_components, Component};
use crate::infer::outlives::env::RegionBoundPairs;
use crate::infer::outlives::verify::VerifyBoundCx;
use crate::infer::traits::{Obligation, PredicateObligation};
use crate::infer::LateBoundRegionConversionTime;
use crate::infer::{
self, GenericKind, InferCtxt, RegionObligation, SubregionOrigin, UndoLog, VerifyBound,
};
use crate::traits::{ObligationCause, ObligationCauseCode};
use rustc_middle::ty::subst::GenericArgKind;
use rustc_middle::ty::subst::InternalSubsts;
use rustc_middle::ty::ToPredicate;
use rustc_middle::ty::{self, Region, Ty, TyCtxt, TypeFoldable};

use rustc_data_structures::fx::FxHashMap;
Expand Down Expand Up @@ -186,6 +190,173 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
}
}
}

fn compute_nested_outlives_obligations(
&self,
cause: &ObligationCause<'tcx>,
param_env: ty::ParamEnv<'tcx>,
ty: Ty<'tcx>,
region: ty::Region<'tcx>,
obligations: &mut Vec<PredicateObligation<'tcx>>,
) {
let nested = |ty, obligations: &mut _| {
self.compute_nested_outlives_obligations(cause, param_env, ty, region, obligations)
};
let to_obligation = |pred: ty::Binder<'tcx, ty::PredicateKind<'tcx>>| {
Obligation::new(cause.clone(), param_env, pred.to_predicate(self.tcx))
};
let ty_outlives = |ty| {
to_obligation(ty::Binder::dummy(ty::PredicateKind::TypeOutlives(
ty::OutlivesPredicate(ty, region),
)))
};
let reg_outlives = |reg| {
to_obligation(ty::Binder::dummy(ty::PredicateKind::RegionOutlives(
ty::OutlivesPredicate(reg, region),
)))
};

match ty.kind() {
// Trivial types
ty::Bool
| ty::Char
| ty::Int(..)
| ty::Uint(..)
| ty::Float(..)
| ty::Never
| ty::Str
| ty::Foreign(..) => (),

// For `&'a T` to be well formed, we require `T: 'a`.
//
// `&'a T: 'b` holds if both `'a: 'b` and `T: 'b` holds.
// `T: 'b` is implied by `'a: 'b`, so we don't have to recurse
// the type.
&ty::Ref(re, _, _) => obligations.push(reg_outlives(re)),

&ty::RawPtr(ty::TypeAndMut { ty, mutbl: _ }) | &ty::Slice(ty) | &ty::Array(ty, _) => {
nested(ty, obligations)
}

&ty::Adt(_, substs) | &ty::Opaque(_, substs) => {
for arg in substs {
match arg.unpack() {
GenericArgKind::Lifetime(re) => obligations.push(reg_outlives(re)),
GenericArgKind::Type(ty) => nested(ty, obligations),
GenericArgKind::Const(_) => (),
}
}
}

ty::Infer(..) => obligations.push(ty_outlives(ty)),

&ty::FnDef(_, substs) => {
for arg in substs {
match arg.unpack() {
GenericArgKind::Type(ty) => nested(ty, obligations),
// HACK(eddyb) ignore lifetimes found shallowly in `substs`.
// This is inconsistent with `ty::Adt` (including all substs)
// and with `ty::Closure` (ignoring all substs other than
// upvars, of which a `ty::FnDef` doesn't have any), but
// consistent with previous (accidental) behavior.
// See https://github.com/rust-lang/rust/issues/70917
// for further background and discussion.
GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => {}
}
}
}

// FIXME: Add comment on why we can ignore the signature.
ty::Closure(_, substs) => {
let tupled_ty = substs.as_closure().tupled_upvars_ty();
nested(tupled_ty, obligations)
}

// FIXME: Add comment on why we can ignore the signature.
ty::Generator(_, substs, _) => {
let tupled_ty = substs.as_generator().tupled_upvars_ty();
nested(tupled_ty, obligations)
}

// All regions are bound inside a witness
ty::GeneratorWitness(..) => {}

// FIXME: These two should ideally happen eagerly here, but
// require some kind of `Any` bound which we don't have yet.
ty::Param(_) | ty::Projection(_) => {
self.register_region_obligation_with_cause(ty, region, cause)
}

&ty::Tuple(fields) => {
for field in fields {
nested(field, obligations)
}
}

&ty::FnPtr(data) => {
let (data, _) = self.replace_bound_vars_with_fresh_vars(
cause.span,
LateBoundRegionConversionTime::HigherRankedType,
data,
);
for ty in data.inputs_and_output {
nested(ty, obligations)
}
}

&ty::Dynamic(traits, region) => {
obligations.push(reg_outlives(region));
let traits_iter = traits.iter().flat_map(|predicate| {
let (predicate, _) = self.replace_bound_vars_with_fresh_vars(
cause.span,
LateBoundRegionConversionTime::HigherRankedType,
predicate,
);
let (substs, opt_ty) = match predicate {
ty::ExistentialPredicate::Trait(tr) => (tr.substs, None),
ty::ExistentialPredicate::Projection(p) => (p.substs, Some(p.term)),
ty::ExistentialPredicate::AutoTrait(_) => (InternalSubsts::empty(), None),
};

substs.iter().rev().chain(opt_ty.and_then(|term| match term {
ty::Term::Ty(ty) => Some(ty.into()),
ty::Term::Const(_) => None,
}))
});
for arg in traits_iter {
match arg.unpack() {
GenericArgKind::Lifetime(re) => obligations.push(reg_outlives(re)),
GenericArgKind::Type(ty) => nested(ty, obligations),
GenericArgKind::Const(_) => (),
}
}
}

// FIXME: The way we deal with placeholders is wrong for now.
//
// Have to check for bounds in the `param_env`.
ty::Placeholder(..) => {}

ty::Bound(..) => bug!("unexpected type: {:?}", ty),

ty::Error(_) => {}
}
}

pub fn nested_outlives_obligations(
&self,
cause: &ObligationCause<'tcx>,
param_env: ty::ParamEnv<'tcx>,
ty: Ty<'tcx>,
region: ty::Region<'tcx>,
) -> Vec<PredicateObligation<'tcx>> {
// Directly using this for inference variables would cause
// the trait solver to be stuck.
assert!(!ty.is_ty_infer());
let mut obligations = Vec::new();
self.compute_nested_outlives_obligations(cause, param_env, ty, region, &mut obligations);
obligations
}
}

/// The `TypeOutlives` struct has the job of "lowering" a `T: 'a`
Expand Down
14 changes: 14 additions & 0 deletions compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2162,10 +2162,24 @@ impl<'a, 'tcx> InferCtxtPrivExt<'a, 'tcx> for InferCtxt<'a, 'tcx> {
}
}

ty::PredicateKind::TypeOutlives(outlives) => {
if self.tcx.sess.has_errors().is_some() || self.is_tainted_by_errors() {
return;
}
self.emit_inference_failure_err(
body_id,
span,
outlives.0.into(),
vec![],
ErrorCode::E0284,
)
}

_ => {
if self.tcx.sess.has_errors().is_some() || self.is_tainted_by_errors() {
return;
}

let mut err = struct_span_err!(
self.tcx.sess,
span,
Expand Down
25 changes: 19 additions & 6 deletions compiler/rustc_trait_selection/src/traits/fulfill.rs
Original file line number Diff line number Diff line change
Expand Up @@ -434,13 +434,26 @@ impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> {

ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(t_a, r_b)) => {
if self.register_region_obligations {
self.selcx.infcx().register_region_obligation_with_cause(
t_a,
r_b,
&obligation.cause,
);
if t_a.is_ty_infer() {
pending_obligation.stalled_on =
vec![TyOrConstInferVar::maybe_from_ty(t_a).unwrap()];
ProcessResult::Unchanged
} else {
if self.register_region_obligations {
let obligations = infcx.nested_outlives_obligations(
&obligation.cause,
obligation.param_env,
t_a,
r_b,
);
ProcessResult::Changed(mk_pending(obligations))
} else {
ProcessResult::Changed(vec![])
}
}
} else {
ProcessResult::Changed(vec![])
}
ProcessResult::Changed(vec![])
}

ty::PredicateKind::Projection(ref data) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use rustc_data_structures::stack::ensure_sufficient_stack;
use rustc_hir::lang_items::LangItem;
use rustc_index::bit_set::GrowableBitSet;
use rustc_infer::infer::InferOk;
use rustc_infer::infer::LateBoundRegionConversionTime::HigherRankedType;
use rustc_infer::infer::LateBoundRegionConversionTime;
use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, Subst, SubstsRef};
use rustc_middle::ty::{self, EarlyBinder, GenericParamDefKind, Ty, TyCtxt};
use rustc_middle::ty::{ToPolyTraitRef, ToPredicate};
Expand Down Expand Up @@ -425,7 +425,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
.infcx
.replace_bound_vars_with_fresh_vars(
obligation.cause.span,
HigherRankedType,
LateBoundRegionConversionTime::HigherRankedType,
object_trait_ref,
)
.0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ LL | fn zero_copy_from<'b>(cart: &'b [T]) -> &'b [T] {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= help: consider adding an explicit lifetime bound `T: 'static`...
= note: ...so that the type `[T]` will meet its required lifetime bounds
= note: ...so that the type `T` will meet its required lifetime bounds

error: aborting due to previous error

Expand Down
11 changes: 8 additions & 3 deletions src/test/ui/generic-associated-types/bugs/issue-86218.stderr
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
error[E0477]: the type `<() as Yay<&'a ()>>::InnerStream<'s>` does not fulfill the required lifetime
error[E0478]: lifetime bound not satisfied
--> $DIR/issue-86218.rs:23:28
|
LL | type InnerStream<'s> = impl Stream<Item = i32> + 's;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
note: type must outlive the lifetime `'s` as defined here as required by this binding
note: lifetime parameter instantiated with the lifetime `'a` as defined here
--> $DIR/issue-86218.rs:22:6
|
LL | impl<'a> Yay<&'a ()> for () {
| ^^
note: but lifetime parameter must outlive the lifetime `'s` as defined here
--> $DIR/issue-86218.rs:23:22
|
LL | type InnerStream<'s> = impl Stream<Item = i32> + 's;
Expand All @@ -20,4 +25,4 @@ LL | type InnerStream<'s> = impl Stream<Item = i32> + 's;

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0477`.
For more information about this error, try `rustc --explain E0478`.
2 changes: 1 addition & 1 deletion src/test/ui/generic-associated-types/issue-90014.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ trait MakeFut {

impl MakeFut for &'_ mut () {
type Fut<'a> = impl Future<Output = ()>;
//~^ ERROR: the type `&mut ()` does not fulfill the required lifetime
//~^ ERROR: lifetime bound not satisfied

fn make_fut<'a>(&'a self) -> Self::Fut<'a> {
async { () }
Expand Down
11 changes: 8 additions & 3 deletions src/test/ui/generic-associated-types/issue-90014.stderr
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
error[E0477]: the type `&mut ()` does not fulfill the required lifetime
error[E0478]: lifetime bound not satisfied
--> $DIR/issue-90014.rs:14:20
|
LL | type Fut<'a> where Self: 'a;
Expand All @@ -7,12 +7,17 @@ LL | type Fut<'a> where Self: 'a;
LL | type Fut<'a> = impl Future<Output = ()>;
| ^^^^^^^^^^^^^^^^^^^^^^^^- help: try copying this clause from the trait: `where Self: 'a`
|
note: type must outlive the lifetime `'a` as defined here
note: lifetime parameter instantiated with the anonymous lifetime as defined here
--> $DIR/issue-90014.rs:13:19
|
LL | impl MakeFut for &'_ mut () {
| ^^
note: but lifetime parameter must outlive the lifetime `'a` as defined here
--> $DIR/issue-90014.rs:14:14
|
LL | type Fut<'a> = impl Future<Output = ()>;
| ^^

error: aborting due to previous error

For more information about this error, try `rustc --explain E0477`.
For more information about this error, try `rustc --explain E0478`.
2 changes: 1 addition & 1 deletion src/test/ui/generic-associated-types/issue-92033.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ trait Swapchain {

impl<'s> Surface for &'s Texture {
type TextureIter<'a> = std::option::IntoIter<&'a Texture>;
//~^ ERROR the type
//~^ ERROR lifetime bound not satisfied

fn get_texture(&self) -> Self::TextureIter<'_> {
let option: Option<&Texture> = Some(self);
Expand Down
11 changes: 8 additions & 3 deletions src/test/ui/generic-associated-types/issue-92033.stderr
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
error[E0477]: the type `&'s Texture` does not fulfill the required lifetime
error[E0478]: lifetime bound not satisfied
--> $DIR/issue-92033.rs:22:28
|
LL | / type TextureIter<'a>: Iterator<Item = &'a Texture>
Expand All @@ -9,12 +9,17 @@ LL | | Self: 'a;
LL | type TextureIter<'a> = std::option::IntoIter<&'a Texture>;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- help: try copying this clause from the trait: `where Self: 'a`
|
note: type must outlive the lifetime `'a` as defined here
note: lifetime parameter instantiated with the lifetime `'s` as defined here
--> $DIR/issue-92033.rs:21:6
|
LL | impl<'s> Surface for &'s Texture {
| ^^
note: but lifetime parameter must outlive the lifetime `'a` as defined here
--> $DIR/issue-92033.rs:22:22
|
LL | type TextureIter<'a> = std::option::IntoIter<&'a Texture>;
| ^^

error: aborting due to previous error

For more information about this error, try `rustc --explain E0477`.
For more information about this error, try `rustc --explain E0478`.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ trait ATy {

impl<'b> ATy for &'b () {
type Item<'a> = &'b ();
//~^ ERROR the type `&'b ()` does not fulfill the required lifetime
//~^ ERROR lifetime bound not satisfied
}

trait StaticTy {
Expand All @@ -15,7 +15,7 @@ trait StaticTy {

impl StaticTy for () {
type Item<'a> = &'a ();
//~^ ERROR the type `&'a ()` does not fulfill the required lifetime
//~^ ERROR lifetime bound not satisfied
}

fn main() {}
Loading