Skip to content

Commit 36a5590

Browse files
committed
hide impls if trait bound is proven from env
1 parent a913c24 commit 36a5590

18 files changed

+367
-122
lines changed

compiler/rustc_trait_selection/src/solve/assembly/mod.rs

+62-40
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use rustc_infer::traits::query::NoSolution;
88
use rustc_infer::traits::Reveal;
99
use rustc_middle::traits::solve::inspect::ProbeKind;
1010
use rustc_middle::traits::solve::{
11-
CandidateSource, CanonicalResponse, Certainty, Goal, QueryResult,
11+
CandidateSource, CanonicalResponse, Certainty, Goal, MaybeCause, QueryResult,
1212
};
1313
use rustc_middle::traits::BuiltinImplSource;
1414
use rustc_middle::ty::fast_reject::{SimplifiedType, TreatParams};
@@ -276,25 +276,16 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
276276
&mut self,
277277
goal: Goal<'tcx, G>,
278278
) -> Vec<Candidate<'tcx>> {
279-
let dummy_candidate = |this: &mut EvalCtxt<'_, 'tcx>, certainty| {
280-
let source = CandidateSource::BuiltinImpl(BuiltinImplSource::Misc);
281-
let result = this.evaluate_added_goals_and_make_canonical_response(certainty).unwrap();
282-
let mut dummy_probe = this.inspect.new_probe();
283-
dummy_probe.probe_kind(ProbeKind::TraitCandidate { source, result: Ok(result) });
284-
this.inspect.finish_probe(dummy_probe);
285-
vec![Candidate { source, result }]
286-
};
287-
288279
let Some(normalized_self_ty) =
289280
self.try_normalize_ty(goal.param_env, goal.predicate.self_ty())
290281
else {
291282
debug!("overflow while evaluating self type");
292-
return dummy_candidate(self, Certainty::OVERFLOW);
283+
return self.forced_ambiguity(MaybeCause::Overflow);
293284
};
294285

295286
if normalized_self_ty.is_ty_var() {
296287
debug!("self type has been normalized to infer");
297-
return dummy_candidate(self, Certainty::AMBIGUOUS);
288+
return self.forced_ambiguity(MaybeCause::Ambiguity);
298289
}
299290

300291
let goal =
@@ -317,9 +308,21 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
317308

318309
self.assemble_coherence_unknowable_candidates(goal, &mut candidates);
319310

311+
self.discard_impls_shadowed_by_env(goal, &mut candidates);
312+
320313
candidates
321314
}
322315

316+
fn forced_ambiguity(&mut self, cause: MaybeCause) -> Vec<Candidate<'tcx>> {
317+
let source = CandidateSource::BuiltinImpl(BuiltinImplSource::Misc);
318+
let certainty = Certainty::Maybe(cause);
319+
let result = self.evaluate_added_goals_and_make_canonical_response(certainty).unwrap();
320+
let mut dummy_probe = self.inspect.new_probe();
321+
dummy_probe.probe_kind(ProbeKind::TraitCandidate { source, result: Ok(result) });
322+
self.inspect.finish_probe(dummy_probe);
323+
vec![Candidate { source, result }]
324+
}
325+
323326
#[instrument(level = "debug", skip_all)]
324327
fn assemble_non_blanket_impl_candidates<G: GoalKind<'tcx>>(
325328
&mut self,
@@ -826,6 +829,51 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
826829
}
827830
}
828831

