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 require `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
This commit is contained in:
parent
9c707a8b76
commit
3ce35a4ec5
12 changed files with 164 additions and 52 deletions
|
@ -980,11 +980,7 @@ impl<'tcx> rustc_type_ir::inherent::Ty<TyCtxt<'tcx>> for Ty<'tcx> {
|
|||
}
|
||||
|
||||
fn has_unsafe_fields(self) -> bool {
|
||||
if let ty::Adt(adt_def, ..) = self.kind() {
|
||||
adt_def.all_fields().any(|x| x.safety == hir::Safety::Unsafe)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
Ty::has_unsafe_fields(self)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1288,6 +1288,15 @@ impl<'tcx> Ty<'tcx> {
|
|||
}
|
||||
}
|
||||
|
||||
/// Checks whether this type is an ADT that has unsafe fields.
|
||||
pub fn has_unsafe_fields(self) -> bool {
|
||||
if let ty::Adt(adt_def, ..) = self.kind() {
|
||||
adt_def.all_fields().any(|x| x.safety == hir::Safety::Unsafe)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Get morphology of the async drop glue, needed for types which do not
|
||||
/// use async drop. To get async drop glue morphology for a definition see
|
||||
/// [`TyCtxt::async_drop_glue_morphology`]. Used for `AsyncDestruct::Destructor`
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue