Skip to content

Commit 795a915

Browse files
Rollup merge of #161386 - bit-aloo:2026-08-17-merge-impls, r=lcnr
Don't merge distinct impl candidates closes: rust-lang/trait-system-refactor-initiative#35 r? lcnr
2 parents 3e13f47 + 0c27f4b commit 795a915

10 files changed

Lines changed: 194 additions & 35 deletions

File tree

‎compiler/rustc_middle/src/ty/context/impl_interner.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -580,6 +580,10 @@ impl<'tcx> Interner for TyCtxt<'tcx> {
580580
self.trait_is_auto(trait_def_id)
581581
}
582582

583+
fn trait_is_marker(self, trait_def_id: DefId) -> bool {
584+
self.trait_def(trait_def_id).is_marker
585+
}
586+
583587
fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
584588
self.trait_is_coinductive(trait_def_id)
585589
}

‎compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1091,8 +1091,12 @@ where
10911091
// we still use modulo regions here. This is fine as specialization currently
10921092
// assumes that specializing impls have to be always applicable, meaning that
10931093
// the only allowed region constraints may be constraints also present on the default impl.
1094+
//
1095+
// If both impls have the same response, dropping victim doesn't change the
1096+
// result. We need to do so here as we don't merge distinct impl candidates.
10941097
if matches!(allow_inference_constraints, AllowInferenceConstraints::Yes)
10951098
|| has_only_region_constraints(c.result)
1099+
|| c.result == candidates[i].result
10961100
{
10971101
if self.cx().impl_specializes(other_def_id, victim_def_id) {
10981102
candidates.remove(i);

‎compiler/rustc_next_trait_solver/src/solve/trait_goals.rs‎

Lines changed: 79 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1556,19 +1556,77 @@ where
15561556
}
15571557
}
15581558

1559+
/// Like `try_merge_candidates`, but returns `None` if there are multiple user-written
1560+
/// impls, or a user-written impl and a builtin impl, in which case we bail with ambiguity.
1561+
///
1562+
/// Candidates with equal responses can still come from conflicting impls, ex - two
1563+
/// overlapping impls which both apply due to impossible where-clauses. We don't want
1564+
/// to merge these. Multiple builtin impls are still merged as usual. This is not
1565+
/// done for marker traits, as their impls are allowed to overlap.
1566+
#[instrument(level = "trace", skip(self), ret)]
1567+
fn try_merge_impl_candidates(
1568+
&mut self,
1569+
trait_def_id: I::TraitId,
1570+
candidates: &[Candidate<I>],
1571+
) -> Option<CanonicalResponse<I>> {
1572+
let is_marker = self.cx().trait_is_marker(trait_def_id);
1573+
let all_builtin = candidates
1574+
.iter()
1575+
.all(|candidate| matches!(candidate.source, CandidateSource::BuiltinImpl(_)));
1576+
1577+
if is_marker || all_builtin {
1578+
self.try_merge_candidates(candidates).map(|(response, _)| response)
1579+
} else if candidates.len() > 1 {
1580+
None
1581+
} else {
1582+
candidates.first().map(|candidate| candidate.result)
1583+
}
1584+
}
1585+
1586+
fn merge_candidates_or_bail_with_ambiguity(
1587+
&mut self,
1588+
candidates: &[Candidate<I>],
1589+
proven_via: TraitGoalProvenVia,
1590+
) -> (CanonicalResponse<I>, Option<TraitGoalProvenVia>) {
1591+
if let Some((response, _)) = self.try_merge_candidates(candidates) {
1592+
(response, Some(proven_via))
1593+
} else {
1594+
(self.bail_with_ambiguity(candidates), None)
1595+
}
1596+
}
1597+
1598+
fn merge_impl_candidates_or_bail_with_ambiguity(
1599+
&mut self,
1600+
trait_def_id: I::TraitId,
1601+
candidates: &[Candidate<I>],
1602+
) -> (CanonicalResponse<I>, Option<TraitGoalProvenVia>) {
1603+
debug_assert!(candidates.iter().all(|c| matches!(
1604+
c.source,
1605+
CandidateSource::Impl(_) | CandidateSource::BuiltinImpl(_)
1606+
)));
1607+
match self.try_merge_impl_candidates(trait_def_id, candidates) {
1608+
Some(response) => (response, Some(TraitGoalProvenVia::Misc)),
1609+
None => (self.bail_with_ambiguity(candidates), None),
1610+
}
1611+
}
1612+
15591613
#[instrument(level = "debug", skip(self), ret)]
15601614
pub(super) fn merge_trait_candidates(
15611615
&mut self,
1562-
candidate_preference_mode: CandidatePreferenceMode,
1616+
trait_def_id: I::TraitId,
15631617
mut candidates: Vec<Candidate<I>>,
15641618
failed_candidate_info: FailedCandidateInfo,
15651619
) -> Result<(CanonicalResponse<I>, Option<TraitGoalProvenVia>), NoSolution> {
1620+
if candidates.is_empty() {
1621+
return Err(NoSolution);
1622+
}
1623+
1624+
let candidate_preference_mode = CandidatePreferenceMode::compute(self.cx(), trait_def_id);
15661625
if self.typing_mode().is_coherence() {
1567-
return if let Some((response, _)) = self.try_merge_candidates(&candidates) {
1568-
Ok((response, Some(TraitGoalProvenVia::Misc)))
1569-
} else {
1570-
self.flounder(&candidates).map(|r| (r, None))
1571-
};
1626+
return Ok(match self.try_merge_impl_candidates(trait_def_id, &candidates) {
1627+
Some(response) => (response, Some(TraitGoalProvenVia::Misc)),
1628+
None => (self.bail_with_ambiguity(&candidates), None),
1629+
});
15721630
}
15731631

15741632
// We prefer trivial builtin candidates, i.e. builtin impls without any
@@ -1595,11 +1653,10 @@ where
15951653
let alias_bounds: Vec<_> = candidates
15961654
.extract_if(.., |c| matches!(c.source, CandidateSource::AliasBound(..)))
15971655
.collect();
1598-
return if let Some((response, _)) = self.try_merge_candidates(&alias_bounds) {
1599-
Ok((response, Some(TraitGoalProvenVia::AliasBound)))
1600-
} else {
1601-
Ok((self.bail_with_ambiguity(&alias_bounds), None))
1602-
};
1656+
return Ok(self.merge_candidates_or_bail_with_ambiguity(
1657+
&alias_bounds,
1658+
TraitGoalProvenVia::AliasBound,
1659+
));
16031660
}
16041661