832+
/// If there's a where-bound for the current goal, do not use any impl candidates
833+
/// to prove the current goal. Most importantly, if there is a where-bound which does
834+
/// not specify any associated types, we do not allow normalizing the associated type
835+
/// by using an impl, even if it would apply.
836+
///
837+
/// https://github.com/rust-lang/trait-system-refactor-initiative/issues/76
838+
// FIXME(@lcnr): The current structure here makes me unhappy and feels ugly. idk how
839+
// to improve this however. However, this should make it fairly straightforward to refine
840+
// the filtering going forward, so it seems alright-ish for now.
841+
fn discard_impls_shadowed_by_env<G: GoalKind<'tcx>>(
842+
&mut self,
843+
goal: Goal<'tcx, G>,
844+
candidates: &mut Vec<Candidate<'tcx>>,
845+
) {
846+
let tcx = self.tcx();
847+
let trait_goal: Goal<'tcx, ty::TraitPredicate<'tcx>> =
848+
goal.with(tcx, goal.predicate.trait_ref(tcx));
849+
let mut trait_candidates_from_env = Vec::new();
850+
self.assemble_param_env_candidates(trait_goal, &mut trait_candidates_from_env);
851+
self.assemble_alias_bound_candidates(trait_goal, &mut trait_candidates_from_env);
852+
if !trait_candidates_from_env.is_empty() {
853+
let trait_env_result = self.merge_candidates(trait_candidates_from_env);
854+
match trait_env_result.unwrap().value.certainty {
855+
// If proving the trait goal succeeds by using the env,
856+
// we freely drop all impl candidates.
857+
//
858+
// FIXME(@lcnr): It feels like this could easily hide
859+
// a forced ambiguity candidate added earlier.
860+
// This feels dangerous.
861+
Certainty::Yes => {
862+
candidates.retain(|c| match c.source {
863+
CandidateSource::Impl(_) | CandidateSource::BuiltinImpl(_) => false,
864+
CandidateSource::ParamEnv(_) | CandidateSource::AliasBound => true,
865+
});
866+
}
867+
// If it is still ambiguous we instead just force the whole goal
868+
// to be ambig and wait for inference constraints. See
869+
// tests/ui/traits/next-solver/env-shadows-impls/ambig-env-no-shadow.rs
870+
Certainty::Maybe(cause) => {
871+
*candidates = self.forced_ambiguity(cause);
872+
}
873+
}
874+
}
875+
}
876+
829877
/// If there are multiple ways to prove a trait or projection goal, we have
830878
/// to somehow try to merge the candidates into one. If that fails, we return
831879
/// ambiguity.
@@ -838,34 +886,8 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
838886
let responses = candidates.iter().map(|c| c.result).collect::<Vec<_>>();
839887
if let Some(result) = self.try_merge_responses(&responses) {
840888
return Ok(result);
889+
} else {
890+
self.flounder(&responses)
841891
}
842-
843-
// We then check whether we should prioritize `ParamEnv` candidates.
844-
//
845-
// Doing so is incomplete and would therefore be unsound during coherence.
846-
match self.solver_mode() {
847-
SolverMode::Coherence => (),
848-
// Prioritize `ParamEnv` candidates only if they do not guide inference.
849-
//
850-
// This is still incomplete as we may add incorrect region bounds.
851-
SolverMode::Normal => {
852-
let param_env_responses = candidates
853-
.iter()
854-
.filter(|c| {
855-
matches!(
856-
c.source,
857-
CandidateSource::ParamEnv(_) | CandidateSource::AliasBound
858-
)
859-
})
860-
.map(|c| c.result)
861-
.collect::<Vec<_>>();
862-
if let Some(result) = self.try_merge_responses(&param_env_responses) {
863-
// We strongly prefer alias and param-env bounds here, even if they affect inference.
864-
// See https://github.com/rust-lang/trait-system-refactor-initiative/issues/11.
865-
return Ok(result);
866-
}
867-
}
868-
}
869-
self.flounder(&responses)
870892
}
871893
}

tests/ui/traits/next-solver/cycles/fixpoint-rerun-all-cycle-heads.rs

+12
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,18 @@ where
2424
{
2525
}
2626

27+
// HACK: This impls is necessary so that the impl above is well-formed.
28+
//
29+
// When checking that the impl above is well-formed we check `B<T>: Trait<'a, 'b>`
30+
// with the where clauses `A<T>: Trait<'a, 'b>` and `A<T> NotImplemented`. Trying to
31+
// use the impl itself to prove that adds region constraints as we uniquified the
32+
// regions in the `A<T>: Trait<'a, 'b>` where-bound. As both the impl above
33+
// and the impl below now apply with some constraints, we failed with ambiguity.
34+
impl<'a, 'b, T: ?Sized> Trait<'a, 'b> for B<T>
35+
where
36+
A<T>: NotImplemented,
37+
{}
38+
2739
// This impl directly requires 'b to be equal to 'static.
2840
//
2941
// Because of the coinductive cycle through `C<T>` it also requires

