Skip to content

Commit

Permalink
Rollup merge of #90910 - RalfJung:const-discriminant-empty-enum, r=pe…
Browse files Browse the repository at this point in the history
…trochenkov

fix getting the discriminant of a zero-variant enum

Fixes #89765
  • Loading branch information
workingjubilee authored Nov 15, 2021
2 parents b5bd3d1 + 9ec8862 commit 8e051de
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
4 changes: 3 additions & 1 deletion compiler/rustc_middle/src/ty/sty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2067,7 +2067,9 @@ impl<'tcx> TyS<'tcx> {
) -> Option<Discr<'tcx>> {
match self.kind() {
TyKind::Adt(adt, _) if adt.variants.is_empty() => {
bug!("discriminant_for_variant called on zero variant enum");
// This can actually happen during CTFE, see
// https://github.com/rust-lang/rust/issues/89765.
None
}
TyKind::Adt(adt, _) if adt.is_enum() => {
Some(adt.discriminant_for_variant(tcx, variant_index))
Expand Down
7 changes: 7 additions & 0 deletions src/test/ui/consts/const_discriminant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,13 @@ enum SingleVariant {

const TEST_V: Discriminant<SingleVariant> = discriminant(&SingleVariant::V);

pub const TEST_VOID: () = {
// This is UB, but CTFE does not check validity so it does not detect this.
// This is a regression test for https://github.com/rust-lang/rust/issues/89765.
unsafe { std::mem::discriminant(&*(&() as *const () as *const Void)); };
};


fn main() {
assert_eq!(TEST_A, TEST_A_OTHER);
assert_eq!(TEST_A, discriminant(black_box(&Test::A(17))));
Expand Down

0 comments on commit 8e051de

Please sign in to comment.