Skip to content

Commit 6bf600b

Browse files
committed
Auto merge of #120019 - lcnr:fn-wf, r=BoxyUwU
fix fn/const items implied bounds and wf check (rebase) A rebase of #104098, see that PR for discussion. This is pretty much entirely the work of `@aliemjay.` I received his permission for this rebase. --- These are two distinct changes (edit: actually three, see below): 1. Wf-check all fn item args. This is a soundness fix. Fixes #104005 2. Use implied bounds from impl header in borrowck of associated functions/consts. This strictly accepts more code and helps to mitigate the impact of other breaking changes. Fixes #98852 Fixes #102611 The first is a breaking change and will likely have a big impact without the the second one. See the first commit for how it breaks libstd. Landing the second one without the first will allow more incorrect code to pass. For example an exploit of #104005 would be as simple as: ```rust use core::fmt::Display; trait ExtendLt<Witness> { fn extend(self) -> Box<dyn Display>; } impl<T: Display> ExtendLt<&'static T> for T { fn extend(self) -> Box<dyn Display> { Box::new(self) } } fn main() { let val = (&String::new()).extend(); println!("{val}"); } ``` The third change is to to check WF of user type annotations before normalizing them (fixes #104764, fixes #104763). It is mutually dependent on the second change above: an attempt to land it separately in #104746 caused several crater regressions that can all be mitigated by using the implied from the impl header. It is also necessary for the soundness of associated consts that use the implied bounds of impl header. See #104763 and how the third commit fixes the soundness issue in `tests/ui/wf/wf-associated-const.rs` that was introduces by the previous commit. r? types
2 parents 6ed31ab + 66090ef commit 6bf600b

23 files changed

+425
-123
lines changed

compiler/rustc_borrowck/src/type_check/free_region_relations.rs

+24-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use rustc_data_structures::frozen::Frozen;
22
use rustc_data_structures::transitive_relation::{TransitiveRelation, TransitiveRelationBuilder};
3+
use rustc_hir::def::DefKind;
34
use rustc_infer::infer::canonical::QueryRegionConstraints;
45
use rustc_infer::infer::outlives;
56
use rustc_infer::infer::outlives::env::RegionBoundPairs;
@@ -195,7 +196,9 @@ impl<'tcx> UniversalRegionRelationsBuilder<'_, 'tcx> {
195196

196197
#[instrument(level = "debug", skip(self))]
197198
pub(crate) fn create(mut self) -> CreateResult<'tcx> {
198-
let span = self.infcx.tcx.def_span(self.universal_regions.defining_ty.def_id());
199+
let tcx = self.infcx.tcx;
200+
let defining_ty_def_id = self.universal_regions.defining_ty.def_id().expect_local();
201+
let span = tcx.def_span(defining_ty_def_id);
199202

200203
// Insert the facts we know from the predicates. Why? Why not.
201204
let param_env = self.param_env;
@@ -275,6 +278,26 @@ impl<'tcx> UniversalRegionRelationsBuilder<'_, 'tcx> {
275278
normalized_inputs_and_output.push(norm_ty);
276279
}
277280

281+
// Add implied bounds from impl header.
282+
if matches!(tcx.def_kind(defining_ty_def_id), DefKind::AssocFn | DefKind::AssocConst) {
283+
for &(ty, _) in tcx.assumed_wf_types(tcx.local_parent(defining_ty_def_id)) {
284+
let Ok(TypeOpOutput { output: norm_ty, constraints: c, .. }) = self
285+
.param_env
286+
.and(type_op::normalize::Normalize::new(ty))
287+
.fully_perform(self.infcx, span)
288+
else {
289+
tcx.dcx().span_delayed_bug(span, format!("failed to normalize {ty:?}"));
290+
continue;
291+
};
292+
constraints.extend(c);
293+
294+
// We currently add implied bounds from the normalized ty only.
295+
// This is more conservative and matches wfcheck behavior.
296+
let c = self.add_implied_bounds(norm_ty);
297+
constraints.extend(c);
298+
}
299+
}
300+
278301
for c in constraints {
279302
self.push_region_constraints(c, span);
280303
}

compiler/rustc_borrowck/src/type_check/mod.rs

