Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit a34faab

Browse files
committedJan 18, 2024
Auto merge of rust-lang#118553 - jackh726:lint-implied-bounds, r=lcnr
error on incorrect implied bounds in wfcheck except for Bevy dependents Rebase of rust-lang#109763 Additionally, special cases Bevy `ParamSet` types to not trigger the lint. This is tracked in rust-lang#119956. Fixes rust-lang#109628
2 parents c485ee7 + a9e30e6 commit a34faab

File tree

26 files changed

+411
-175
lines changed

26 files changed

+411
-175
lines changed
 

‎compiler/rustc_hir_analysis/src/check/check.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -368,7 +368,7 @@ fn check_opaque_meets_bounds<'tcx>(
368368
// Can have different predicates to their defining use
369369
hir::OpaqueTyOrigin::TyAlias { .. } => {
370370
let wf_tys = ocx.assumed_wf_types_and_report_errors(param_env, def_id)?;
371-
let implied_bounds = infcx.implied_bounds_tys(param_env, def_id, wf_tys);
371+
let implied_bounds = infcx.implied_bounds_tys(param_env, def_id, &wf_tys);
372372
let outlives_env = OutlivesEnvironment::with_bounds(param_env, implied_bounds);
373373
ocx.resolve_regions_and_report_errors(defining_use_anchor, &outlives_env)?;
374374
}

‎compiler/rustc_hir_analysis/src/check/compare_impl_item.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -378,7 +378,7 @@ fn compare_method_predicate_entailment<'tcx>(
378378
// lifetime parameters.
379379
let outlives_env = OutlivesEnvironment::with_bounds(
380380
param_env,
381-
infcx.implied_bounds_tys(param_env, impl_m_def_id, wf_tys),
381+
infcx.implied_bounds_tys(param_env, impl_m_def_id, &wf_tys),
382382
);
383383
let errors = infcx.resolve_regions(&outlives_env);
384384
if !errors.is_empty() {
@@ -702,7 +702,7 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>(
702702
// lifetime parameters.
703703
let outlives_env = OutlivesEnvironment::with_bounds(
704704
param_env,
705-
infcx.implied_bounds_tys(param_env, impl_m_def_id, wf_tys),
705+
infcx.implied_bounds_tys(param_env, impl_m_def_id, &wf_tys),
706706
);
707707
ocx.resolve_regions_and_report_errors(impl_m_def_id, &outlives_env)?;
708708

@@ -2070,7 +2070,7 @@ pub(super) fn check_type_bounds<'tcx>(
20702070

20712071
// Finally, resolve all regions. This catches wily misuses of
20722072
// lifetime parameters.
2073-
let implied_bounds = infcx.implied_bounds_tys(param_env, impl_ty_def_id, assumed_wf_types);
2073+
let implied_bounds = infcx.implied_bounds_tys(param_env, impl_ty_def_id, &assumed_wf_types);
20742074
let outlives_env = OutlivesEnvironment::with_bounds(param_env, implied_bounds);
20752075
ocx.resolve_regions_and_report_errors(impl_ty_def_id, &outlives_env)
20762076
}

‎compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ pub(super) fn check_refining_return_position_impl_trait_in_trait<'tcx>(
158158
}
159159
let outlives_env = OutlivesEnvironment::with_bounds(
160160
param_env,
161-
infcx.implied_bounds_tys(param_env, impl_m.def_id.expect_local(), implied_wf_types),
161+
infcx.implied_bounds_tys(param_env, impl_m.def_id.expect_local(), &implied_wf_types),
162162
);
163163
let errors = infcx.resolve_regions(&outlives_env);
164164
if !errors.is_empty() {

‎compiler/rustc_hir_analysis/src/check/wfcheck.rs

Lines changed: 59 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ use rustc_infer::infer::outlives::obligations::TypeOutlives;
1515
use rustc_infer::infer::{self, InferCtxt, TyCtxtInferExt};
1616
use rustc_middle::mir::ConstraintCategory;
1717
use rustc_middle::query::Providers;
18+
use rustc_middle::ty::print::with_no_trimmed_paths;
1819
use rustc_middle::ty::trait_def::TraitSpecializationKind;
1920
use rustc_middle::ty::{
2021
self, AdtKind, GenericParamDefKind, ToPredicate, Ty, TyCtxt, TypeFoldable, TypeSuperVisitable,
@@ -112,8 +113,6 @@ where
112113

113114
let assumed_wf_types = wfcx.ocx.assumed_wf_types_and_report_errors(param_env, body_def_id)?;
114115

115-
let implied_bounds = infcx.implied_bounds_tys(param_env, body_def_id, assumed_wf_types);
116-
117116
let errors = wfcx.select_all_or_error();
118117
if !errors.is_empty() {
119118
let err = infcx.err_ctxt().report_fulfillment_errors(errors);
@@ -128,10 +127,65 @@ where
128127
}
129128
}
130129

130+
debug!(?assumed_wf_types);
131+
132+
let infcx_compat = infcx.fork();
133+
134+
// We specifically want to call the non-compat version of `implied_bounds_tys`; we do this always.
135+
let implied_bounds =
136+
infcx.implied_bounds_tys_compat(param_env, body_def_id, &assumed_wf_types, false);
131137
let outlives_env = OutlivesEnvironment::with_bounds(param_env, implied_bounds);
132138

133-
wfcx.ocx.resolve_regions_and_report_errors(body_def_id, &outlives_env)?;
134-
infcx.tainted_by_errors().error_reported()
139+
let errors = infcx.resolve_regions(&outlives_env);
140+
if errors.is_empty() {
141+
return Ok(());
142+
}
143+
144+
let is_bevy = 'is_bevy: {
145+
// We don't want to emit this for dependents of Bevy, for now.
146+
// See #119956
147+
let is_bevy_paramset = |def: ty::AdtDef<'_>| {
148+
let adt_did = with_no_trimmed_paths!(infcx.tcx.def_path_str(def.0.did));
149+
adt_did.contains("ParamSet")
150+
};
151+
for ty in assumed_wf_types.iter() {
152+
match ty.kind() {
153+
ty::Adt(def, _) => {
154+
if is_bevy_paramset(*def) {
155+
break 'is_bevy true;
156+
}
157+
}
158+
ty::Ref(_, ty, _) => match ty.kind() {
159+
ty::Adt(def, _) => {
160+
if is_bevy_paramset(*def) {
161+
break 'is_bevy true;
162+
}
163+
}
164+
_ => {}
165+
},
166+
_ => {}
167+
}
168+
}
169+
false
170+
};
171+
172+
// If we have set `no_implied_bounds_compat`, then do not attempt compatibility.
173+
// We could also just always enter if `is_bevy`, and call `implied_bounds_tys`,
174+
// but that does result in slightly more work when this option is set and
175+
// just obscures what we mean here anyways. Let's just be explicit.
176+
if is_bevy && !infcx.tcx.sess.opts.unstable_opts.no_implied_bounds_compat {
177+
let implied_bounds =
178+
infcx_compat.implied_bounds_tys_compat(param_env, body_def_id, &assumed_wf_types, true);
179+
let outlives_env = OutlivesEnvironment::with_bounds(param_env, implied_bounds);
180+
let errors_compat = infcx_compat.resolve_regions(&outlives_env);
181+
if errors_compat.is_empty() {
182+
Ok(())
183+
} else {
184+
Err(infcx_compat.err_ctxt().report_region_errors(body_def_id, &errors_compat))
185+
}
186+
} else {
187+
Err(infcx.err_ctxt().report_region_errors(body_def_id, &errors))
188+
}
135189
}
136190

