Skip to content

Commit 5c25d30

Browse files
committed
Allow specialized const trait impls.
Fixes #95186. Fixes #95187.
1 parent 01a6f30 commit 5c25d30

9 files changed

+286
-21
lines changed

compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs

+44-21
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ use rustc_span::Span;
8080
use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt;
8181
use rustc_trait_selection::traits::outlives_bounds::InferCtxtExt as _;
8282
use rustc_trait_selection::traits::{self, translate_substs, wf, ObligationCtxt};
83+
use tracing::instrument;
8384

8485
pub(super) fn check_min_specialization(tcx: TyCtxt<'_>, impl_def_id: LocalDefId) {
8586
if let Some(node) = parent_specialization_node(tcx, impl_def_id) {
@@ -103,13 +104,11 @@ fn parent_specialization_node(tcx: TyCtxt<'_>, impl1_def_id: LocalDefId) -> Opti
103104
}
104105

105106
/// Check that `impl1` is a sound specialization
107+
#[instrument(level = "debug", skip(tcx))]
106108
fn check_always_applicable(tcx: TyCtxt<'_>, impl1_def_id: LocalDefId, impl2_node: Node) {
107109
if let Some((impl1_substs, impl2_substs)) = get_impl_substs(tcx, impl1_def_id, impl2_node) {
108110
let impl2_def_id = impl2_node.def_id();
109-
debug!(
110-
"check_always_applicable(\nimpl1_def_id={:?},\nimpl2_def_id={:?},\nimpl2_substs={:?}\n)",
111-
impl1_def_id, impl2_def_id, impl2_substs
112-
);
111+
debug!(?impl2_def_id, ?impl2_substs);
113112

114113
let parent_substs = if impl2_node.is_from_trait() {
115114
impl2_substs.to_vec()
@@ -280,13 +279,13 @@ fn check_static_lifetimes<'tcx>(
280279
///
281280
/// Each predicate `P` must be:
282281
///
283-
/// * global (not reference any parameters)
284-
/// * `T: Tr` predicate where `Tr` is an always-applicable trait
285-
/// * on the base `impl impl2`
286-
/// * Currently this check is done using syntactic equality, which is
287-
/// conservative but generally sufficient.
288-
/// * a well-formed predicate of a type argument of the trait being implemented,
282+
/// * Global (not reference any parameters).
283+
/// * A `T: Tr` predicate where `Tr` is an always-applicable trait.
284+
/// * Present on the base impl `impl2`.
285+
/// * This check is done using the `trait_predicates_eq` function below.
286+
/// * A well-formed predicate of a type argument of the trait being implemented,
289287
/// including the `Self`-type.
288+
#[instrument(level = "debug", skip(tcx))]
290289
fn check_predicates<'tcx>(
291290
tcx: TyCtxt<'tcx>,
292291
impl1_def_id: LocalDefId,
@@ -322,10 +321,7 @@ fn check_predicates<'tcx>(
322321
.map(|obligation| obligation.predicate)
323322
.collect()
324323
};
325-
debug!(
326-
"check_always_applicable(\nimpl1_predicates={:?},\nimpl2_predicates={:?}\n)",
327-
impl1_predicates, impl2_predicates,
328-
);
324+
debug!(?impl1_predicates, ?impl2_predicates);
329325

330326
// Since impls of always applicable traits don't get to assume anything, we
331327
// can also assume their supertraits apply.
@@ -373,25 +369,52 @@ fn check_predicates<'tcx>(
373369
);
374370

375371
for (predicate, span) in impl1_predicates {
376-
if !impl2_predicates.contains(&predicate) {
372+
if !impl2_predicates.iter().any(|pred2| trait_predicates_eq(predicate, *pred2)) {
377373
check_specialization_on(tcx, predicate, span)
378374
}
379375
}
380376
}
381377

378+
/// Checks whether two predicates are the same for the purposes of specialization.
379+
///
380+
/// This is slightly more complicated than simple syntactic equivalence, since
381+
/// we want to equate `T: Tr` with `T: ~const Tr` so this can work:
382+
///
383+
/// #[rustc_specialization_trait]
384+
/// trait Specialize { }
385+
///
386+
/// impl<T: ~const Bound> const Tr for T { }
387+
/// impl<T: Bound + Specialize> Tr for T { }
388+
fn trait_predicates_eq<'tcx>(
389+
predicate1: ty::Predicate<'tcx>,
390+
predicate2: ty::Predicate<'tcx>,
391+
) -> bool {
392+
let predicate_kind_without_constness = |kind: ty::PredicateKind<'tcx>| match kind {
393+
ty::PredicateKind::Trait(ty::TraitPredicate { trait_ref, constness: _, polarity }) => {
394+
ty::PredicateKind::Trait(ty::TraitPredicate {
395+
trait_ref,
396+
constness: ty::BoundConstness::NotConst,
397+
polarity,
398+
})
399+
}
400+
_ => kind,
401+
};
402+
403+
let pred1_kind_not_const = predicate1.kind().map_bound(predicate_kind_without_constness);
404+
let pred2_kind_not_const = predicate2.kind().map_bound(predicate_kind_without_constness);
405+
406+
pred1_kind_not_const == pred2_kind_not_const
407+
}
408+
409+
#[instrument(level = "debug", skip(tcx))]
382410
fn check_specialization_on<'tcx>(tcx: TyCtxt<'tcx>, predicate: ty::Predicate<'tcx>, span: Span) {
383-
debug!("can_specialize_on(predicate = {:?})", predicate);
384411
match predicate.kind().skip_binder() {
385412
// Global predicates are either always true or always false, so we
386413
// are fine to specialize on.
387414
_ if predicate.is_global() => (),
388415
// We allow specializing on explicitly marked traits with no associated
389416
// items.
390-
ty::PredicateKind::Trait(ty::TraitPredicate {
391-
trait_ref,
392-
constness: ty::BoundConstness::NotConst,
393-
polarity: _,
394-
}) => {
417+
ty::PredicateKind::Trait(ty::TraitPredicate { trait_ref, constness: _, polarity: _ }) => {
395418
if !matches!(
396419
trait_predicate_kind(tcx, predicate),
397420
Some(TraitSpecializationKind::Marker)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// Tests that a const default trait impl can be specialized by another const
2+
// trait impl and that the specializing impl will be used during const-eval.
3+
4+
// run-pass
5+
6+
#![feature(const_trait_impl)]
7+
#![feature(min_specialization)]
8+
9+
trait Value {
10+
fn value() -> u32;
11+
}
12+
13+
const fn get_value<T: ~const Value>() -> u32 {
14+
T::value()
15+
}
16+
17+
impl<T> const Value for T {
18+
default fn value() -> u32 {
19+
0
20+
}
21+
}
22+
23+
struct FortyTwo;
24+
25+
impl const Value for FortyTwo {
26+
fn value() -> u32 {
27+
42
28+
}
29+
}
30+
31+
const ZERO: u32 = get_value::<()>();
32+
33+
const FORTY_TWO: u32 = get_value::<FortyTwo>();
34+
35+
fn main() {
36+
assert_eq!(ZERO, 0);
37+
assert_eq!(FORTY_TWO, 42);
38+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Tests that a const default trait impl can be specialized by a non-const trait
2+
// impl, but that the specializing impl cannot be used in a const context.
3+
4+
#![feature(const_trait_impl)]
5+
#![feature(min_specialization)]
6+
7+
trait Value {
8+
fn value() -> u32;
9+
}
10+
11+
const fn get_value<T: ~const Value>() -> u32 {
12+
T::value()
13+
//~^ ERROR any use of this value will cause an error [const_err]
14+
//~| WARNING this was previously accepted
15+
}
16+
17+
impl<T> const Value for T {
18+
default fn value() -> u32 {
19+
0
20+
}
21+
}
22+
23+
struct FortyTwo;
24+
25+
impl Value for FortyTwo {
26+
fn value() -> u32 {
27+
println!("You can't do that (constly)");
28+
42
29+
}
30+
}
31+
32+
const ZERO: u32 = get_value::<()>();
33+
34+
const FORTY_TWO: u32 =
35+
get_value::<FortyTwo>(); // This is the line that causes the error, but it gets reported above
36+
37+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
error: any use of this value will cause an error
2+
--> $DIR/const-default-non-const-specialized.rs:12:5
3+
|
4+
LL | T::value()
5+
| ^^^^^^^^^^
6+
| |
7+
| calling non-const function `<FortyTwo as Value>::value`
8+
| inside `get_value::<FortyTwo>` at $DIR/const-default-non-const-specialized.rs:12:5
9+
| inside `FORTY_TWO` at $DIR/const-default-non-const-specialized.rs:35:5
10+
...
11+
LL | const FORTY_TWO: u32 =
12+
| --------------------
13+
|
14+
= note: `#[deny(const_err)]` on by default
15+
= warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
16+
= note: for more information, see issue #71800 <https://github.com/rust-lang/rust/issues/71800>
17+
18+
error: aborting due to previous error
19+
20+
Future incompatibility report: Future breakage diagnostic:
21+
error: any use of this value will cause an error
22+
--> $DIR/const-default-non-const-specialized.rs:12:5
23+
|
24+
LL | T::value()
25+
| ^^^^^^^^^^
26+
| |
27+
| calling non-const function `<FortyTwo as Value>::value`
28+
| inside `get_value::<FortyTwo>` at $DIR/const-default-non-const-specialized.rs:12:5
29+
| inside `FORTY_TWO` at $DIR/const-default-non-const-specialized.rs:35:5
30+
...
31+
LL | const FORTY_TWO: u32 =
32+
| --------------------
33+
|
34+
= note: `#[deny(const_err)]` on by default
35+
= warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
36+
= note: for more information, see issue #71800 <https://github.com/rust-lang/rust/issues/71800>
37+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// check-pass
2+
3+
#![feature(const_trait_impl)]
4+
#![feature(min_specialization)]
5+
6+
trait Foo {
7+
fn foo();
8+
}
9+
10+
impl const Foo for u32 {
11+
default fn foo() {}
12+
}
13+
14+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Tests that `~const` trait bounds can be used to specialize const trait impls.
2+
3+
// check-pass
4+
5+
#![feature(const_trait_impl)]
6+
#![feature(rustc_attrs)]
7+
#![feature(min_specialization)]
8+
9+
#[rustc_specialization_trait]
10+
trait Specialize {}
11+
12+
trait Foo {}
13+
14+
impl<T> const Foo for T {}
15+
16+
impl<T> const Foo for T
17+
where
18+
T: ~const Specialize,
19+
{}
20+
21+
trait Bar {}
22+
23+
impl<T> const Bar for T
24+
where
25+
T: ~const Foo,
26+
{}
27+
28+
impl<T> const Bar for T
29+
where
30+
T: ~const Foo,
31+
T: ~const Specialize,
32+
{}
33+
34+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Tests that `T: ~const Foo` and `T: Foo` are treated as equivalent for the
2+
// purposes of min_specialization.
3+
4+
// check-pass
5+
6+
#![feature(rustc_attrs)]
7+
#![feature(min_specialization)]
8+
#![feature(const_trait_impl)]
9+
10+
#[rustc_specialization_trait]
11+
trait Specialize {}
12+
13+
trait Foo {}
14+
15+
trait Bar {}
16+
17+
impl<T> const Bar for T
18+
where
19+
T: ~const Foo,
20+
{}
21+
22+
impl<T> Bar for T
23+
where
24+
T: Foo,
25+
T: Specialize,
26+
{}
27+
28+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Tests that a non-const default impl can be specialized by a const trait impl,
2+
// but that the default impl cannot be used in a const context.
3+
4+
#![feature(const_trait_impl)]
5+
#![feature(min_specialization)]
6+
7+
trait Value {
8+
fn value() -> u32;
9+
}
10+
11+
const fn get_value<T: ~const Value>() -> u32 {
12+
T::value()
13+
}
14+
15+
impl<T> Value for T {
16+
default fn value() -> u32 {
17+
println!("You can't do that (constly)");
18+
0
19+
}
20+
}
21+
22+
struct FortyTwo;
23+
24+
impl const Value for FortyTwo {
25+
fn value() -> u32 {
26+
42
27+
}
28+
}
29+
30+
const ZERO: u32 = get_value::<()>(); //~ ERROR the trait bound `(): ~const Value` is not satisfied
31+
32+
const FORTY_TWO: u32 = get_value::<FortyTwo>();
33+
34+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
error[E0277]: the trait bound `(): ~const Value` is not satisfied
2+
--> $DIR/non-const-default-const-specialized.rs:30:31
3+
|
4+
LL | const ZERO: u32 = get_value::<()>();
5+
| ^^ the trait `~const Value` is not implemented for `()`
6+
|
7+
note: the trait `Value` is implemented for `()`, but that implementation is not `const`
8+
--> $DIR/non-const-default-const-specialized.rs:30:31
9+
|
10+
LL | const ZERO: u32 = get_value::<()>();
11+
| ^^
12+
note: required by a bound in `get_value`
13+
--> $DIR/non-const-default-const-specialized.rs:11:23
14+
|
15+
LL | const fn get_value<T: ~const Value>() -> u32 {
16+
| ^^^^^^^^^^^^ required by this bound in `get_value`
17+
18+
error: aborting due to previous error
19+
20+
For more information about this error, try `rustc --explain E0277`.

0 commit comments

Comments
 (0)