Skip to content

Commit e6e322f

Browse files
committed
do not implement unsafe auto traits for types with unsafe fields
If a type has unsafe fields, its safety invariants are not simply the conjunction of its field types' safety invariants. Consequently, it's invalid to reason about the safety properties of these types in a purely structural manner — i.e., the manner in which `auto` traits are implemented. Makes progress towards #132922.
1 parent 0e98766 commit e6e322f

File tree

10 files changed

+20
-0
lines changed

10 files changed

+20
-0
lines changed

Diff for: compiler/rustc_middle/src/ty/mod.rs

+5
Original file line numberDiff line numberDiff line change
@@ -1837,6 +1837,11 @@ impl<'tcx> TyCtxt<'tcx> {
18371837
self.trait_def(trait_def_id).has_auto_impl
18381838
}
18391839

1840+
/// Returns `true` if this is an `unsafe trait`.
1841+
pub fn trait_is_unsafe(self, trait_def_id: DefId) -> bool {
1842+
self.trait_def(trait_def_id).safety == Safety::Unsafe
1843+
}
1844+
18401845
/// Returns `true` if this is coinductive, either because it is
18411846
/// an auto trait or because it has the `#[rustc_coinductive]` attribute.
18421847
pub fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {

Diff for: 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 directly contains 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`

Diff for: compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs

+6
Original file line numberDiff line numberDiff line change
@@ -794,6 +794,12 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
794794
| ty::Never
795795
| ty::Tuple(_)
796796
| ty::CoroutineWitness(..) => {
797+
// Only consider auto impls of unsafe traits when there are
798+
// no unsafe fields.
799+
if self.tcx().trait_is_unsafe(def_id) && self_ty.has_unsafe_fields() {
800+
return;
801+
}
802+
797803
// Only consider auto impls if there are no manual impls for the root of `self_ty`.
798804
//
799805
// For example, we only consider auto candidates for `&i32: Auto` if no explicit impl
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

0 commit comments

Comments
 (0)