137191
fn check_well_formed(tcx: TyCtxt<'_>, def_id: hir::OwnerId) -> Result<(), ErrorGuaranteed> {
@@ -723,7 +777,7 @@ fn resolve_regions_with_wf_tys<'tcx>(
723777
let infcx = tcx.infer_ctxt().build();
724778
let outlives_environment = OutlivesEnvironment::with_bounds(
725779
param_env,
726-
infcx.implied_bounds_tys(param_env, id, wf_tys.clone()),
780+
infcx.implied_bounds_tys(param_env, id, wf_tys),
727781
);
728782
let region_bound_pairs = outlives_environment.region_bound_pairs();
729783

‎compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ fn get_impl_args(
202202
return Err(guar);
203203
}
204204

205-
let implied_bounds = infcx.implied_bounds_tys(param_env, impl1_def_id, assumed_wf_types);
205+
let implied_bounds = infcx.implied_bounds_tys(param_env, impl1_def_id, &assumed_wf_types);
206206
let outlives_env = OutlivesEnvironment::with_bounds(param_env, implied_bounds);
207207
let _ = ocx.resolve_regions_and_report_errors(impl1_def_id, &outlives_env);
208208
let Ok(impl2_args) = infcx.fully_resolve(impl2_args) else {

‎compiler/rustc_middle/src/query/erase.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,10 @@ impl<T> EraseType for Result<&'_ T, traits::query::NoSolution> {
7474
type Result = [u8; size_of::<Result<&'static (), traits::query::NoSolution>>()];
7575
}
7676

77+
impl<T> EraseType for Result<&'_ [T], traits::query::NoSolution> {
78+
type Result = [u8; size_of::<Result<&'static [()], traits::query::NoSolution>>()];
79+
}
80+
7781
impl<T> EraseType for Result<&'_ T, rustc_errors::ErrorGuaranteed> {
7882
type Result = [u8; size_of::<Result<&'static (), rustc_errors::ErrorGuaranteed>>()];
7983
}

‎compiler/rustc_middle/src/query/mod.rs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1949,7 +1949,7 @@ rustc_queries! {
19491949
desc { "normalizing `{}`", goal.value }
19501950
}
19511951

1952-
query implied_outlives_bounds(
1952+
query implied_outlives_bounds_compat(
19531953
goal: CanonicalTyGoal<'tcx>
19541954
) -> Result<
19551955
&'tcx Canonical<'tcx, canonical::QueryResponse<'tcx, Vec<OutlivesBound<'tcx>>>>,
@@ -1958,6 +1958,15 @@ rustc_queries! {
19581958
desc { "computing implied outlives bounds for `{}`", goal.value.value }
19591959
}
19601960

1961+
query implied_outlives_bounds(
1962+
goal: CanonicalTyGoal<'tcx>
1963+
) -> Result<
1964+
&'tcx Canonical<'tcx, canonical::QueryResponse<'tcx, Vec<OutlivesBound<'tcx>>>>,
1965+
NoSolution,
1966+
> {
1967+
desc { "computing implied outlives bounds v2 for `{}`", goal.value.value }
1968+
}
1969+
19611970
/// Do not call this query directly:
19621971
/// invoke `DropckOutlives::new(dropped_ty)).fully_perform(typeck.infcx)` instead.
19631972
query dropck_outlives(

‎compiler/rustc_middle/src/traits/query.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ pub struct NormalizationResult<'tcx> {
191191
/// case they are called implied bounds). They are fed to the
192192
/// `OutlivesEnv` which in turn is supplied to the region checker and
193193
/// other parts of the inference system.
194-
#[derive(Clone, Debug, TypeFoldable, TypeVisitable, HashStable)]
194+
#[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, HashStable)]
195195
pub enum OutlivesBound<'tcx> {
196196
RegionSubRegion(ty::Region<'tcx>, ty::Region<'tcx>),
197197
RegionSubParam(ty::Region<'tcx>, ty::ParamTy),

‎compiler/rustc_session/src/options.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1724,6 +1724,8 @@ options! {
17241724
"run all passes except codegen; no output"),
17251725
no_generate_arange_section: bool = (false, parse_no_flag, [TRACKED],
17261726
"omit DWARF address ranges that give faster lookups"),
1727+
no_implied_bounds_compat: bool = (false, parse_bool, [TRACKED],
1728+
"disable the compatibility version of the `implied_bounds_ty` query"),
17271729
no_jump_tables: bool = (false, parse_no_flag, [TRACKED],
17281730
"disable the jump tables and lookup tables that can be generated from a switch case lowering"),
17291731
no_leak_check: bool = (false, parse_no_flag, [UNTRACKED],

‎compiler/rustc_trait_selection/src/traits/misc.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ pub fn all_fields_implement_trait<'tcx>(
194194
infcx.implied_bounds_tys(
195195
param_env,
196196
parent_cause.body_id,
197-
FxIndexSet::from_iter([self_type]),
197+
&FxIndexSet::from_iter([self_type]),
198198
),
199199
);
200200
let errors = infcx.resolve_regions(&outlives_env);

‎compiler/rustc_trait_selection/src/traits/outlives_bounds.rs

Lines changed: 120 additions & 90 deletions
Original file line numberDiff line numberDiff line change
@@ -9,123 +9,153 @@ use rustc_span::def_id::LocalDefId;
99

1010
pub use rustc_middle::traits::query::OutlivesBound;
1111

12+
pub type BoundsCompat<'a, 'tcx: 'a> = impl Iterator<Item = OutlivesBound<'tcx>> + 'a;
1213
pub type Bounds<'a, 'tcx: 'a> = impl Iterator<Item = OutlivesBound<'tcx>> + 'a;
1314
pub trait InferCtxtExt<'a, 'tcx> {
14-
fn implied_outlives_bounds(
15-
&self,
15+
/// Do *NOT* call this directly.
16+
fn implied_bounds_tys_compat(
17+
&'a self,
1618
param_env: ty::ParamEnv<'tcx>,
1719
body_id: LocalDefId,
18-
ty: Ty<'tcx>,
19-
) -> Vec<OutlivesBound<'tcx>>;
20+
tys: &'a FxIndexSet<Ty<'tcx>>,
21+
compat: bool,
22+
) -> BoundsCompat<'a, 'tcx>;
2023

24+
/// If `-Z no-implied-bounds-compat` is set, calls `implied_bounds_tys_compat`
25+
/// with `compat` set to `true`, otherwise `false`.
2126
fn implied_bounds_tys(
2227
&'a self,
2328
param_env: ty::ParamEnv<'tcx>,
2429
body_id: LocalDefId,
25-
tys: FxIndexSet<Ty<'tcx>>,
30+
tys: &'a FxIndexSet<Ty<'tcx>>,
2631
) -> Bounds<'a, 'tcx>;
2732
}
2833

29-
impl<'a, 'tcx: 'a> InferCtxtExt<'a, 'tcx> for InferCtxt<'tcx> {
30-
/// Implied bounds are region relationships that we deduce
31-
/// automatically. The idea is that (e.g.) a caller must check that a
32-
/// function's argument types are well-formed immediately before
33-
/// calling that fn, and hence the *callee* can assume that its
34-
/// argument types are well-formed. This may imply certain relationships
35-
/// between generic parameters. For example:
36-
/// ```
37-
/// fn foo<T>(x: &T) {}
38-
/// ```
39-
/// can only be called with a `'a` and `T` such that `&'a T` is WF.
40-
/// For `&'a T` to be WF, `T: 'a` must hold. So we can assume `T: 'a`.
41-
///
42-
/// # Parameters
43-
///
44-
/// - `param_env`, the where-clauses in scope
45-
/// - `body_id`, the body-id to use when normalizing assoc types.
46-
/// Note that this may cause outlives obligations to be injected
47-
/// into the inference context with this body-id.
48-
/// - `ty`, the type that we are supposed to assume is WF.
49-
#[instrument(level = "debug", skip(self, param_env, body_id), ret)]
50-
fn implied_outlives_bounds(
51-
&self,
52-
param_env: ty::ParamEnv<'tcx>,
53-
body_id: LocalDefId,
54-
ty: Ty<'tcx>,
55-
) -> Vec<OutlivesBound<'tcx>> {
56-
let ty = self.resolve_vars_if_possible(ty);
57-
let ty = OpportunisticRegionResolver::new(self).fold_ty(ty);
34+
/// Implied bounds are region relationships that we deduce
35+
/// automatically. The idea is that (e.g.) a caller must check that a
36+
/// function's argument types are well-formed immediately before
37+
/// calling that fn, and hence the *callee* can assume that its
38+
/// argument types are well-formed. This may imply certain relationships
39+
/// between generic parameters. For example:
40+
/// ```
41+
/// fn foo<T>(x: &T) {}
42+
/// ```
43+
/// can only be called with a `'a` and `T` such that `&'a T` is WF.
44+
/// For `&'a T` to be WF, `T: 'a` must hold. So we can assume `T: 'a`.
45+
///
46+
/// # Parameters
47+
///
48+
/// - `param_env`, the where-clauses in scope
49+
/// - `body_id`, the body-id to use when normalizing assoc types.
50+
/// Note that this may cause outlives obligations to be injected
51+
/// into the inference context with this body-id.
52+
/// - `ty`, the type that we are supposed to assume is WF.
53+
#[instrument(level = "debug", skip(infcx, param_env, body_id), ret)]
54+
fn implied_outlives_bounds<'a, 'tcx>(
55+
infcx: &'a InferCtxt<'tcx>,
56+
param_env: ty::ParamEnv<'tcx>,
57+
body_id: LocalDefId,
58+
ty: Ty<'tcx>,
59+
compat: bool,
60+
) -> Vec<OutlivesBound<'tcx>> {
61+
let ty = infcx.resolve_vars_if_possible(ty);
62+
let ty = OpportunisticRegionResolver::new(infcx).fold_ty(ty);
5863

59-
// We do not expect existential variables in implied bounds.
60-
// We may however encounter unconstrained lifetime variables
61-
// in very rare cases.
62-
//
63-
// See `ui/implied-bounds/implied-bounds-unconstrained-2.rs` for
64-
// an example.
65-
assert!(!ty.has_non_region_infer());
64+
// We do not expect existential variables in implied bounds.
65+
// We may however encounter unconstrained lifetime variables
66+
// in very rare cases.
67+
//
68+
// See `ui/implied-bounds/implied-bounds-unconstrained-2.rs` for
69+
// an example.
70+
assert!(!ty.has_non_region_infer());
6671

67-
let mut canonical_var_values = OriginalQueryValues::default();
68-
let canonical_ty = self.canonicalize_query(param_env.and(ty), &mut canonical_var_values);
69-
let Ok(canonical_result) = self.tcx.implied_outlives_bounds(canonical_ty) else {
70-
return vec![];
71-
};
72+
let mut canonical_var_values = OriginalQueryValues::default();
73+
let canonical_ty = infcx.canonicalize_query(param_env.and(ty), &mut canonical_var_values);
74+
let implied_bounds_result = if compat {
75+
infcx.tcx.implied_outlives_bounds_compat(canonical_ty)
76+
} else {
77+
infcx.tcx.implied_outlives_bounds(canonical_ty)
78+
};
79+
let Ok(canonical_result) = implied_bounds_result else {
80+
return vec![];
81+
};
7282

73-
let mut constraints = QueryRegionConstraints::default();
74-
let Ok(InferOk { value: mut bounds, obligations }) = self
75-
.instantiate_nll_query_response_and_region_obligations(
76-
&ObligationCause::dummy(),
77-
param_env,
78-
&canonical_var_values,
79-
canonical_result,
80-
&mut constraints,
81-
)
82-
else {
83-
return vec![];
84-
};
85-
assert_eq!(&obligations, &[]);
83+
let mut constraints = QueryRegionConstraints::default();
84+
let Ok(InferOk { value: mut bounds, obligations }) = infcx
85+
.instantiate_nll_query_response_and_region_obligations(
86+
&ObligationCause::dummy(),
87+
param_env,
88+
&canonical_var_values,
89+
canonical_result,
90+
&mut constraints,
91+
)
92+
else {
93+
return vec![];
94+
};
95+
assert_eq!(&obligations, &[]);
8696

87-
// Because of #109628, we may have unexpected placeholders. Ignore them!
88-
// FIXME(#109628): panic in this case once the issue is fixed.
89-
bounds.retain(|bound| !bound.has_placeholders());
97+
// Because of #109628, we may have unexpected placeholders. Ignore them!
98+
// FIXME(#109628): panic in this case once the issue is fixed.
99+
bounds.retain(|bound| !bound.has_placeholders());
90100

91-
if !constraints.is_empty() {
92-
let span = self.tcx.def_span(body_id);
101+
if !constraints.is_empty() {
102+
let span = infcx.tcx.def_span(body_id);
93103

94-
debug!(?constraints);
95-
if !constraints.member_constraints.is_empty() {
96-
span_bug!(span, "{:#?}", constraints.member_constraints);
97-
}
104+
debug!(?constraints);
105+
if !constraints.member_constraints.is_empty() {
106+
span_bug!(span, "{:#?}", constraints.member_constraints);
107+
}
98108

99-
// Instantiation may have produced new inference variables and constraints on those
100-
// variables. Process these constraints.
101-
let ocx = ObligationCtxt::new(self);
102-
let cause = ObligationCause::misc(span, body_id);
103-
for &constraint in &constraints.outlives {
104-
ocx.register_obligation(self.query_outlives_constraint_to_obligation(
105-
constraint,
106-
cause.clone(),
107-
param_env,
108-
));
109-
}
109+
// Instantiation may have produced new inference variables and constraints on those
110+
// variables. Process these constraints.
111+
let ocx = ObligationCtxt::new(infcx);
112+
let cause = ObligationCause::misc(span, body_id);
113+
for &constraint in &constraints.outlives {
114+
ocx.register_obligation(infcx.query_outlives_constraint_to_obligation(
115+
constraint,
116+
cause.clone(),
117+
param_env,
118+
));
119+
}
110120

111-
let errors = ocx.select_all_or_error();
112-
if !errors.is_empty() {
113-
self.dcx().span_delayed_bug(
114-
span,
115-
"implied_outlives_bounds failed to solve obligations from instantiation",
116-
);
117-
}
118-
};
121+
let errors = ocx.select_all_or_error();
122+
if !errors.is_empty() {
123+
infcx.dcx().span_delayed_bug(
124+
span,
125+
"implied_outlives_bounds failed to solve obligations from instantiation",
126+
);
127+
}
128+
};
119129

120-
bounds
130+
bounds
131+
}
132+
133+
impl<'a, 'tcx: 'a> InferCtxtExt<'a, 'tcx> for InferCtxt<'tcx> {
134+
fn implied_bounds_tys_compat(
135+
&'a self,
136+
param_env: ParamEnv<'tcx>,
137+
body_id: LocalDefId,
138+
tys: &'a FxIndexSet<Ty<'tcx>>,
139+
compat: bool,
140+
) -> BoundsCompat<'a, 'tcx> {
141+
tys.iter()
142+
.flat_map(move |ty| implied_outlives_bounds(self, param_env, body_id, *ty, compat))
121143
}
122144

123145
fn implied_bounds_tys(
124146
&'a self,
125147
param_env: ParamEnv<'tcx>,
126148
body_id: LocalDefId,
127-
tys: FxIndexSet<Ty<'tcx>>,
149+
tys: &'a FxIndexSet<Ty<'tcx>>,
128150
) -> Bounds<'a, 'tcx> {
129-
tys.into_iter().flat_map(move |ty| self.implied_outlives_bounds(param_env, body_id, ty))
151+
tys.iter().flat_map(move |ty| {
152+
implied_outlives_bounds(
153+
self,
154+
param_env,
155+
body_id,
156+
*ty,
157+
!self.tcx.sess.opts.unstable_opts.no_implied_bounds_compat,
158+
)
159+
})
130160
}
131161
}

‎compiler/rustc_trait_selection/src/traits/query/type_op/implied_outlives_bounds.rs

Lines changed: 81 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,11 @@ use crate::traits::ObligationCtxt;
55

66
use rustc_infer::infer::canonical::Canonical;
77
use rustc_infer::infer::outlives::components::{push_outlives_components, Component};
8+
use rustc_infer::infer::resolve::OpportunisticRegionResolver;
89
use rustc_infer::traits::query::OutlivesBound;
910
use rustc_middle::infer::canonical::CanonicalQueryResponse;
1011
use rustc_middle::traits::ObligationCause;
11-
use rustc_middle::ty::{self, ParamEnvAnd, Ty, TyCtxt, TypeVisitableExt};
12+
use rustc_middle::ty::{self, ParamEnvAnd, Ty, TyCtxt, TypeFolder, TypeVisitableExt};
1213
use rustc_span::def_id::CRATE_DEF_ID;
1314
use rustc_span::DUMMY_SP;
1415
use smallvec::{smallvec, SmallVec};
@@ -62,6 +63,85 @@ pub fn compute_implied_outlives_bounds_inner<'tcx>(
6263
ocx: &ObligationCtxt<'_, 'tcx>,
6364
param_env: ty::ParamEnv<'tcx>,
6465
ty: Ty<'tcx>,
66+
) -> Result<Vec<OutlivesBound<'tcx>>, NoSolution> {
67+
let normalize_op = |ty| {
68+
let ty = ocx.normalize(&ObligationCause::dummy(), param_env, ty);
69+
if !ocx.select_all_or_error().is_empty() {
70+
return Err(NoSolution);
71+
}
72+
let ty = ocx.infcx.resolve_vars_if_possible(ty);
73+
let ty = OpportunisticRegionResolver::new(&ocx.infcx).fold_ty(ty);
74+
Ok(ty)
75+
};
76+
77+
// Sometimes when we ask what it takes for T: WF, we get back that
78+
// U: WF is required; in that case, we push U onto this stack and
79+
// process it next. Because the resulting predicates aren't always
80+
// guaranteed to be a subset of the original type, so we need to store the
81+
// WF args we've computed in a set.
82+
let mut checked_wf_args = rustc_data_structures::fx::FxHashSet::default();
83+
let mut wf_args = vec![ty.into(), normalize_op(ty)?.into()];
84+
85+
let mut outlives_bounds: Vec<OutlivesBound<'tcx>> = vec![];
86+
87+
while let Some(arg) = wf_args.pop() {
88+
if !checked_wf_args.insert(arg) {
89+
continue;
90+
}
91+
92+
// From the full set of obligations, just filter down to the region relationships.
93+
for obligation in
94+
wf::unnormalized_obligations(ocx.infcx, param_env, arg).into_iter().flatten()
95+
{
96+
assert!(!obligation.has_escaping_bound_vars());
97+
let Some(pred) = obligation.predicate.kind().no_bound_vars() else {
98+
continue;
99+
};
100+
match pred {
101+
// FIXME(const_generics): Make sure that `<'a, 'b, const N: &'a &'b u32>` is sound
102+
// if we ever support that
103+
ty::PredicateKind::Clause(ty::ClauseKind::Trait(..))
104+
| ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(..))
105+
| ty::PredicateKind::Subtype(..)
106+
| ty::PredicateKind::Coerce(..)
107+
| ty::PredicateKind::Clause(ty::ClauseKind::Projection(..))
108+
| ty::PredicateKind::ObjectSafe(..)
109+
| ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..))
110+
| ty::PredicateKind::ConstEquate(..)
111+
| ty::PredicateKind::Ambiguous
112+
| ty::PredicateKind::NormalizesTo(..)
113+
| ty::PredicateKind::AliasRelate(..) => {}
114+
115+
// We need to search through *all* WellFormed predicates
116+
ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(arg)) => {
117+
wf_args.push(arg);
118+
}
119+
120+
// We need to register region relationships
121+
ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(
122+
ty::OutlivesPredicate(r_a, r_b),
123+
)) => outlives_bounds.push(OutlivesBound::RegionSubRegion(r_b, r_a)),
124+
125+
ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(
126+
ty_a,
127+
r_b,
128+
))) => {
129+
let ty_a = normalize_op(ty_a)?;
130+
let mut components = smallvec![];
131+
push_outlives_components(ocx.infcx.tcx, ty_a, &mut components);
132+
outlives_bounds.extend(implied_bounds_from_components(r_b, components))
133+
}
134+
}
135+
}
136+
}
137+
138+
Ok(outlives_bounds)
139+
}
140+
141+
pub fn compute_implied_outlives_bounds_compat_inner<'tcx>(
142+
ocx: &ObligationCtxt<'_, 'tcx>,
143+
param_env: ty::ParamEnv<'tcx>,
144+
ty: Ty<'tcx>,
65145
) -> Result<Vec<OutlivesBound<'tcx>>, NoSolution> {
66146
let tcx = ocx.infcx.tcx;
67147

