diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index 6a42fdb1079f4..acccc692fea13 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -1025,7 +1025,13 @@ fn adt_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::AdtDef<'_> { let is_anonymous = item.ident.name == kw::Empty; let repr = if is_anonymous { - tcx.adt_def(tcx.local_parent(def_id)).repr() + let parent = tcx.local_parent(def_id); + if matches!(tcx.hir_node_by_def_id(parent), Node::Item(_)) { + tcx.adt_def(tcx.local_parent(def_id)).repr() + } else { + tcx.dcx().span_delayed_bug(item.span, "anonymous field inside non struct/union"); + tcx.repr_options_of_def(def_id.to_def_id()) + } } else { tcx.repr_options_of_def(def_id.to_def_id()) }; diff --git a/tests/ui/union/unnamed-fields/anon-struct-in-enum-issue-121446.rs b/tests/ui/union/unnamed-fields/anon-struct-in-enum-issue-121446.rs new file mode 100644 index 0000000000000..00f9bfd5cdff9 --- /dev/null +++ b/tests/ui/union/unnamed-fields/anon-struct-in-enum-issue-121446.rs @@ -0,0 +1,11 @@ +#![crate_type = "lib"] +#![feature(unnamed_fields)] +#![allow(unused, incomplete_features)] + +enum K { + M { + _ : struct { field: u8 }, + //~^ error: unnamed fields are not allowed outside of structs or unions + //~| error: anonymous structs are not allowed outside of unnamed struct or union fields + } +} diff --git a/tests/ui/union/unnamed-fields/anon-struct-in-enum-issue-121446.stderr b/tests/ui/union/unnamed-fields/anon-struct-in-enum-issue-121446.stderr new file mode 100644 index 0000000000000..43843141e2e7a --- /dev/null +++ b/tests/ui/union/unnamed-fields/anon-struct-in-enum-issue-121446.stderr @@ -0,0 +1,16 @@ +error: unnamed fields are not allowed outside of structs or unions + --> $DIR/anon-struct-in-enum-issue-121446.rs:7:9 + | +LL | _ : struct { field: u8 }, + | -^^^^^^^^^^^^^^^^^^^^^^^ + | | + | unnamed field declared here + +error: anonymous structs are not allowed outside of unnamed struct or union fields + --> $DIR/anon-struct-in-enum-issue-121446.rs:7:13 + | +LL | _ : struct { field: u8 }, + | ^^^^^^^^^^^^^^^^^^^^ anonymous struct declared here + +error: aborting due to 2 previous errors +