Skip to content

Commit f5c5423

Browse files
author
Ulrik Sverdrup
committed
typeck: Make sure casts from fat to thin pointers are illegal
Fixes an ICE on casting *const [T] to *const T and similar cases. Fixes #21397 Fixes #22955
1 parent 2568a4d commit f5c5423

File tree

2 files changed

+17
-5
lines changed

2 files changed

+17
-5
lines changed

src/librustc_typeck/check/cast.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -170,9 +170,9 @@ pub fn check_cast<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, cast: &CastCheck<'tcx>) {
170170
demand::coerce(fcx, e.span, t_1, &e);
171171
}
172172
}
173-
} else if fcx.type_is_fat_ptr(t_e, span) && !fcx.type_is_fat_ptr(t_1, span) {
173+
} else if fcx.type_is_fat_ptr(t_e, span) != fcx.type_is_fat_ptr(t_1, span) {
174174
fcx.type_error_message(span, |actual| {
175-
format!("illegal cast; cast from fat pointer: `{}` as `{}`",
175+
format!("illegal cast; cast between thin and fat pointer: `{}` as `{}`",
176176
actual, fcx.infcx().ty_to_string(t_1))
177177
}, t_e, None);
178178
} else if !(t_e_is_scalar && t_1_is_trivial) {

src/test/compile-fail/fat-ptr-cast.rs

+15-3
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,24 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010

11+
// Make sure casts between thin pointer <-> fat pointer are illegal.
12+
13+
pub trait Trait {}
14+
1115
fn main() {
1216
let a: &[i32] = &[1, 2, 3];
1317
let b: Box<[i32]> = Box::new([1, 2, 3]);
1418
let p = a as *const [i32];
19+
let q = a.as_ptr();
20+
21+
a as usize; //~ ERROR illegal cast
22+
b as usize; //~ ERROR illegal cast
23+
p as usize; //~ ERROR illegal cast
24+
25+
// #22955
26+
q as *const [i32]; //~ ERROR illegal cast
1527

16-
a as usize; //~ ERROR cast from fat pointer
17-
b as usize; //~ ERROR cast from fat pointer
18-
p as usize; //~ ERROR cast from fat pointer
28+
// #21397
29+
let t: *mut (Trait + 'static) = 0 as *mut _; //~ ERROR illegal cast
30+
let mut fail: *const str = 0 as *const str; //~ ERROR illegal cast
1931
}

0 commit comments

Comments
 (0)