16051662
// If there are non-global where-bounds, prefer where-bounds
@@ -1651,11 +1708,10 @@ where
16511708
let alias_bounds: Vec<_> = candidates
16521709
.extract_if(.., |c| matches!(c.source, CandidateSource::AliasBound(_)))
16531710
.collect();
1654-
return if let Some((response, _)) = self.try_merge_candidates(&alias_bounds) {
1655-
Ok((response, Some(TraitGoalProvenVia::AliasBound)))
1656-
} else {
1657-
Ok((self.bail_with_ambiguity(&alias_bounds), None))
1658-
};
1711+
return Ok(self.merge_candidates_or_bail_with_ambiguity(
1712+
&alias_bounds,
1713+
TraitGoalProvenVia::AliasBound,
1714+
));
16591715
}
16601716

16611717
self.filter_specialized_impls(AllowInferenceConstraints::No, &mut candidates);
@@ -1665,21 +1721,16 @@ where
16651721
// is still reported as being proven-via the param-env so that rigid projections
16661722
// operate correctly. Otherwise, drop all global where-bounds before merging the
16671723
// remaining candidates.
1668-
let proven_via = if candidates
1724+
let only_global_where_bounds = candidates
16691725
.iter()
1670-
.all(|c| matches!(c.source, CandidateSource::ParamEnv(ParamEnvSource::Global)))
1671-
{
1672-
TraitGoalProvenVia::ParamEnv
1726+
.all(|c| matches!(c.source, CandidateSource::ParamEnv(ParamEnvSource::Global)));
1727+
if only_global_where_bounds {
1728+
Ok(self
1729+
.merge_candidates_or_bail_with_ambiguity(&candidates, TraitGoalProvenVia::ParamEnv))
16731730
} else {
16741731
candidates
16751732
.retain(|c| !matches!(c.source, CandidateSource::ParamEnv(ParamEnvSource::Global)));
1676-
TraitGoalProvenVia::Misc
1677-
};
1678-
1679-
if let Some((response, _)) = self.try_merge_candidates(&candidates) {
1680-
Ok((response, Some(proven_via)))
1681-
} else {
1682-
self.flounder(&candidates).map(|r| (r, None))
1733+
Ok(self.merge_impl_candidates_or_bail_with_ambiguity(trait_def_id, &candidates))
16831734
}
16841735
}
16851736