tests/ui/traits/next-solver/cycles/fixpoint-rerun-all-cycle-heads.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
error: lifetime may not live long enough
2-
--> $DIR/fixpoint-rerun-all-cycle-heads.rs:47:5
2+
--> $DIR/fixpoint-rerun-all-cycle-heads.rs:59:5
33
|
44
LL | fn check<'a, T: ?Sized>() {
55
| -- lifetime `'a` defined here
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// compile-flags: -Znext-solver
2+
// check-pass
3+
4+
trait Trait<T>: Sized {
5+
type Assoc: From<Self>;
6+
}
7+
8+
impl<T, U> Trait<U> for T {
9+
type Assoc = T;
10+
}
11+
12+
fn mk_assoc<T: Trait<U>, U>(t: T, _: U) -> <T as Trait<U>>::Assoc {
13+
t.into()
14+
}
15+
16+
fn generic<T>(t: T) -> T
17+
where
18+
T: Trait<u32>,
19+
T: Trait<i16>,
20+
{
21+
let u = Default::default();
22+
let ret: T = mk_assoc(t, u);
23+
let _: u8 = u;
24+
ret
25+
}
26+
27+
fn main() {
28+
assert_eq!(generic(1), 1);
29+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// compile-flags: -Znext-solver
2+
// check-pass
3+
4+
// Normalizing `<T as Trait>::TraitAssoc` in the elaborated environment
5+
// `[T: Trait, T: Super, <T as Super>::SuperAssoc = <T as Trait>::TraitAssoc]`
6+
// has a single impl candidate, which uses the environment to
7+
// normalize `<T as Trait>::TraitAssoc` to itself. We avoid this overflow
8+
// by discarding impl candidates the trait bound is proven by a where-clause.
9+
10+
// https://github.com/rust-lang/trait-system-refactor-initiative/issues/76
11+
trait Super {
12+
type SuperAssoc;
13+
}
14+
15+
trait Trait: Super<SuperAssoc = Self::TraitAssoc> {
16+
type TraitAssoc;
17+
}
18+
19+
impl<T, U> Trait for T
20+
where
21+
T: Super<SuperAssoc = U>,
22+
{
23+
type TraitAssoc = U;
24+
}
25+
26+
fn overflow<T: Trait>() {
27+
let x: <T as Trait>::TraitAssoc;
28+
}
29+
30+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// revisions: next current
2+
//[next] compile-flags: -Znext-solver
3+
// check-pass
4+
5+
#![allow(warnings)]
6+
trait Trait<U> {
7+
type Assoc;
8+
}
9+
10+
impl<T> Trait<u64> for T {
11+
type Assoc = T;
12+
}
13+
14+
fn lazy_init<T: Trait<U>, U>() -> (T, <T as Trait<U>>::Assoc) {
15+
todo!()
16+
}
17+
18+
fn foo<T: Trait<u32, Assoc = T>>(x: T) {
19+
// When considering impl candidates to be equally valid as env candidates
20+
// this ends up being ambiguous as `U` can be both `u32´ and `u64` here.
21+
//
22+
// This is acceptable breakage but we should still note that it's
23+
// theoretically breaking.
24+
let (delayed, mut proj) = lazy_init::<_, _>();
25+
proj = x;
26+
let _: T = delayed;
27+
}
28+
29+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// compile-flags: -Znext-solver
2+
// check-pass
3+
4+
// If we normalize using the impl here the constraints from normalization and
5+
// trait goals can differ. This is especially bad if normalization results
6+
// in stronger constraints.
7+
trait Trait<'a> {
8+
type Assoc;
9+
}
10+
11+
impl<T> Trait<'static> for T {
12+
type Assoc = ();
13+
}
14+
15+
// normalizing requires `'a == 'static`, the trait bound does not.
16+
fn foo<'a, T: Trait<'a>>(_: T::Assoc) {}
17+
18+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// compile-flags: -Znext-solver
2+
3+
// Checks whether the new solver is smart enough to infer `?0 = U` when solving:
4+
// `normalizes-to(<Vec<?0> as Trait>::Assoc, u8)`
5+
// with `normalizes-to(<Vec<U> as Trait>::Assoc, u8)` in the paramenv even when
6+
// there is a separate `Vec<T>: Trait` bound in the paramenv.
7+
//
8+
// We currently intentionally do not guide inference this way.
9+
10+
trait Trait {
11+
type Assoc;
12+
}
13+
14+
fn foo<T: Trait<Assoc = u8>>(x: T) {}
15+
16+
fn unconstrained<T>() -> Vec<T> {
17+
todo!()
18+
}
19+
20+
fn bar<T, U>()
21+
where
22+
Vec<T>: Trait,
23+
Vec<U>: Trait<Assoc = u8>,
24+
{
25+
foo(unconstrained())
26+
//~^ ERROR type annotations needed
27+
}
28+
29+
fn main() {}

