Rollup merge of #90910 - RalfJung:const-discriminant-empty-enum, r=petrochenkov

fix getting the discriminant of a zero-variant enum

Fixes https://github.com/rust-lang/rust/issues/89765
This commit is contained in:
Yuki Okushi 2021-11-16 15:59:41 +09:00 committed by GitHub
commit 6d9c3a1b97
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 10 additions and 1 deletions

View file

@ -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))

View file

@ -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))));