Skip to content

Commit f67d045

Browse files
committed
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
1 parent f6b4b71 commit f67d045

File tree

3 files changed

+37
-1
lines changed

3 files changed

+37
-1
lines changed

compiler/rustc_middle/src/ty/consts.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,11 @@ impl<'tcx> Const<'tcx> {
150150

151151
impl<'tcx> rustc_type_ir::inherent::Const<TyCtxt<'tcx>> for Const<'tcx> {
152152
fn try_to_target_usize(self, interner: TyCtxt<'tcx>) -> Option<u64> {
153-
self.try_to_target_usize(interner)
153+
let scalar = self.try_to_valtree()?.try_to_scalar_int()?;
154+
if scalar.size() != interner.data_layout.pointer_size {
155+
return None;
156+
}
157+
Some(scalar.to_target_usize(interner))
154158
}
155159

156160
fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferConst) -> Self {
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// Regression test for ICE #126359
2+
3+
// Tests that there is no ICE when the generic const
4+
// specifying the size of an array is of a non-usize type
5+
6+
struct OppOrder<const N: u8 = 3, T = u32> {
7+
arr: [T; N], // Array size is u8 instead of usize
8+
//~^ ERROR mismatched types
9+
}
10+
11+
fn main() {
12+
let _ = OppOrder::<3, u32> { arr: [0, 0, 0] };
13+
//~^ ERROR mismatched types
14+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
error[E0308]: mismatched types
2+
--> $DIR/ice-const-size-relate-126359.rs:12:39
3+
|
4+
LL | let _ = OppOrder::<3, u32> { arr: [0, 0, 0] };
5+
| ^^^^^^^^^ expected `3`, found `3`
6+
|
7+
= note: expected array `[u32; 3]`
8+
found array `[u32; 3]`
9+
10+
error[E0308]: mismatched types
11+
--> $DIR/ice-const-size-relate-126359.rs:7:14
12+
|
13+
LL | arr: [T; N], // Array size is u8 instead of usize
14+
| ^ expected `usize`, found `u8`
15+
16+
error: aborting due to 2 previous errors
17+
18+
For more information about this error, try `rustc --explain E0308`.

0 commit comments

Comments
 (0)