‎compiler/rustc_traits/src/implied_outlives_bounds.rs

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,29 @@ use rustc_infer::traits::query::OutlivesBound;
88
use rustc_middle::query::Providers;
99
use rustc_middle::ty::TyCtxt;
1010
use rustc_trait_selection::infer::InferCtxtBuilderExt;
11-
use rustc_trait_selection::traits::query::type_op::implied_outlives_bounds::compute_implied_outlives_bounds_inner;
11+
use rustc_trait_selection::traits::query::type_op::implied_outlives_bounds::{
12+
compute_implied_outlives_bounds_compat_inner, compute_implied_outlives_bounds_inner,
13+
};
1214
use rustc_trait_selection::traits::query::{CanonicalTyGoal, NoSolution};
1315

1416
pub(crate) fn provide(p: &mut Providers) {
17+
*p = Providers { implied_outlives_bounds_compat, ..*p };
1518
*p = Providers { implied_outlives_bounds, ..*p };
1619
}
1720

21+
fn implied_outlives_bounds_compat<'tcx>(
22+
tcx: TyCtxt<'tcx>,
23+
goal: CanonicalTyGoal<'tcx>,
24+
) -> Result<
25+
&'tcx Canonical<'tcx, canonical::QueryResponse<'tcx, Vec<OutlivesBound<'tcx>>>>,
26+
NoSolution,
27+
> {
28+
tcx.infer_ctxt().enter_canonical_trait_query(&goal, |ocx, key| {
29+
let (param_env, ty) = key.into_parts();
30+
compute_implied_outlives_bounds_compat_inner(ocx, param_env, ty)
31+
})
32+
}
33+
1834
fn implied_outlives_bounds<'tcx>(
1935
tcx: TyCtxt<'tcx>,
2036
goal: CanonicalTyGoal<'tcx>,