tests/ui/traits/next-solver/normalizes_to_ignores_unnormalizable_candidate.self_infer.stderr tests/ui/traits/next-solver/env-shadows-impls/normalizes_to_ignores_unnormalizable_candidate.stderr

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,21 @@
11
error[E0283]: type annotations needed
2-
--> $DIR/normalizes_to_ignores_unnormalizable_candidate.rs:36:5
2+
--> $DIR/normalizes_to_ignores_unnormalizable_candidate.rs:25:5
33
|
44
LL | foo(unconstrained())
55
| ^^^ --------------- type must be known at this point
66
| |
77
| cannot infer type of the type parameter `T` declared on the function `foo`
88
|
9-
= note: cannot satisfy `_: Trait`
9+
= note: cannot satisfy `Vec<_>: Trait`
1010
note: required by a bound in `foo`
11-
--> $DIR/normalizes_to_ignores_unnormalizable_candidate.rs:19:11
11+
--> $DIR/normalizes_to_ignores_unnormalizable_candidate.rs:14:11
1212
|
1313
LL | fn foo<T: Trait<Assoc = u8>>(x: T) {}
1414
| ^^^^^^^^^^^^^^^^^ required by this bound in `foo`
1515
help: consider specifying the generic argument
1616
|
17-
LL | foo::<T>(unconstrained())
18-
| +++++
17+
LL | foo::<Vec<T>>(unconstrained())
18+
| ++++++++++
1919

2020
error: aborting due to 1 previous error
2121

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// compile-flags: -Znext-solver
2+
3+
trait Foo {
4+
type Assoc;
5+
}
6+
7+
trait Bar {}
8+
9+
impl<T> Foo for T {
10+
type Assoc = i32;
11+
}
12+
13+
impl<T> Bar for T where T: Foo<Assoc = i32> {}
14+
15+
fn require_bar<T: Bar>() {}
16+
17+
fn foo<T: Foo>() {
18+
// Unlike the classic solver, the new solver previous projected
19+
// `<T as Foo>::Assoc = _` down to `i32` even though there's a param-env
20+
// candidate here, since we don't assemble any param-env projection
21+
// candidates for `T: Foo` alone.
22+
//
23+
// However, allowing impl candidates shadowed by env candidates results
24+
// in multiple issues, so we explicitly hide them, e.g.
25+
//
26+
// https://github.com/rust-lang/trait-system-refactor-initiative/issues/76
27+
require_bar::<T>();
28+
//~^ ERROR the trait bound `T: Bar` is not satisfied
29+
}
30+
31+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
error[E0277]: the trait bound `T: Bar` is not satisfied
2+
--> $DIR/param-candidate-shadows-project.rs:27:19
3+
|
4+
LL | require_bar::<T>();
5+
| ^ the trait `Bar` is not implemented for `T`
6+
|
7+
note: required by a bound in `require_bar`
8+
--> $DIR/param-candidate-shadows-project.rs:15:19
9+
|
10+
LL | fn require_bar<T: Bar>() {}
11+
| ^^^ required by this bound in `require_bar`
12+
help: consider further restricting this bound
13+
|
14+
LL | fn foo<T: Foo + Bar>() {
15+
| +++++
16+
17+
error: aborting due to 1 previous error
18+
19+
For more information about this error, try `rustc --explain E0277`.

0 commit comments

Comments
 (0)