+10
Original file line numberDiff line numberDiff line change
@@ -407,6 +407,16 @@ impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> {
407407
instantiated_predicates,
408408
locations,
409409
);
410+
411+
assert!(!matches!(
412+
tcx.impl_of_method(def_id).map(|imp| tcx.def_kind(imp)),
413+
Some(DefKind::Impl { of_trait: true })
414+
));
415+
self.cx.prove_predicates(
416+
args.types().map(|ty| ty::ClauseKind::WellFormed(ty.into())),
417+
locations,
418+
ConstraintCategory::Boring,
419+
);
410420
}
411421
}
412422
}

compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs

+32-22
Original file line numberDiff line numberDiff line change
@@ -63,13 +63,16 @@ fn relate_mir_and_user_ty<'tcx>(
6363
user_ty: Ty<'tcx>,
6464
) -> Result<(), NoSolution> {
6565
let cause = ObligationCause::dummy_with_span(span);
66+
ocx.register_obligation(Obligation::new(
67+
ocx.infcx.tcx,
68+
cause.clone(),
69+
param_env,
70+
ty::ClauseKind::WellFormed(user_ty.into()),
71+
));
72+
6673
let user_ty = ocx.normalize(&cause, param_env, user_ty);
6774
ocx.eq(&cause, param_env, mir_ty, user_ty)?;
6875

69-
// FIXME(#104764): We should check well-formedness before normalization.
70-
let predicate =
71-
ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(user_ty.into())));
72-
ocx.register_obligation(Obligation::new(ocx.infcx.tcx, cause, param_env, predicate));
7376
Ok(())
7477
}
7578

@@ -113,31 +116,38 @@ fn relate_mir_and_user_args<'tcx>(
113116
ocx.register_obligation(Obligation::new(tcx, cause, param_env, instantiated_predicate));
114117
}
115118

119+
// Now prove the well-formedness of `def_id` with `substs`.
120+
// Note for some items, proving the WF of `ty` is not sufficient because the
121+
// well-formedness of an item may depend on the WF of gneneric args not present in the
122+
// item's type. Currently this is true for associated consts, e.g.:
123+
// ```rust
124+
// impl<T> MyTy<T> {
125+
// const CONST: () = { /* arbitrary code that depends on T being WF */ };
126+
// }
127+
// ```
128+
for arg in args {
129+
ocx.register_obligation(Obligation::new(
130+
tcx,
131+
cause.clone(),
132+
param_env,
133+
ty::ClauseKind::WellFormed(arg),
134+
));
135+
}
136+
116137
if let Some(UserSelfTy { impl_def_id, self_ty }) = user_self_ty {
138+
ocx.register_obligation(Obligation::new(
139+
tcx,
140+
cause.clone(),
141+
param_env,
142+
ty::ClauseKind::WellFormed(self_ty.into()),
143+
));
144+
117145
let self_ty = ocx.normalize(&cause, param_env, self_ty);
118146
let impl_self_ty = tcx.type_of(impl_def_id).instantiate(tcx, args);
119147
let impl_self_ty = ocx.normalize(&cause, param_env, impl_self_ty);
120148

121149
ocx.eq(&cause, param_env, self_ty, impl_self_ty)?;
122-
let predicate = ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(
123-
impl_self_ty.into(),
124-
)));
125-
ocx.register_obligation(Obligation::new(tcx, cause.clone(), param_env, predicate));
126150
}
127151

128-
// In addition to proving the predicates, we have to
129-
// prove that `ty` is well-formed -- this is because
130-
// the WF of `ty` is predicated on the args being
131-
// well-formed, and we haven't proven *that*. We don't
132-
// want to prove the WF of types from `args` directly because they
133-
// haven't been normalized.
134-
//
135-
// FIXME(nmatsakis): Well, perhaps we should normalize
136-
// them? This would only be relevant if some input
137-
// type were ill-formed but did not appear in `ty`,
138-
// which...could happen with normalization...
139-
let predicate =
140-
ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(ty.into())));
141-
ocx.register_obligation(Obligation::new(tcx, cause, param_env, predicate));
142152
Ok(())
143153
}