‎tests/ui/associated-inherent-types/issue-111404-1.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,5 +10,6 @@ impl<'a> Foo<fn(&'a ())> {
1010
fn bar(_: fn(Foo<for<'b> fn(Foo<fn(&'b ())>::Assoc)>::Assoc)) {}
1111
//~^ ERROR higher-ranked subtype error
1212
//~| ERROR higher-ranked subtype error
13+
//~| ERROR higher-ranked subtype error
1314

1415
fn main() {}

‎tests/ui/associated-inherent-types/issue-111404-1.stderr

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,5 +12,13 @@ LL | fn bar(_: fn(Foo<for<'b> fn(Foo<fn(&'b ())>::Assoc)>::Assoc)) {}
1212
|
1313
= note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`
1414

15-
error: aborting due to 2 previous errors
15+
error: higher-ranked subtype error
16+
--> $DIR/issue-111404-1.rs:10:1
17+
|
18+
LL | fn bar(_: fn(Foo<for<'b> fn(Foo<fn(&'b ())>::Assoc)>::Assoc)) {}
19+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
20+
|
21+
= note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`
22+
23+
error: aborting due to 3 previous errors
1624

‎tests/ui/implied-bounds/auxiliary/bevy_ecs.rs

Lines changed: 0 additions & 18 deletions
This file was deleted.
Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,26 @@
1-
// aux-crate:bevy_ecs=bevy_ecs.rs
21
// check-pass
3-
// Related to Bevy regression #118553
42

