1
Fork 0

Rollup merge of #134008 - jswrenn:unsafe-fields-copy, r=compiler-errors

Make `Copy` unsafe to implement for ADTs with `unsafe` fields

As a rule, the application of `unsafe` to a declaration requires that use-sites of that declaration also entail `unsafe`. For example, a field declared `unsafe` may only be read in the lexical context of an `unsafe` block.

For nearly all safe traits, the safety obligations of fields are explicitly discharged when they are mentioned in method definitions. For example, idiomatically implementing `Clone` (a safe trait) for a type with unsafe fields will require `unsafe` to clone those fields.

Prior to this commit, `Copy` violated this rule. The trait is marked safe, and although it has no explicit methods, its implementation permits reads of `Self`.

This commit resolves this by making `Copy` conditionally safe to implement. It remains safe to implement for ADTs without unsafe fields, but unsafe to implement for ADTs with unsafe fields.

Tracking: #132922

r? ```@compiler-errors```
This commit is contained in:
León Orell Valerian Liehr 2024-12-10 13:51:10 +01:00 committed by GitHub
commit 3eaa785daa
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 164 additions and 52 deletions

View file

@ -625,6 +625,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingCopyImplementations {
cx.param_env,
ty,
traits::ObligationCause::misc(item.span, item.owner_id.def_id),
hir::Safety::Safe,
)
.is_ok()
{