diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index 3c9a6b5697eeb..8e7524d1f0674 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -7,14 +7,15 @@ use rustc_attr_ir::find_attr; use rustc_attr_ir::lang_items::LangItem; use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_errors::codes::*; -use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, Level, MultiSpan}; +use rustc_errors::{Diag, DiagCtxtHandle, DiagDecorator, Diagnostic, Level, MultiSpan}; use rustc_hir as hir; use rustc_hir::def::{CtorKind, DefKind}; use rustc_hir::{Node, intravisit}; use rustc_infer::infer::{RegionVariableOrigin, TyCtxtInferExt}; use rustc_infer::traits::{Obligation, ObligationCauseCode, TraitErrors, WellFormedLoc}; use rustc_lint_defs::builtin::{ - ALIGNED_FIELDS_IN_PACKED, DEAD_CODE, UNINHABITED_STATIC, UNSUPPORTED_CALLING_CONVENTIONS, + ALIGNED_FIELDS_IN_PACKED, DEAD_CODE, NON_ZST_REPR_TRANSPARENT_ARRAY_ELEMENT, + UNINHABITED_STATIC, UNSUPPORTED_CALLING_CONVENTIONS, }; use rustc_macros::Diagnostic; use rustc_middle::hir::nested_filter; @@ -1813,32 +1814,66 @@ fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) { /// We call a field "trivial" for `repr(transparent)` purposes if it can be ignored. /// IOW, `repr(transparent)` is allowed if there is at most one non-trivial field. /// This enum captures all the reasons why a field might not be "trivial". + /// All types we consider trivial here must have [trivial ABI]. + /// + /// [trivial ABI]: https://doc.rust-lang.org/nightly/std/primitive.fn.html#abi-compatibility enum NonTrivialReason<'tcx> { UnknownLayout, NonZeroSized, + NonZeroSizedElement { element: Ty<'tcx> }, NonTrivialAlignment, PrivateField { inside: Ty<'tcx> }, NonExhaustive { ty: Ty<'tcx> }, ReprC { ty: Ty<'tcx> }, + ContainsClosure { ty: Ty<'tcx> }, } struct NonTrivialFieldInfo<'tcx> { span: Span, reason: NonTrivialReason<'tcx>, + /// True if this is an error, false if this is just a FCW. + hard_error: bool, } /// Check if this type is "trivial" for `repr(transparent)`. If not, return the reason why - /// and the problematic type. + /// and the problematic type. If `only_check_semver` is set, only checks for things that could + /// become non-1-ZST in the future (i.e., types where more fields could be added in a + /// semver-compatible way). This assumes that `ty` has already been confirmed to be a 1-ZST. + // Note that this is currently called with non-1-ZST array element types as the check for those + // being a 1-ZST is currently only a FCW. fn is_trivial<'tcx>( tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, ty: Ty<'tcx>, + only_check_semver: bool, + found_fcw: &mut impl FnMut(NonTrivialReason<'tcx>), ) -> ControlFlow> { // We can encounter projections during traversal, so ensure the type is normalized. let ty = tcx.try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty)).unwrap_or(ty); match ty.kind() { - ty::Tuple(list) => list.iter().try_for_each(|t| is_trivial(tcx, typing_env, t)), - ty::Array(ty, _) => is_trivial(tcx, typing_env, *ty), + // Tuples are always trivial iff they are 1-ZSTs. + // They still need to be checked for semver issues. + ty::Tuple(list) => { + list.iter().try_for_each(|t| is_trivial(tcx, typing_env, t, true, found_fcw)) + } + // Arrays are trivial iff the element type is trivial. + ty::Array(ty, _) => { + if !only_check_semver { + // Check that the element type is a 1-ZST, which is required for the array to be + // trivial and not checked by the `is_trivial` call below. This is currently a + // FCW. + if let Ok(layout) = tcx.layout_of(typing_env.as_query_input(*ty)) { + if !layout.is_1zst() { + found_fcw(NonTrivialReason::NonZeroSizedElement { element: *ty }); + } + } else { + found_fcw(NonTrivialReason::UnknownLayout); + } + } + is_trivial(tcx, typing_env, *ty, only_check_semver, found_fcw) + } + // 1-ZST ADTs are trivial iff they are (a) `repr(Rust)`, or (b) `repr(transparent)` with + // all fields also being trivial. Fields must always be checked for semver issues. ty::Adt(def, args) => { if !def.did().is_local() && !find_attr!(tcx, def.did(), RustcPubTransparent(_)) { let non_exhaustive = def.is_variant_list_non_exhaustive() @@ -1851,14 +1886,66 @@ fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) { return ControlFlow::Break(NonTrivialReason::PrivateField { inside: ty }); } } - if def.repr().c() { + if !only_check_semver && !def.repr().rust() && !def.repr().transparent() { return ControlFlow::Break(NonTrivialReason::ReprC { ty }); } - def.all_fields() - .map(|field| field.ty(tcx, *args).skip_norm_wip()) - .try_for_each(|t| is_trivial(tcx, typing_env, t)) + // Transparent ADTs must have trivial fields, so we fully recurse. For other ADTs we + // can switch to `only_check_semver` mode as the ABI is definitely trivial. + def.all_fields().map(|field| field.ty(tcx, *args).skip_norm_wip()).try_for_each( + |t| { + is_trivial( + tcx, + typing_env, + t, + only_check_semver || !def.repr().transparent(), + found_fcw, + ) + }, + ) + } + // These types always have trivial ABI. + ty::FnDef(..) | ty::Never => ControlFlow::Continue(()), + // A closure changing size shouldn't break semver, so disallow closure-like types. Note + // that this cannot occur in practice at the moment as these types are all unnameable. + ty::Closure(..) + | ty::CoroutineClosure(..) + | ty::Coroutine(..) + | ty::CoroutineWitness(..) => { + ControlFlow::Break(NonTrivialReason::ContainsClosure { ty }) + } + // Pattern types are trivial iff their underlying type is trivial (shouldn't occur at + // the moment as pattern types are currently restricted to integers). + ty::Pat(ty, _) => is_trivial(tcx, typing_env, *ty, only_check_semver, found_fcw), + ty::UnsafeBinder(bound_ty) => { + // Lifetimes do not affect whether a type has trivial ABI. + let ty = tcx.instantiate_bound_regions_with_erased((*bound_ty).into()); + is_trivial(tcx, typing_env, ty, only_check_semver, found_fcw) } - _ => ControlFlow::Continue(()), + // FIXME(scrabsha): View types are still being implemented. + ty::View(..) => unimplemented!(), + + // These types are never 1-ZSTs, so this is only reachable due to the array element type + // 1-ZST check only being a FCW. + // FIXME: Make this `bug!` once the FCW is a hard error. + ty::Bool + | ty::Char + | ty::Int(..) + | ty::Uint(..) + | ty::Float(..) + | ty::RawPtr(..) + | ty::Ref(..) + | ty::FnPtr(..) => ControlFlow::Continue(()), + // These types are unsized, so this is unreachable. + ty::Foreign(..) | ty::Str | ty::Slice(..) | ty::Dynamic(..) => { + bug!("unexpected type passed to is_trivial: {ty:?}") + } + // The layout of `ty` is known, so these cannot occur. + ty::Alias(..) + | ty::Param(..) + | ty::Bound(..) + | ty::Placeholder(..) + | ty::Infer(..) + | ty::Error(..) => bug!("unexpected type passed to is_trivial: {ty:?}"), } } @@ -1883,14 +1970,24 @@ fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) { } } }; - return Some(NonTrivialFieldInfo { span, reason }); + return Some(NonTrivialFieldInfo { span, reason, hard_error: true }); } // Recursively check for other things that have to be ruled out. - if let Some(reason) = is_trivial(tcx, typing_env, ty).break_value() { - return Some(NonTrivialFieldInfo { span, reason }); + let mut fcw_reason = None; + if let Some(reason) = is_trivial(tcx, typing_env, ty, false, &mut |reason| { + if fcw_reason.is_none() { + fcw_reason = Some(reason); + } + }) + .break_value() + { + Some(NonTrivialFieldInfo { span, reason, hard_error: true }) + } else if let Some(reason) = fcw_reason { + Some(NonTrivialFieldInfo { span, reason, hard_error: false }) + } else { + // Otherwise, + None } - // Otherwise, - None }) .collect::>(); @@ -1902,37 +1999,60 @@ fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) { format_args!("transparent {}", adt.descr()) }; let ty_span = tcx.def_span(adt.did()); - let mut diag = tcx.dcx().struct_span_err( - ty_span, - format!("{desc} needs at most one non-trivial field, but has {count}"), - ); - diag.code(E0690); - - // Label for the type. - diag.span_label(ty_span, format!("needs at most one non-trivial field, but has {count}")); - // Label for each non-trivial field. - for field in non_trivial_fields { - let msg = match field.reason { - NonTrivialReason::UnknownLayout => { - format!("this field is generic and hence may have non-zero size") - } - NonTrivialReason::NonZeroSized => format!("this field has non-zero size"), - NonTrivialReason::NonTrivialAlignment => format!("this field requires alignment"), - NonTrivialReason::PrivateField { inside } => format!( - "this field contains `{inside}`, which has private fields, so it could become non-zero-sized in the future" - ), - NonTrivialReason::NonExhaustive { ty } => format!( - "this field contains `{ty}`, which is marked with `#[non_exhaustive]`, so it could become non-zero-sized in the future" - ), - NonTrivialReason::ReprC { ty } => format!( - "this field contains `{ty}`, which is a `#[repr(C)]` type, so it is not guaranteed to be zero-sized on all targets" + let message = format!("{desc} needs at most one non-trivial field, but has {count}"); + let decorate = |diag: &mut Diag<'_>| { + // Label for the type. + diag.span_label( + ty_span, + format!("needs at most one non-trivial field, but has {count}"), + ); + // Label for each non-trivial field. + for field in &non_trivial_fields { + let msg = match field.reason { + NonTrivialReason::UnknownLayout => { + format!("this field is generic and hence may have non-zero size") + } + NonTrivialReason::NonZeroSized => format!("this field has non-zero size"), + NonTrivialReason::NonZeroSizedElement { element } => format!( + "this field contains an array with an element type of `{element}`, which has non-zero size" + ), + NonTrivialReason::NonTrivialAlignment => { + format!("this field requires alignment") + } + NonTrivialReason::PrivateField { inside } => format!( + "this field contains `{inside}`, which has private fields, so it could become non-zero-sized in the future" + ), + NonTrivialReason::NonExhaustive { ty } => format!( + "this field contains `{ty}`, which is marked with `#[non_exhaustive]`, so it could become non-zero-sized in the future" + ), + NonTrivialReason::ReprC { ty } => format!( + "this field contains `{ty}`, which is a `#[repr(C)]` type, so it is not guaranteed to be zero-sized on all targets" + ), + NonTrivialReason::ContainsClosure { ty } => format!( + "this field contains `{ty}` which is a closure and therefore is not guaranteed to be zero-sized" + ), + }; + diag.span_label(field.span, msg); + } + }; + if non_trivial_fields.iter().filter(|field| field.hard_error).count() > 1 { + let mut diag = tcx.dcx().struct_span_err(ty_span, message); + diag.code(E0690); + decorate(&mut diag); + diag.emit(); + } else { + tcx.emit_node_span_lint( + NON_ZST_REPR_TRANSPARENT_ARRAY_ELEMENT, + tcx.local_def_id_to_hir_id( + adt.did().as_local().expect("check_transparent is only called on local types"), ), - }; - diag.span_label(field.span, msg); + ty_span, + DiagDecorator(|diag| { + diag.primary_message(message); + decorate(diag); + }), + ); } - - diag.emit(); - return; } } diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index f1bf802dad9d0..952fbc1b08719 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -83,6 +83,7 @@ pub mod hardwired { NEVER_TYPE_FALLBACK_FLOWING_INTO_UNSAFE, NON_CONTIGUOUS_RANGE_ENDPOINTS, NON_EXHAUSTIVE_OMITTED_PATTERNS, + NON_ZST_REPR_TRANSPARENT_ARRAY_ELEMENT, NO_LINK_ATTRIBUTES, OUT_OF_SCOPE_MACRO_CALLS, OVERLAPPING_RANGE_ENDPOINTS, @@ -6051,3 +6052,44 @@ declare_lint! { report_in_deps: true, }; } + +declare_lint! { + /// The `non_zst_repr_transparent_array_element` lint detects `repr(transparent)` types that + /// have multiple non-trivial fields due to some of the fields being arrays with non-ZST element + /// types. + /// + /// ### Example + /// + /// ```rust + /// #[repr(transparent)] + /// struct Foo(u64, [u8; 0]); + /// ``` + /// + /// {{produces}} + /// + /// ### Explanation + /// + /// Only some zero-sized types with an alignment of 1 (1-ZSTs) have a trivial ABI (meaning that + /// they do not influence the ABI) - the full list can be found in the + /// [abi compatibility documentation]. `#[repr(transparent)]` types must have at most 1 field + /// with non-trivial ABI, as they have the same ABI as that non-trivial field. Arrays with + /// element types that are non-trivial are also non-trivial, regardless of length. The compiler + /// currently accepts as trivial fields some arrays with non-zero-sized element types as trivial + /// field types if the resulting array happened to be a 1-ZST, but this means that a + /// `#[repr(transparent)]` type can have multiple fields with non-trivial ABI and therefore an + /// ambiguous ABI, so this a [future-incompatible] lint to transition this to a hard error in a + /// future release. + /// + /// The fix for this lint is usually to either remove the array field, or replace it with a type + /// with trivial ABI like [`PhantomData`]. + /// + /// [abi compatibility documentation]: https://doc.rust-lang.org/nightly/std/primitive.fn.html#abi-compatibility + /// [`PhantomData`]: https://doc.rust-lang.org/std/marker/struct.PhantomData.html + /// [future-incompatible]: ../index.md#future-incompatible-lints + pub NON_ZST_REPR_TRANSPARENT_ARRAY_ELEMENT, + Warn, + "detects `repr(transparent)` types which have more than one type with non-trivial type due to 1-ZST arrays with non-ZST elements", + @future_incompatible = FutureIncompatibleInfo { + reason: fcw!(FutureReleaseError #166183), + }; +} diff --git a/tests/codegen-llvm/repr/transparent.rs b/tests/codegen-llvm/repr/transparent.rs index 0f23508f2e644..4fda8fa31246a 100644 --- a/tests/codegen-llvm/repr/transparent.rs +++ b/tests/codegen-llvm/repr/transparent.rs @@ -53,7 +53,7 @@ pub extern "C" fn test_WithZst(_: WithZst) -> WithZst { } #[repr(transparent)] -pub struct WithZeroSizedArray(*const f32, [i8; 0]); +pub struct WithZeroSizedArray(*const f32, [(); 0]); // CHECK: define{{.*}}ptr @test_WithZeroSizedArray(ptr noundef %_1) #[no_mangle] diff --git a/tests/ui/abi/compatibility.rs b/tests/ui/abi/compatibility.rs index 37139f0e633cf..b08e72434f45d 100644 --- a/tests/ui/abi/compatibility.rs +++ b/tests/ui/abi/compatibility.rs @@ -260,7 +260,7 @@ struct TransparentWrapper1(T); #[repr(transparent)] struct TransparentWrapper2((), Zst, T); #[repr(transparent)] -struct TransparentWrapper3(T, [u8; 0], PhantomData); +struct TransparentWrapper3(T, [(ReprC,); 0], PhantomData); #[repr(transparent)] union TransparentWrapperUnion { nothing: (), diff --git a/tests/ui/layout/homogeneous-aggr-transparent.rs b/tests/ui/layout/homogeneous-aggr-transparent.rs index d968d609835f7..a9abf44198c9f 100644 --- a/tests/ui/layout/homogeneous-aggr-transparent.rs +++ b/tests/ui/layout/homogeneous-aggr-transparent.rs @@ -14,7 +14,7 @@ struct Wrapper1(T); #[repr(transparent)] struct Wrapper2((), Zst, T); #[repr(transparent)] -struct Wrapper3(T, [u8; 0], PhantomData); +struct Wrapper3(T, [(); 0], PhantomData); #[repr(transparent)] union WrapperUnion { nothing: (), diff --git a/tests/ui/repr/repr-transparent-non-exhaustive.rs b/tests/ui/repr/repr-transparent-non-exhaustive.rs index 43dba32affb01..a3ed01f4ceca7 100644 --- a/tests/ui/repr/repr-transparent-non-exhaustive.rs +++ b/tests/ui/repr/repr-transparent-non-exhaustive.rs @@ -126,4 +126,12 @@ pub struct T22(NonExhaustive, InternalPrivate); pub struct T22Flipped(InternalPrivate, NonExhaustive); // Okay, since there's only 1 foreign non-exhaustive type. +#[repr(transparent)] +pub struct T23(Sized, (NonExhaustive,)); +//~^ ERROR needs at most one non-trivial field + +#[repr(transparent)] +pub struct T24(Sized, InternalIndirection); +//~^ ERROR needs at most one non-trivial field + fn main() {} diff --git a/tests/ui/repr/repr-transparent-non-exhaustive.stderr b/tests/ui/repr/repr-transparent-non-exhaustive.stderr index cdaedcca418da..57f5a80fcdf8d 100644 --- a/tests/ui/repr/repr-transparent-non-exhaustive.stderr +++ b/tests/ui/repr/repr-transparent-non-exhaustive.stderr @@ -151,6 +151,24 @@ LL | pub struct T19Flipped(Private, NonExhaustive); | | this field contains `Private`, which has private fields, so it could become non-zero-sized in the future | needs at most one non-trivial field, but has 2 -error: aborting due to 17 previous errors +error[E0690]: transparent struct needs at most one non-trivial field, but has 2 + --> $DIR/repr-transparent-non-exhaustive.rs:130:1 + | +LL | pub struct T23(Sized, (NonExhaustive,)); + | ^^^^^^^^^^^^^^ ----- ---------------- this field contains `NonExhaustive`, which is marked with `#[non_exhaustive]`, so it could become non-zero-sized in the future + | | | + | | this field has non-zero size + | needs at most one non-trivial field, but has 2 + +error[E0690]: transparent struct needs at most one non-trivial field, but has 2 + --> $DIR/repr-transparent-non-exhaustive.rs:134:1 + | +LL | pub struct T24(Sized, InternalIndirection); + | ^^^^^^^^^^^^^^ ----- ---------------------------- this field contains `Private`, which has private fields, so it could become non-zero-sized in the future + | | | + | | this field has non-zero size + | needs at most one non-trivial field, but has 2 + +error: aborting due to 19 previous errors For more information about this error, try `rustc --explain E0690`. diff --git a/tests/ui/repr/repr-transparent-repr-c.rs b/tests/ui/repr/repr-transparent-repr-c.rs index 148284469da32..261b5a3814972 100644 --- a/tests/ui/repr/repr-transparent-repr-c.rs +++ b/tests/ui/repr/repr-transparent-repr-c.rs @@ -3,6 +3,8 @@ pub struct ReprC1Zst { pub _f: (), } +pub struct ReprRust(T); + pub type Sized = i32; #[repr(transparent)] @@ -24,4 +26,15 @@ pub struct T6(ReprC1Zst, Sized); pub struct T7(T1, [Sized; 0]); // still wrong, even when the repr(C) is hidden inside another type //~^ ERROR needs at most one non-trivial field +#[repr(transparent)] +pub struct T8(Sized, ReprRust); +#[repr(transparent)] +pub struct T9(Sized, (ReprC1Zst,)); +#[repr(transparent)] +pub struct T10(Sized, [u8; 0]); +//~^ WARN needs at most one non-trivial field +//~| WARN this was previously accepted by the compiler +#[repr(transparent)] +pub struct T11(Sized, !); + fn main() {} diff --git a/tests/ui/repr/repr-transparent-repr-c.stderr b/tests/ui/repr/repr-transparent-repr-c.stderr index e6d11148a064e..b7268479c7a2c 100644 --- a/tests/ui/repr/repr-transparent-repr-c.stderr +++ b/tests/ui/repr/repr-transparent-repr-c.stderr @@ -1,5 +1,5 @@ error[E0690]: transparent struct needs at most one non-trivial field, but has 2 - --> $DIR/repr-transparent-repr-c.rs:16:1 + --> $DIR/repr-transparent-repr-c.rs:18:1 | LL | pub struct T5(Sized, ReprC1Zst); | ^^^^^^^^^^^^^ ----- --------- this field contains `ReprC1Zst`, which is a `#[repr(C)]` type, so it is not guaranteed to be zero-sized on all targets @@ -8,7 +8,7 @@ LL | pub struct T5(Sized, ReprC1Zst); | needs at most one non-trivial field, but has 2 error[E0690]: transparent struct needs at most one non-trivial field, but has 2 - --> $DIR/repr-transparent-repr-c.rs:20:1 + --> $DIR/repr-transparent-repr-c.rs:22:1 | LL | pub struct T6(ReprC1Zst, Sized); | ^^^^^^^^^^^^^ --------- ----- this field has non-zero size @@ -17,7 +17,7 @@ LL | pub struct T6(ReprC1Zst, Sized); | needs at most one non-trivial field, but has 2 error[E0690]: transparent struct needs at most one non-trivial field, but has 2 - --> $DIR/repr-transparent-repr-c.rs:24:1 + --> $DIR/repr-transparent-repr-c.rs:26:1 | LL | pub struct T7(T1, [Sized; 0]); // still wrong, even when the repr(C) is hidden inside another type | ^^^^^^^^^^^^^ -- ---------- this field requires alignment @@ -25,6 +25,19 @@ LL | pub struct T7(T1, [Sized; 0]); // still wrong, even when the repr(C) is hid | | this field contains `ReprC1Zst`, which is a `#[repr(C)]` type, so it is not guaranteed to be zero-sized on all targets | needs at most one non-trivial field, but has 2 -error: aborting due to 3 previous errors +warning: transparent struct needs at most one non-trivial field, but has 2 + --> $DIR/repr-transparent-repr-c.rs:34:1 + | +LL | pub struct T10(Sized, [u8; 0]); + | ^^^^^^^^^^^^^^ ----- ------- this field contains an array with an element type of `u8`, which has non-zero size + | | | + | | this field has non-zero size + | needs at most one non-trivial field, but has 2 + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #166183 + = note: `#[warn(non_zst_repr_transparent_array_element)]` (part of `#[warn(future_incompatible)]`) on by default + +error: aborting due to 3 previous errors; 1 warning emitted For more information about this error, try `rustc --explain E0690`.