compiler/rustc_trait_selection/src/traits/query/type_op/prove_predicate.rs

+17
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,23 @@ impl<'tcx> super::QueryTypeOp<'tcx> for ProvePredicate<'tcx> {
3030
}
3131
}
3232

33+
if let ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(arg)) =
34+
key.value.predicate.kind().skip_binder()
35+
{
36+
match arg.as_type()?.kind() {
37+
ty::Param(_)
38+
| ty::Bool
39+
| ty::Char
40+
| ty::Int(_)
41+
| ty::Float(_)
42+
| ty::Str
43+
| ty::Uint(_) => {
44+
return Some(());
45+
}
46+
_ => {}
47+
}
48+
}
49+
3350
None
3451
}
3552

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// The method `assert_static` should be callable only for static values,
2+
// because the impl has an implied bound `where T: 'static`.
3+
4+
// check-fail
5+
6+
trait AnyStatic<Witness>: Sized {
7+
fn assert_static(self) {}
8+
}
9+
10+
impl<T> AnyStatic<&'static T> for T {}
11+
12+
fn main() {
13+
(&String::new()).assert_static();
14+
//~^ ERROR temporary value dropped while borrowed
15+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
error[E0716]: temporary value dropped while borrowed
2+
--> $DIR/fn-item-check-trait-ref.rs:13:7
3+
|
4+
LL | (&String::new()).assert_static();
5+
| --^^^^^^^^^^^^^------------------ temporary value is freed at the end of this statement
6+
| | |
7+
| | creates a temporary value which is freed while still in use
8+
| argument requires that borrow lasts for `'static`
9+
10+
error: aborting due to 1 previous error
11+
12+
For more information about this error, try `rustc --explain E0716`.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// Regression test for #104005.
2+
//
3+
// Previously, different borrowck implementations used to disagree here.
4+
// The status of each is documented on `fn test_*`.
5+
6+
// check-fail
7+
8+
use std::fmt::Display;
9+
10+
trait Displayable {
11+
fn display(self) -> Box<dyn Display>;
12+
}
13+
14+
impl<T: Display> Displayable for (T, Option<&'static T>) {
15+
fn display(self) -> Box<dyn Display> {
16+
Box::new(self.0)
17+
}
18+
}
19+
20+
fn extend_lt<T, U>(val: T) -> Box<dyn Display>
21+
where
22+
(T, Option<U>): Displayable,
23+
{
24+
Displayable::display((val, None))
25+
}
26+
27+
// AST: fail
28+
// HIR: pass
29+
// MIR: pass
30+
pub fn test_call<'a>(val: &'a str) {
31+
extend_lt(val);
32+
//~^ ERROR borrowed data escapes outside of function
33+
}
34+
35+
// AST: fail
36+
// HIR: fail
37+
// MIR: pass
38+
pub fn test_coercion<'a>() {
39+
let _: fn(&'a str) -> _ = extend_lt;
40+
//~^ ERROR lifetime may not live long enough
41+
}
42+
43+
// AST: fail
44+
// HIR: fail
45+
// MIR: fail
46+
pub fn test_arg() {
47+
fn want<I, O>(_: I, _: impl Fn(I) -> O) {}
48+
want(&String::new(), extend_lt);
49+
//~^ ERROR temporary value dropped while borrowed
50+
}
51+
52+
// An exploit of the unsoundness.
53+
fn main() {
54+
let val = extend_lt(&String::from("blah blah blah"));
55+
//~^ ERROR temporary value dropped while borrowed
56+
println!("{}", val);
57+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
error[E0521]: borrowed data escapes outside of function
2+
--> $DIR/fn-item-check-type-params.rs:31:5
3+
|
4+
LL | pub fn test_call<'a>(val: &'a str) {
5+
| -- --- `val` is a reference that is only valid in the function body
6+
| |
7+
| lifetime `'a` defined here
8+
LL | extend_lt(val);
9+
| ^^^^^^^^^^^^^^
10+
| |
11+
| `val` escapes the function body here
12+
| argument requires that `'a` must outlive `'static`
13+
14+
error: lifetime may not live long enough
15+
--> $DIR/fn-item-check-type-params.rs:39:12
16+
|
17+
LL | pub fn test_coercion<'a>() {
18+
| -- lifetime `'a` defined here
19+
LL | let _: fn(&'a str) -> _ = extend_lt;
20+
| ^^^^^^^^^^^^^^^^ type annotation requires that `'a` must outlive `'static`
21+
22+
error[E0716]: temporary value dropped while borrowed
23+
--> $DIR/fn-item-check-type-params.rs:48:11
24+
|
25+
LL | want(&String::new(), extend_lt);
26+
| ------^^^^^^^^^^^^^------------- temporary value is freed at the end of this statement
27+
| | |
28+
| | creates a temporary value which is freed while still in use
29+
| argument requires that borrow lasts for `'static`
30+
31+
error[E0716]: temporary value dropped while borrowed
32+
--> $DIR/fn-item-check-type-params.rs:54:26
33+
|
34+
LL | let val = extend_lt(&String::from("blah blah blah"));
35+
| -----------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-- temporary value is freed at the end of this statement
36+
| | |
37+
| | creates a temporary value which is freed while still in use
38+
| argument requires that borrow lasts for `'static`
39+
40+
error: aborting due to 4 previous errors
41+
42+
Some errors have detailed explanations: E0521, E0716.
43+
For more information about an error, try `rustc --explain E0521`.

tests/ui/higher-ranked/trait-bounds/issue-59311.rs

+1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ where
1717
v.t(|| {});
1818
//~^ ERROR: higher-ranked lifetime error
1919
//~| ERROR: higher-ranked lifetime error
20+
//~| ERROR: higher-ranked lifetime error
2021
}
2122

2223
fn main() {}

tests/ui/higher-ranked/trait-bounds/issue-59311.stderr

+10-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,15 @@ LL | v.t(|| {});
66
|
77
= note: could not prove `{closure@$DIR/issue-59311.rs:17:9: 17:11} well-formed`
88

9+
error: higher-ranked lifetime error
10+
--> $DIR/issue-59311.rs:17:5
11+
|
12+
LL | v.t(|| {});
13+
| ^^^^^^^^^^
14+
|
15+
= note: could not prove `{closure@$DIR/issue-59311.rs:17:9: 17:11} well-formed`
16+
= note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`
17+
918
error: higher-ranked lifetime error
1019
--> $DIR/issue-59311.rs:17:9
1120
|
@@ -14,5 +23,5 @@ LL | v.t(|| {});
1423
|
1524
= note: could not prove `for<'a> &'a V: 'b`
1625

17-
error: aborting due to 2 previous errors
26+
error: aborting due to 3 previous errors
1827

tests/ui/implied-bounds/implied-bounds-on-trait-hierarchy.rs tests/ui/implied-bounds/implied-bounds-on-trait-hierarchy-1.rs

+4-5
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
1-
// check-pass
2-
// known-bug: #84591
1+
// issue: #84591
32

4-
// Should fail. Subtrait can incorrectly extend supertrait lifetimes even when
5-
// supertrait has weaker implied bounds than subtrait. Strongly related to
6-
// issue #25860.
3+
// Subtrait was able to incorrectly extend supertrait lifetimes even when
4+
// supertrait had weaker implied bounds than subtrait.
75

86
trait Subtrait<T>: Supertrait {}
97
trait Supertrait {
@@ -34,6 +32,7 @@ fn main() {
3432
{
3533
let x = "Hello World".to_string();
3634
subs_to_soup((x.as_str(), &mut d));
35+
//~^ does not live long enough
3736
}
3837
println!("{}", d);
3938
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
error[E0597]: `x` does not live long enough
2+
--> $DIR/implied-bounds-on-trait-hierarchy-1.rs:34:23
3+
|
4+
LL | let x = "Hello World".to_string();
5+
| - binding `x` declared here
6+
LL | subs_to_soup((x.as_str(), &mut d));
7+
| ^ borrowed value does not live long enough
8+
LL |
9+
LL | }
10+
| - `x` dropped here while still borrowed
11+
LL | println!("{}", d);
12+
| - borrow later used here
13+
14+
error: aborting due to 1 previous error
15+
16+
For more information about this error, try `rustc --explain E0597`.

0 commit comments

Comments
 (0)