Skip to content

Commit 3eaa785

Browse files
authored
Rollup merge of rust-lang#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: rust-lang#132922 r? ```@compiler-errors```
2 parents ceaca6b + 3ce35a4 commit 3eaa785

File tree

12 files changed

+166
-54
lines changed

12 files changed

+166
-54
lines changed

compiler/rustc_codegen_cranelift/example/mini_core.rs

+20-20
Original file line numberDiff line numberDiff line change
@@ -55,26 +55,26 @@ impl<T: ?Sized> LegacyReceiver for &mut T {}
5555
impl<T: ?Sized> LegacyReceiver for Box<T> {}
5656

5757
#[lang = "copy"]
58-
pub unsafe trait Copy {}
59-
60-
unsafe impl Copy for bool {}
61-
unsafe impl Copy for u8 {}
62-
unsafe impl Copy for u16 {}
63-
unsafe impl Copy for u32 {}
64-
unsafe impl Copy for u64 {}
65-
unsafe impl Copy for u128 {}
66-
unsafe impl Copy for usize {}
67-
unsafe impl Copy for i8 {}
68-
unsafe impl Copy for i16 {}
69-
unsafe impl Copy for i32 {}
70-
unsafe impl Copy for isize {}
71-
unsafe impl Copy for f32 {}
72-
unsafe impl Copy for f64 {}
73-
unsafe impl Copy for char {}
74-
unsafe impl<'a, T: ?Sized> Copy for &'a T {}
75-
unsafe impl<T: ?Sized> Copy for *const T {}
76-
unsafe impl<T: ?Sized> Copy for *mut T {}
77-
unsafe impl<T: Copy> Copy for Option<T> {}
58+
pub trait Copy {}
59+
60+
impl Copy for bool {}
61+
impl Copy for u8 {}
62+
impl Copy for u16 {}
63+
impl Copy for u32 {}
64+
impl Copy for u64 {}
65+
impl Copy for u128 {}
66+
impl Copy for usize {}
67+
impl Copy for i8 {}
68+
impl Copy for i16 {}
69+
impl Copy for i32 {}
70+
impl Copy for isize {}
71+
impl Copy for f32 {}
72+
impl Copy for f64 {}
73+
impl Copy for char {}
74+
impl<'a, T: ?Sized> Copy for &'a T {}
75+
impl<T: ?Sized> Copy for *const T {}
76+
impl<T: ?Sized> Copy for *mut T {}
77+
impl<T: Copy> Copy for Option<T> {}
7878

7979
#[lang = "sync"]
8080
pub unsafe trait Sync {}

compiler/rustc_codegen_gcc/example/mini_core.rs

+18-18
Original file line numberDiff line numberDiff line change
@@ -52,24 +52,24 @@ impl<T: ?Sized> LegacyReceiver for &mut T {}
5252
impl<T: ?Sized, A: Allocator> LegacyReceiver for Box<T, A> {}
5353

5454
#[lang = "copy"]
55-
pub unsafe trait Copy {}
56-
57-
unsafe impl Copy for bool {}
58-
unsafe impl Copy for u8 {}
59-
unsafe impl Copy for u16 {}
60-
unsafe impl Copy for u32 {}
61-
unsafe impl Copy for u64 {}
62-
unsafe impl Copy for usize {}
63-
unsafe impl Copy for i8 {}
64-
unsafe impl Copy for i16 {}
65-
unsafe impl Copy for i32 {}
66-
unsafe impl Copy for isize {}
67-
unsafe impl Copy for f32 {}
68-
unsafe impl Copy for f64 {}
69-
unsafe impl Copy for char {}
70-
unsafe impl<'a, T: ?Sized> Copy for &'a T {}
71-
unsafe impl<T: ?Sized> Copy for *const T {}
72-
unsafe impl<T: ?Sized> Copy for *mut T {}
55+
pub trait Copy {}
56+
57+
impl Copy for bool {}
58+
impl Copy for u8 {}
59+
impl Copy for u16 {}
60+
impl Copy for u32 {}
61+
impl Copy for u64 {}
62+
impl Copy for usize {}
63+
impl Copy for i8 {}
64+
impl Copy for i16 {}
65+
impl Copy for i32 {}
66+
impl Copy for isize {}
67+
impl Copy for f32 {}
68+
impl Copy for f64 {}
69+
impl Copy for char {}
70+
impl<'a, T: ?Sized> Copy for &'a T {}
71+
impl<T: ?Sized> Copy for *const T {}
72+
impl<T: ?Sized> Copy for *mut T {}
7373