@@ -1691,9 +1742,7 @@ where
16911742
{
16921743
let (candidates, failed_candidate_info) =
16931744
self.assemble_and_evaluate_candidates(goal, AssembleCandidatesFrom::All)?;
1694-
let candidate_preference_mode =
1695-
CandidatePreferenceMode::compute(self.cx(), goal.predicate.def_id());
1696-
self.merge_trait_candidates(candidate_preference_mode, candidates, failed_candidate_info)
1745+
self.merge_trait_candidates(goal.predicate.def_id(), candidates, failed_candidate_info)
16971746
.map_err(Into::into)
16981747
}
16991748

‎compiler/rustc_type_ir/src/interner.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -491,6 +491,8 @@ pub trait Interner:
491491

492492
fn trait_is_auto(self, trait_def_id: Self::TraitId) -> bool;
493493

494+
fn trait_is_marker(self, trait_def_id: Self::TraitId) -> bool;
495+
494496
fn trait_is_coinductive(self, trait_def_id: Self::TraitId) -> bool;
495497

496498
fn trait_is_alias(self, trait_def_id: Self::TraitId) -> bool;

‎tests/ui/coherence/coherence-inherited-assoc-ty-cycle-err.stderr‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,12 @@ error[E0391]: cycle detected when building specialization graph of trait `Trait`
44
LL | trait Trait<T> { type Assoc; }
55
| ^^^^^^^^^^^^^^
66
|
7-
= note: ...which immediately requires building specialization graph of trait `Trait` again
7+
note: ...which requires computing whether impls specialize one another...
8+
--> $DIR/coherence-inherited-assoc-ty-cycle-err.rs:17:1
9+
|
10+
LL | impl<T> Trait<T> for String {
11+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
12+
= note: ...which again requires building specialization graph of trait `Trait`, completing the cycle
813
= note: cycle used when coherence checking all impls of trait `Trait`
914
= note: for more information, see <https://rustc-dev-guide.rust-lang.org/overview.html#queries> and <https://rustc-dev-guide.rust-lang.org/query.html>
1015

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
error[E0283]: type annotations needed: cannot satisfy `Option<T>: Overlap`
2+
--> $DIR/ambiguous-impl-in-resolve.rs:17:6
3+
|
4+
LL | <Option<T> as Overlap>::f();
5+
| ^^^^^^^^^
6+
|
7+
note: multiple `impl`s satisfying `Option<T>: Overlap` found
8+
--> $DIR/ambiguous-impl-in-resolve.rs:10:1
9+
|
10+
LL | impl<T> Overlap for Option<T> where Self: Clone, { fn f() {} }
11+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
12+
LL | impl<T> Overlap for Option<T> where Self: Local, { fn f() {} }
13+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
14+
15+
error: aborting due to 1 previous error
16+
17+
For more information about this error, try `rustc --explain E0283`.
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
error[E0283]: type annotations needed: cannot satisfy `Option<T>: Overlap`
2+
--> $DIR/ambiguous-impl-in-resolve.rs:17:6
3+
|
4+
LL | <Option<T> as Overlap>::f();
5+
| ^^^^^^^^^
6+
|
7+
note: multiple `impl`s satisfying `Option<T>: Overlap` found
8+
--> $DIR/ambiguous-impl-in-resolve.rs:10:1
9+
|
10+
LL | impl<T> Overlap for Option<T> where Self: Clone, { fn f() {} }
11+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
12+
LL | impl<T> Overlap for Option<T> where Self: Local, { fn f() {} }
13+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
14+
15+
error: aborting due to 1 previous error
16+
17+
For more information about this error, try `rustc --explain E0283`.

‎tests/ui/traits/next-solver/ambiguous-impl-in-resolve.rs‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
1-
//@ check-pass
2-
//@ compile-flags: -Znext-solver
1+
//@ revisions: old next
2+
//@[next] compile-flags: -Znext-solver
3+
4+
// Impossible where-clauses can cause multiple overlapping impls to apply
5+
// with the same constraints.
36

47
trait Local {}
58

@@ -12,6 +15,7 @@ where
1215
Option<T>: Clone + Local,
1316
{
1417
<Option<T> as Overlap>::f();
18+
//~^ ERROR type annotations needed
1519
}
1620

1721
fn main() {}

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ impl<'a, 'b, T> Trait<'a, 'b> for A<T> where B<T>: Trait<'a, 'b> {}
1919
// not have a cycle with `A<T>`. This candidate never applies because of
2020
// the `A<T>: NotImplemented` bound.
2121
impl<'a, 'b, T> Trait<'a, 'b> for B<T>
22+
//~^ ERROR: type annotations needed: cannot satisfy `B<T>: Trait<'a, 'b>` [E0283]
2223
where
2324
A<T>: Trait<'a, 'b>,
2425
A<T>: NotImplemented,
@@ -33,6 +34,7 @@ where
3334
// regions in the `A<T>: Trait<'a, 'b>` where-bound. As both the impl above
3435
// and the impl below now apply with some constraints, we failed with ambiguity.
3536
impl<'a, 'b, T> Trait<'a, 'b> for B<T>
37+
//~^ ERROR: type annotations needed: cannot satisfy `B<T>: Trait<'a, 'b>` [E0283]
3638
where
3739
A<T>: NotImplemented,
3840
{}
Lines changed: 57 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,65 @@
1+
error[E0283]: type annotations needed: cannot satisfy `B<T>: Trait<'a, 'b>`
2+
--> $DIR/fixpoint-rerun-all-cycle-heads.rs:21:35
3+
|
4+
LL | impl<'a, 'b, T> Trait<'a, 'b> for B<T>
5+
| ^^^^
6+
|
7+
note: multiple `impl`s satisfying `B<T>: Trait<'a, 'b>` found
8+
--> $DIR/fixpoint-rerun-all-cycle-heads.rs:21:1
9+
|
10+
LL | / impl<'a, 'b, T> Trait<'a, 'b> for B<T>
11+
LL | |
12+
LL | | where
13+
LL | | A<T>: Trait<'a, 'b>,
14+
LL | | A<T>: NotImplemented,
15+
| |_________________________^
16+
...
17+
LL | / impl<'a, 'b, T> Trait<'a, 'b> for B<T>
18+
LL | |
19+
LL | | where
20+
LL | | A<T>: NotImplemented,
21+
| |_________________________^
22+
...
23+
LL | / impl<'a, T> Trait<'a, 'static> for B<T>
24+
LL | | where
25+
LL | | C<T>: Trait<'a, 'a>,
26+
| |________________________^
27+
28+
error[E0283]: type annotations needed: cannot satisfy `B<T>: Trait<'a, 'b>`
29+
--> $DIR/fixpoint-rerun-all-cycle-heads.rs:36:35
30+
|
31+
LL | impl<'a, 'b, T> Trait<'a, 'b> for B<T>
32+
| ^^^^
33+
|
34+
note: multiple `impl`s satisfying `B<T>: Trait<'a, 'b>` found
35+
--> $DIR/fixpoint-rerun-all-cycle-heads.rs:21:1
36+
|
37+
LL | / impl<'a, 'b, T> Trait<'a, 'b> for B<T>
38+
LL | |
39+
LL | | where
40+
LL | | A<T>: Trait<'a, 'b>,
41+
LL | | A<T>: NotImplemented,
42+
| |_________________________^
43+
...
44+
LL | / impl<'a, 'b, T> Trait<'a, 'b> for B<T>
45+
LL | |
46+
LL | | where
47+
LL | | A<T>: NotImplemented,
48+
| |_________________________^
49+
...
50+
LL | / impl<'a, T> Trait<'a, 'static> for B<T>
51+
LL | | where
52+
LL | | C<T>: Trait<'a, 'a>,
53+
| |________________________^
54+
155
error: lifetime may not live long enough
2-
--> $DIR/fixpoint-rerun-all-cycle-heads.rs:60:5
56+
--> $DIR/fixpoint-rerun-all-cycle-heads.rs:62:5
357
|
458
LL | fn check<'a, T>() {
559
| -- lifetime `'a` defined here
660
LL | impls_trait::<'a, 'static, A<T>>();
761
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ requires that `'a` must outlive `'static`
862

9-
error: aborting due to 1 previous error
63+
error: aborting due to 3 previous errors
1064

65+
For more information about this error, try `rustc --explain E0283`.

0 commit comments

Comments
 (0)