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

Commit 8a84d47

Browse files
committed
Auto merge of rust-lang#138176 - compiler-errors:rigid-sized-obl, r=<try>
Prefer built-in sized impls (and only sized impls) for rigid types always This PR changes the confirmation of `Sized` obligations to unconditionally prefer the built-in obligation, even if it has nested obligations. In the old solver, we register many builtin candidates with the `BuiltinCandidate { has_nested: bool }` candidate kind. The precedence this candidate takes over other candidates is based on the `has_nested` field. If it's false, then we prefer it over param-env candidates: https://github.com/rust-lang/rust/blob/2b4694a69804f89ff9d47d1a427f72c876f7f44c/compiler/rustc_trait_selection/src/traits/select/mod.rs#L1804-L1815 Otherwise we prefer param-env candidates over it: https://github.com/rust-lang/rust/blob/2b4694a69804f89ff9d47d1a427f72c876f7f44c/compiler/rustc_trait_selection/src/traits/select/mod.rs#L1847-L1866 I assume that the motivation for this behavior is to prefer built-in candidates if they have no nested obligations, but we can't as confidently prefer built-in candidates when they have where-clauses since we have no guarantee that the nested obligations for the built-in candidate are actually satisfyable (especially considering regions). However, for `Sized` candidates in particular, unlike the example above we never end up bottoming-out in a user-written impl, since *all* `Sized` impls are built-in. Thus, we don't have this problem, and preferring param-env candidates actually ends up leading to detrimental inference guidance, like: ```rust fn hello<T>() where (T,): Sized { let x: (_,) = Default::default(); // ^^ The `Sized` obligation on the variable infers `_ = T`. let x: (i32,) = x; // We error here, both a type mismatch and also b/c `T: Default` doesn't hold. } ``` Therefore this PR adjusts the candidate precedence of `Sized` obligations by making them a distinct candidate kind and unconditionally preferring them over all other candidate kinds. r? lcnr
2 parents 2b285cd + ee3359a commit 8a84d47

File tree

4 files changed

+43
-16
lines changed

4 files changed

+43
-16
lines changed

compiler/rustc_middle/src/traits/select.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,10 +95,16 @@ pub type EvaluationCache<'tcx, ENV> = Cache<(ENV, ty::PolyTraitPredicate<'tcx>),
9595
/// parameter environment.
9696
#[derive(PartialEq, Eq, Debug, Clone, TypeVisitable)]
9797
pub enum SelectionCandidate<'tcx> {
98+
/// A built-in implementation for the `Sized` trait. This is preferred
99+
/// over all other candidates.
100+
SizedCandidate {
101+
has_nested: bool,
102+
},
103+
98104
/// A builtin implementation for some specific traits, used in cases
99105
/// where we cannot rely an ordinary library implementations.
100106
///
101-
/// The most notable examples are `sized`, `Copy` and `Clone`. This is also
107+
/// The most notable examples are `Copy` and `Clone`. This is also
102108
/// used for the `DiscriminantKind` and `Pointee` trait, both of which have
103109
/// an associated type.
104110
BuiltinCandidate {

compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -86,10 +86,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
8686
// `Pointee` is automatically implemented for every type.
8787
candidates.vec.push(BuiltinCandidate { has_nested: false });
8888
} else if tcx.is_lang_item(def_id, LangItem::Sized) {
89-
// Sized is never implementable by end-users, it is
90-
// always automatically computed.
91-
let sized_conditions = self.sized_conditions(obligation);
92-
self.assemble_builtin_bound_candidates(sized_conditions, &mut candidates);
89+
self.assemble_builtin_sized_candidate(obligation, &mut candidates);
9390
} else if tcx.is_lang_item(def_id, LangItem::Unsize) {
9491
self.assemble_candidates_for_unsizing(obligation, &mut candidates);
9592
} else if tcx.is_lang_item(def_id, LangItem::Destruct) {
@@ -1059,6 +1056,27 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
10591056
/// Assembles the trait which are built-in to the language itself:
10601057
/// `Copy`, `Clone` and `Sized`.
10611058
#[instrument(level = "debug", skip(self, candidates))]
1059+
fn assemble_builtin_sized_candidate(
1060+
&mut self,
1061+
obligation: &PolyTraitObligation<'tcx>,
1062+
candidates: &mut SelectionCandidateSet<'tcx>,
1063+
) {
1064+
match self.sized_conditions(obligation) {
1065+
BuiltinImplConditions::Where(nested) => {
1066+
candidates
1067+
.vec
1068+
.push(SizedCandidate { has_nested: !nested.skip_binder().is_empty() });
1069+
}
1070+
BuiltinImplConditions::None => {}
1071+
BuiltinImplConditions::Ambiguous => {
1072+
candidates.ambiguous = true;
1073+
}
1074+
}
1075+
}
1076+
1077+
/// Assembles the trait which are built-in to the language itself:
1078+
/// e.g. `Copy` and `Clone`.
1079+
#[instrument(level = "debug", skip(self, candidates))]
10621080
fn assemble_builtin_bound_candidates(
10631081
&mut self,
10641082
conditions: BuiltinImplConditions<'tcx>,

compiler/rustc_trait_selection/src/traits/select/confirmation.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,11 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
4040
candidate: SelectionCandidate<'tcx>,
4141
) -> Result<Selection<'tcx>, SelectionError<'tcx>> {
4242
let mut impl_src = match candidate {
43+
SizedCandidate { has_nested } => {
44+
let data = self.confirm_builtin_candidate(obligation, has_nested);
45+
ImplSource::Builtin(BuiltinImplSource::Misc, data)
46+
}
47+
4348
BuiltinCandidate { has_nested } => {
4449
let data = self.confirm_builtin_candidate(obligation, has_nested);
4550
ImplSource::Builtin(BuiltinImplSource::Misc, data)

compiler/rustc_trait_selection/src/traits/select/mod.rs

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1801,17 +1801,14 @@ impl<'tcx> SelectionContext<'_, 'tcx> {
18011801
return Some(candidates.pop().unwrap().candidate);
18021802
}
18031803

1804-
// We prefer trivial builtin candidates, i.e. builtin impls without any nested
1805-
// requirements, over all others. This is a fix for #53123 and prevents winnowing
1806-
// from accidentally extending the lifetime of a variable.
1807-
let mut trivial_builtin = candidates
1808-
.iter()
1809-
.filter(|c| matches!(c.candidate, BuiltinCandidate { has_nested: false }));
1810-
if let Some(_trivial) = trivial_builtin.next() {
1811-
// There should only ever be a single trivial builtin candidate
1804+
// We prefer `Sized` candidates over everything.
1805+
let mut sized_candidates =
1806+
candidates.iter().filter(|c| matches!(c.candidate, SizedCandidate { has_nested: _ }));
1807+
if let Some(sized_candidate) = sized_candidates.next() {
1808+
// There should only ever be a single sized candidate
18121809
// as they would otherwise overlap.
1813-
debug_assert_eq!(trivial_builtin.next(), None);
1814-
return Some(BuiltinCandidate { has_nested: false });
1810+
debug_assert_eq!(sized_candidates.next(), None);
1811+
return Some(sized_candidate.candidate.clone());
18151812
}
18161813

18171814
// Before we consider where-bounds, we have to deduplicate them here and also
@@ -1940,7 +1937,8 @@ impl<'tcx> SelectionContext<'_, 'tcx> {
19401937
// Don't use impl candidates which overlap with other candidates.
19411938
// This should pretty much only ever happen with malformed impls.
19421939
if candidates.iter().all(|c| match c.candidate {
1943-
BuiltinCandidate { has_nested: _ }
1940+
SizedCandidate { has_nested: _ }
1941+
| BuiltinCandidate { has_nested: _ }
19441942
| TransmutabilityCandidate
19451943
| AutoImplCandidate
19461944
| ClosureCandidate { .. }

0 commit comments

Comments
 (0)