5-
extern crate bevy_ecs;
3+
// We currently special case bevy from erroring on incorrect implied bounds
4+
// from normalization (issue #109628).
5+
// Otherwise, we would expect this to hit that error.
66

7-
use bevy_ecs::*;
7+
pub trait WorldQuery {}
8+
impl WorldQuery for &u8 {}
9+
10+
pub struct Query<Q: WorldQuery>(Q);
11+
12+
pub trait SystemParam {
13+
type State;
14+
}
15+
impl<Q: WorldQuery + 'static> SystemParam for Query<Q> {
16+
type State = ();
17+
// `Q: 'static` is required because we need the TypeId of Q ...
18+
}
19+
20+
pub struct ParamSet<T: SystemParam>(T) where T::State: Sized;
821

922
fn handler<'a>(_: ParamSet<Query<&'a u8>>) {}
1023

24+
fn ref_handler<'a>(_: &ParamSet<Query<&'a u8>>) {}
25+
1126
fn main() {}

‎tests/ui/implied-bounds/from-trait-impl.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
// check-pass
2-
// known-bug: #109628
3-
41
trait Trait {
52
type Assoc;
63
}
@@ -14,11 +11,13 @@ where
1411
T::Assoc: Clone; // any predicate using `T::Assoc` works here
1512

