Skip to content

Commit

Permalink
Do not panic in ty::consts::Const::try_to_target_usize() in case of…
Browse files Browse the repository at this point in the history
… size mismatch

Fixes an ICE when we try to relate an array size of type u8 to usize
  • Loading branch information
gurry committed Aug 23, 2024
1 parent a32d4a0 commit ef1925a
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 10 deletions.
6 changes: 5 additions & 1 deletion compiler/rustc_middle/src/ty/consts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,11 @@ impl<'tcx> Const<'tcx> {

impl<'tcx> rustc_type_ir::inherent::Const<TyCtxt<'tcx>> for Const<'tcx> {
fn try_to_target_usize(self, interner: TyCtxt<'tcx>) -> Option<u64> {
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 {
Expand Down
9 changes: 0 additions & 9 deletions tests/crashes/126359.rs

This file was deleted.

14 changes: 14 additions & 0 deletions tests/ui/consts/ice-const-size-relate-126359.rs
Original file line number Diff line number Diff line change
@@ -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<const N: u8 = 3, T = u32> {
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
}
18 changes: 18 additions & 0 deletions tests/ui/consts/ice-const-size-relate-126359.stderr
Original file line number Diff line number Diff line change
@@ -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`.

0 comments on commit ef1925a

Please sign in to comment.