From f67d045b547204c39bf14be377a4967f3b632905 Mon Sep 17 00:00:00 2001 From: Gurinder Singh Date: Sun, 16 Jun 2024 16:37:16 +0530 Subject: [PATCH] Do not panic in `ty::consts::Const::try_to_target_usize()` in case of size mismatch Fixes an ICE when we try to relate an array size of type u8 to usize --- compiler/rustc_middle/src/ty/consts.rs | 6 +++++- .../ui/consts/ice-const-size-relate-126359.rs | 14 ++++++++++++++ .../consts/ice-const-size-relate-126359.stderr | 18 ++++++++++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 tests/ui/consts/ice-const-size-relate-126359.rs create mode 100644 tests/ui/consts/ice-const-size-relate-126359.stderr diff --git a/compiler/rustc_middle/src/ty/consts.rs b/compiler/rustc_middle/src/ty/consts.rs index 12f0c38b054a0..aaa2f3c9dc309 100644 --- a/compiler/rustc_middle/src/ty/consts.rs +++ b/compiler/rustc_middle/src/ty/consts.rs @@ -150,7 +150,11 @@ impl<'tcx> Const<'tcx> { impl<'tcx> rustc_type_ir::inherent::Const> for Const<'tcx> { fn try_to_target_usize(self, interner: TyCtxt<'tcx>) -> Option { - self.try_to_target_usize(interner) + let scalar = self.try_to_valtree()?.try_to_scalar_int()?; + if scalar.size() != interner.data_layout.pointer_size { + return None; + } + Some(scalar.to_target_usize(interner)) } fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferConst) -> Self { diff --git a/tests/ui/consts/ice-const-size-relate-126359.rs b/tests/ui/consts/ice-const-size-relate-126359.rs new file mode 100644 index 0000000000000..db09bd228b349 --- /dev/null +++ b/tests/ui/consts/ice-const-size-relate-126359.rs @@ -0,0 +1,14 @@ +// Regression test for ICE #126359 + +// Tests that there is no ICE when the generic const +// specifying the size of an array is of a non-usize type + +struct OppOrder { + arr: [T; N], // Array size is u8 instead of usize + //~^ ERROR mismatched types +} + +fn main() { + let _ = OppOrder::<3, u32> { arr: [0, 0, 0] }; + //~^ ERROR mismatched types +} diff --git a/tests/ui/consts/ice-const-size-relate-126359.stderr b/tests/ui/consts/ice-const-size-relate-126359.stderr new file mode 100644 index 0000000000000..b9c057b204472 --- /dev/null +++ b/tests/ui/consts/ice-const-size-relate-126359.stderr @@ -0,0 +1,18 @@ +error[E0308]: mismatched types + --> $DIR/ice-const-size-relate-126359.rs:12:39 + | +LL | let _ = OppOrder::<3, u32> { arr: [0, 0, 0] }; + | ^^^^^^^^^ expected `3`, found `3` + | + = note: expected array `[u32; 3]` + found array `[u32; 3]` + +error[E0308]: mismatched types + --> $DIR/ice-const-size-relate-126359.rs:7:14 + | +LL | arr: [T; N], // Array size is u8 instead of usize + | ^ expected `usize`, found `u8` + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0308`.