1613
fn func1(foo: Foo<(&str,)>) {
14+
//~^ ERROR `&str` does not fulfill the required lifetime
1715
let _: &'static str = foo.0.0;
1816
}
1917

2018
trait TestTrait {}
2119

2220
impl<X> TestTrait for [Foo<(X,)>; 1] {}
21+
//~^ ERROR `X` may not live long enough
2322

2423
fn main() {}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
error[E0477]: the type `&str` does not fulfill the required lifetime
2+
--> $DIR/from-trait-impl.rs:13:15
3+
|
4+
LL | fn func1(foo: Foo<(&str,)>) {
5+
| ^^^^^^^^^^^^
6+
|
7+
= note: type must satisfy the static lifetime
8+
9+
error[E0310]: the parameter type `X` may not live long enough
10+
--> $DIR/from-trait-impl.rs:20:23
11+
|
12+
LL | impl<X> TestTrait for [Foo<(X,)>; 1] {}
13+
| ^^^^^^^^^^^^^^
14+
| |
15+
| the parameter type `X` must be valid for the static lifetime...
16+
| ...so that the type `X` will meet its required lifetime bounds
17+
|
18+
help: consider adding an explicit lifetime bound
19+
|
20+
LL | impl<X: 'static> TestTrait for [Foo<(X,)>; 1] {}
21+
| +++++++++
22+
23+
error: aborting due to 2 previous errors
24+
25+
Some errors have detailed explanations: E0310, E0477.
26+
For more information about an error, try `rustc --explain E0310`.

‎tests/ui/implied-bounds/gluon_salsa.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// check-pass
2-
// Related to Bevy regression #118553
2+
// Found in a crater run on #118553
33

44
pub trait QueryBase {
55
type Db;
@@ -17,8 +17,7 @@ pub struct QueryTable<'me, Q, DB> {
1717
_marker: Option<&'me ()>,
1818
}
1919

20-
impl<'me, Q> QueryTable<'me, Q, <Q as QueryBase>::Db>
21-
// projection is important
20+
impl<'me, Q> QueryTable<'me, Q, <Q as QueryBase>::Db> // projection is important
2221
// ^^^ removing 'me (and in QueryTable) gives a different error
2322
where
2423
Q: for<'f> AsyncQueryFunction<'f>,

‎tests/ui/implied-bounds/normalization-nested.lifetime.stderr

Lines changed: 0 additions & 33 deletions
This file was deleted.

‎tests/ui/implied-bounds/normalization-nested.rs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,8 @@
11
// Test for normalization of projections that appear in the item bounds
22
// (versus those that appear directly in the input types).
3-
// Both revisions should pass. `lifetime` revision is a bug.
43
//
54
// revisions: param_ty lifetime
6-
// [param_ty] check-pass
7-
// [lifetime] check-fail
8-
// [lifetime] known-bug: #109799
5+
// check-pass
96

107
pub trait Iter {
118
type Item;

‎tests/ui/implied-bounds/sod_service_chain.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
// check-pass
2-
// Related to crater regressions on #118553
1+
// Found in a crater run on #118553
32

43
pub trait Debug {}
54

@@ -30,6 +29,9 @@ impl<P: Service, S: Service<Input = P::Output>> ServiceChainBuilder<P, S> {
3029
pub fn next<NS: Service<Input = S::Output>>(
3130
self,
3231
) -> ServiceChainBuilder<ServiceChain<P, S>, NS> {
32+
//~^ the associated type
33+
//~| the associated type
34+
//~| the associated type
3335
panic!();
3436
}
3537
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
error[E0310]: the associated type `<P as Service>::Error` may not live long enough
2+
--> $DIR/sod_service_chain.rs:31:10
3+
|
4+
LL | ) -> ServiceChainBuilder<ServiceChain<P, S>, NS> {
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6+
| |
7+
| the associated type `<P as Service>::Error` must be valid for the static lifetime...
8+
| ...so that the type `<P as Service>::Error` will meet its required lifetime bounds
9+
|
10+
help: consider adding an explicit lifetime bound
11+
|
12+
LL | ) -> ServiceChainBuilder<ServiceChain<P, S>, NS> where <P as Service>::Error: 'static {
13+
| ++++++++++++++++++++++++++++++++++++
14+
15+
error[E0310]: the associated type `<S as Service>::Error` may not live long enough
16+
--> $DIR/sod_service_chain.rs:31:10
17+
|
18+
LL | ) -> ServiceChainBuilder<ServiceChain<P, S>, NS> {
19+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
20+
| |
21+
| the associated type `<S as Service>::Error` must be valid for the static lifetime...
22+
| ...so that the type `<S as Service>::Error` will meet its required lifetime bounds
23+
|
24+
help: consider adding an explicit lifetime bound
25+
|
26+
LL | ) -> ServiceChainBuilder<ServiceChain<P, S>, NS> where <S as Service>::Error: 'static {
27+
| ++++++++++++++++++++++++++++++++++++
28+
29+
error: aborting due to 2 previous errors
30+
31+
For more information about this error, try `rustc --explain E0310`.

‎tests/ui/inference/issue-80409.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,12 @@
1-
// check-pass
1+
// This should not pass, because `usize: Fsm` does not hold. However, it currently ICEs.
2+
3+
// check-fail
4+
// known-bug: #80409
5+
// failure-status: 101
6+
// normalize-stderr-test "note: .*\n\n" -> ""
7+
// normalize-stderr-test "thread 'rustc' panicked.*\n" -> ""
8+
// normalize-stderr-test "(error: internal compiler error: [^:]+):\d+:\d+: " -> "$1:LL:CC: "
9+
// rustc-env:RUST_BACKTRACE=0
210

311
#![allow(unreachable_code, unused)]
412

‎tests/ui/inference/issue-80409.stderr

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
error: internal compiler error: error performing ParamEnvAnd { param_env: ParamEnv { caller_bounds: [], reveal: UserFacing }, value: ImpliedOutlivesBounds { ty: &'?2 mut StateContext<'?3, usize> } }
2+
|
3+
= query stack during panic:
4+
end of query stack
5+
error: aborting due to 1 previous error
6+

0 commit comments

Comments
 (0)
This repository has been archived.