Skip to content

Commit d18b405

Browse files
committed
Check casts from fat pointer
1 parent f4c2228 commit d18b405

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

src/librustc_typeck/check/cast.rs

+5
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,11 @@ 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) {
174+
fcx.type_error_message(span, |actual| {
175+
format!("illegal cast; cast from fat pointer: `{}` as `{}`",
176+
actual, fcx.infcx().ty_to_string(t_1))
177+
}, t_e, None);
173178
} else if !(t_e_is_scalar && t_1_is_trivial) {
174179
/*
175180
If more type combinations should be supported than are

src/librustc_typeck/check/mod.rs

+10
Original file line numberDiff line numberDiff line change
@@ -1559,6 +1559,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
15591559
span)
15601560
}
15611561

1562+
pub fn type_is_fat_ptr(&self, ty: Ty<'tcx>, span: Span) -> bool {
1563+
match ty.sty {
1564+
ty::ty_ptr(ty::mt { ty: t, .. }) |
1565+
ty::ty_rptr(_, ty::mt { ty: t, .. }) => {
1566+
!self.type_is_known_to_be_sized(t, span)
1567+
}
1568+
_ => false
1569+
}
1570+
}
1571+
15621572
pub fn register_builtin_bound(&self,
15631573
ty: Ty<'tcx>,
15641574
builtin_bound: ty::BuiltinBound,

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

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
fn main() {
12+
let a: &[i32] = &[1, 2, 3];
13+
a as *const [i32] as usize; //~ ERROR cast from fat pointer
14+
}

0 commit comments

Comments
 (0)