7474
#[lang = "sync"]
7575
pub unsafe trait Sync {}

compiler/rustc_hir_analysis/src/coherence/builtin.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ fn visit_implementation_of_copy(checker: &Checker<'_>) -> Result<(), ErrorGuaran
103103
}
104104

105105
let cause = traits::ObligationCause::misc(DUMMY_SP, impl_did);
106-
match type_allowed_to_implement_copy(tcx, param_env, self_type, cause) {
106+
match type_allowed_to_implement_copy(tcx, param_env, self_type, cause, impl_header.safety) {
107107
Ok(()) => Ok(()),
108108
Err(CopyImplementationError::InfringingFields(fields)) => {
109109
let span = tcx.hir().expect_item(impl_did).expect_impl().self_ty.span;
@@ -123,6 +123,12 @@ fn visit_implementation_of_copy(checker: &Checker<'_>) -> Result<(), ErrorGuaran
123123
let span = tcx.hir().expect_item(impl_did).expect_impl().self_ty.span;
124124
Err(tcx.dcx().emit_err(errors::CopyImplOnTypeWithDtor { span }))
125125
}
126+
Err(CopyImplementationError::HasUnsafeFields) => {
127+
let span = tcx.hir().expect_item(impl_did).expect_impl().self_ty.span;
128+
Err(tcx
129+
.dcx()
130+
.span_delayed_bug(span, format!("cannot implement `Copy` for `{}`", self_type)))
131+
}
126132
}
127133
}
128134

compiler/rustc_hir_analysis/src/coherence/unsafety.rs

+30-8
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
44
use rustc_errors::codes::*;
55
use rustc_errors::struct_span_code_err;
6-
use rustc_hir::Safety;
6+
use rustc_hir::{LangItem, Safety};
77
use rustc_middle::ty::ImplPolarity::*;
88
use rustc_middle::ty::print::PrintTraitRefExt as _;
99
use rustc_middle::ty::{ImplTraitHeader, TraitDef, TyCtxt};
@@ -20,7 +20,19 @@ pub(super) fn check_item(
2020
tcx.generics_of(def_id).own_params.iter().find(|p| p.pure_wrt_drop).map(|_| "may_dangle");
2121
let trait_ref = trait_header.trait_ref.instantiate_identity();
2222

23-
match (trait_def.safety, unsafe_attr, trait_header.safety, trait_header.polarity) {
23+
let is_copy = tcx.is_lang_item(trait_def.def_id, LangItem::Copy);
24+
let trait_def_safety = if is_copy {
25+
// If `Self` has unsafe fields, `Copy` is unsafe to implement.
26+
if trait_header.trait_ref.skip_binder().self_ty().has_unsafe_fields() {
27+
rustc_hir::Safety::Unsafe
28+
} else {
29+
rustc_hir::Safety::Safe
30+
}
31+
} else {
32+
trait_def.safety
33+
};
34+
35+
match (trait_def_safety, unsafe_attr, trait_header.safety, trait_header.polarity) {
2436
(Safety::Safe, None, Safety::Unsafe, Positive | Reservation) => {
2537
let span = tcx.def_span(def_id);
2638
return Err(struct_span_code_err!(
@@ -48,12 +60,22 @@ pub(super) fn check_item(
4860
"the trait `{}` requires an `unsafe impl` declaration",
4961
trait_ref.print_trait_sugared()
5062
)
51-
.with_note(format!(
52-
"the trait `{}` enforces invariants that the compiler can't check. \
53-
Review the trait documentation and make sure this implementation \
54-
upholds those invariants before adding the `unsafe` keyword",
55-
trait_ref.print_trait_sugared()
56-
))
63+
.with_note(if is_copy {
64+
format!(
65+
"the trait `{}` cannot be safely implemented for `{}` \
66+
because it has unsafe fields. Review the invariants \
67+
of those fields before adding an `unsafe impl`",
68+
trait_ref.print_trait_sugared(),
69+
trait_ref.self_ty(),
70+
)
71+
} else {
72+
format!(
73+
"the trait `{}` enforces invariants that the compiler can't check. \
74+
Review the trait documentation and make sure this implementation \
75+
upholds those invariants before adding the `unsafe` keyword",
76+
trait_ref.print_trait_sugared()
77+
)
78+
})
5779
.with_span_suggestion_verbose(
5880
span.shrink_to_lo(),
5981
"add `unsafe` to this trait implementation",

compiler/rustc_lint/src/builtin.rs

+1
Original file line numberDiff line numberDiff line change
@@ -625,6 +625,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingCopyImplementations {
625625
cx.param_env,
626626
ty,
627627
traits::ObligationCause::misc(item.span, item.owner_id.def_id),
628+
hir::Safety::Safe,
628629
)
629630
.is_ok()
630631
{

compiler/rustc_middle/src/ty/sty.rs

+1-5
Original file line numberDiff line numberDiff line change
@@ -980,11 +980,7 @@ impl<'tcx> rustc_type_ir::inherent::Ty<TyCtxt<'tcx>> for Ty<'tcx> {
980980
}
981981

982982
fn has_unsafe_fields(self) -> bool {
983-
if let ty::Adt(adt_def, ..) = self.kind() {
984-
adt_def.all_fields().any(|x| x.safety == hir::Safety::Unsafe)
985-
} else {
986-
false
987-
}
983+
Ty::has_unsafe_fields(self)
988984
}
989985
}
990986

compiler/rustc_middle/src/ty/util.rs

+9
Original file line numberDiff line numberDiff line change
@@ -1288,6 +1288,15 @@ impl<'tcx> Ty<'tcx> {
12881288
}
12891289
}
12901290

1291+
/// Checks whether this type is an ADT that has unsafe fields.
1292+
pub fn has_unsafe_fields(self) -> bool {
1293+
if let ty::Adt(adt_def, ..) = self.kind() {
1294+
adt_def.all_fields().any(|x| x.safety == hir::Safety::Unsafe)
1295+
} else {
1296+
false
1297+
}
1298+
}
1299+
12911300
/// Get morphology of the async drop glue, needed for types which do not
12921301
/// use async drop. To get async drop glue morphology for a definition see
12931302
/// [`TyCtxt::async_drop_glue_morphology`]. Used for `AsyncDestruct::Destructor`

compiler/rustc_trait_selection/src/traits/misc.rs

+10
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ pub enum CopyImplementationError<'tcx> {
1818
InfringingFields(Vec<(&'tcx ty::FieldDef, Ty<'tcx>, InfringingFieldsReason<'tcx>)>),
1919
NotAnAdt,
2020
HasDestructor,
21+
HasUnsafeFields,
2122
}
2223

2324
pub enum ConstParamTyImplementationError<'tcx> {
@@ -39,11 +40,16 @@ pub enum InfringingFieldsReason<'tcx> {
3940
///
4041
/// If it's not an ADT, int ty, `bool`, float ty, `char`, raw pointer, `!`,
4142
/// a reference or an array returns `Err(NotAnAdt)`.
43+
///
44+
/// If the impl is `Safe`, `self_type` must not have unsafe fields. When used to
45+
/// generate suggestions in lints, `Safe` should be supplied so as to not
46+
/// suggest implementing `Copy` for types with unsafe fields.
4247
pub fn type_allowed_to_implement_copy<'tcx>(
4348
tcx: TyCtxt<'tcx>,
4449
param_env: ty::ParamEnv<'tcx>,
4550
self_type: Ty<'tcx>,
4651
parent_cause: ObligationCause<'tcx>,
52+
impl_safety: hir::Safety,
4753
) -> Result<(), CopyImplementationError<'tcx>> {
4854
let (adt, args) = match self_type.kind() {
4955
// These types used to have a builtin impl.
@@ -78,6 +84,10 @@ pub fn type_allowed_to_implement_copy<'tcx>(
7884
return Err(CopyImplementationError::HasDestructor);
7985
}
8086

87+
if impl_safety == hir::Safety::Safe && self_type.has_unsafe_fields() {
88+
return Err(CopyImplementationError::HasUnsafeFields);
89+
}
90+
8191
Ok(())
8292
}
8393

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

-2
Original file line numberDiff line numberDiff line change
@@ -795,8 +795,6 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
795795
| ty::Never
796796
| ty::Tuple(_)
797797
| ty::CoroutineWitness(..) => {
798-
use rustc_type_ir::inherent::*;
799-
800798
// Only consider auto impls of unsafe traits when there are
801799
// no unsafe fields.
802800
if self.tcx().trait_is_unsafe(def_id) && self_ty.has_unsafe_fields() {

src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs

+1
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue {
200200
cx.param_env,
201201
ty,
202202
traits::ObligationCause::dummy_with_span(span),
203+
rustc_hir::Safety::Safe,
203204
)
204205
.is_ok()
205206
{

tests/ui/unsafe-fields/copy-trait.rs

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
//@ compile-flags: --crate-type=lib
2+
3+
#![feature(unsafe_fields)]
4+
#![allow(incomplete_features)]
5+
#![deny(missing_copy_implementations)]
6+
7+
mod good_safe_impl {
8+
enum SafeEnum {
9+
Safe(u8),
10+
}
11+
12+
impl Copy for SafeEnum {}
13+
}
14+
15+
mod bad_safe_impl {
16+
enum UnsafeEnum {
17+
Safe(u8),
18+
Unsafe { unsafe field: u8 },
19+
}
20+
21+
impl Copy for UnsafeEnum {}
22+
//~^ ERROR the trait `Copy` requires an `unsafe impl` declaration
23+
}
24+
25+
mod good_unsafe_impl {
26+
enum UnsafeEnum {
27+
Safe(u8),
28+
Unsafe { unsafe field: u8 },
29+
}
30+
31+
unsafe impl Copy for UnsafeEnum {}
32+
}
33+
34+
mod bad_unsafe_impl {
35+
enum SafeEnum {
36+
Safe(u8),
37+
}
38+
39+
unsafe impl Copy for SafeEnum {}
40+
//~^ ERROR implementing the trait `Copy` is not unsafe
41+
}
+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
error[E0200]: the trait `Copy` requires an `unsafe impl` declaration
2+
--> $DIR/copy-trait.rs:21:5
3+
|
4+
LL | impl Copy for UnsafeEnum {}
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^
6+
|
7+
= note: the trait `Copy` cannot be safely implemented for `bad_safe_impl::UnsafeEnum` because it has unsafe fields. Review the invariants of those fields before adding an `unsafe impl`
8+
help: add `unsafe` to this trait implementation
9+
|
10+
LL | unsafe impl Copy for UnsafeEnum {}
11+
| ++++++
12+
13+
error[E0199]: implementing the trait `Copy` is not unsafe
14+
--> $DIR/copy-trait.rs:39:5
15+
|
16+
LL | unsafe impl Copy for SafeEnum {}
17+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
18+
|
19+
help: remove `unsafe` from this trait implementation
20+
|
21+
LL - unsafe impl Copy for SafeEnum {}
22+
LL + impl Copy for SafeEnum {}
23+
|
24+
25+
error: aborting due to 2 previous errors
26+
27+
Some errors have detailed explanations: E0199, E0200.
28+
For more information about an error, try `rustc --explain E0199`.

0 commit comments

Comments
 (0)