Skip to content

Commit

Permalink
fix getting the discriminant of a zero-variant enum
Browse files Browse the repository at this point in the history
  • Loading branch information
RalfJung committed Nov 14, 2021
1 parent c8e9497 commit eebf676
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
4 changes: 3 additions & 1 deletion compiler/rustc_middle/src/ty/sty.rs
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
6 changes: 6 additions & 0 deletions src/test/ui/consts/const_discriminant.rs
Expand Up @@ -25,6 +25,12 @@ 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.
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 eebf676

Please sign in to comment.