Skip to content

Commit ca15637

Browse files
committed
Reject casts to unsized types and suggest use of reference or box
This prevents ICEs or less helpful diagnostics if typeck proceeds further. Closes issue #17441
1 parent 34dfa45 commit ca15637

File tree

1 file changed

+31
-0
lines changed
  • src/librustc/middle/typeck/check

1 file changed

+31
-0
lines changed

src/librustc/middle/typeck/check/mod.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1405,6 +1405,37 @@ fn check_cast(fcx: &FnCtxt,
14051405
return
14061406
}
14071407

1408+
if !ty::type_is_sized(fcx.tcx(), t_1) {
1409+
let tstr = fcx.infcx().ty_to_string(t_1);
1410+
fcx.type_error_message(span, |actual| {
1411+
format!("cast to unsized type: `{}` as `{}`", actual, tstr)
1412+
}, t_e, None);
1413+
match ty::get(t_e).sty {
1414+
ty::ty_rptr(_, ty::mt { mutbl: mt, .. }) => {
1415+
let mtstr = match mt {
1416+
ast::MutMutable => "mut ",
1417+
ast::MutImmutable => ""
1418+
};
1419+
if ty::type_is_trait(t_1) {
1420+
span_note!(fcx.tcx().sess, t.span, "did you mean `&{}{}`?", mtstr, tstr);
1421+
} else {
1422+
span_note!(fcx.tcx().sess, span,
1423+
"consider using an implicit coercion to `&{}{}` instead",
1424+
mtstr, tstr);
1425+
}
1426+
}
1427+
ty::ty_uniq(..) => {
1428+
span_note!(fcx.tcx().sess, t.span, "did you mean `Box<{}>`?", tstr);
1429+
}
1430+
_ => {
1431+
span_note!(fcx.tcx().sess, e.span,
1432+
"consider using a box or reference as appropriate");
1433+
}
1434+
}
1435+
fcx.write_error(id);
1436+
return
1437+
}
1438+
14081439
if ty::type_is_trait(t_1) {
14091440
// This will be looked up later on.
14101441
vtable2::check_object_cast(fcx, cast_expr, e, t_1);

0 commit comments

Comments
 (0)