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.
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.
11 //! Code for type-checking cast expressions.
13 //! A cast `e as U` is valid if one of the following holds:
14 //! * `e` has type `T` and `T` coerces to `U`; *coercion-cast*
15 //! * `e` has type `*T`, `U` is `*U_0`, and either `U_0: Sized` or
16 //! unsize_kind(`T`) = unsize_kind(`U_0`); *ptr-ptr-cast*
17 //! * `e` has type `*T` and `U` is a numeric type, while `T: Sized`; *ptr-addr-cast*
18 //! * `e` is an integer and `U` is `*U_0`, while `U_0: Sized`; *addr-ptr-cast*
19 //! * `e` has type `T` and `T` and `U` are any numeric types; *numeric-cast*
20 //! * `e` is a C-like enum and `U` is an integer type; *enum-cast*
21 //! * `e` has type `bool` or `char` and `U` is an integer; *prim-int-cast*
22 //! * `e` has type `u8` and `U` is `char`; *u8-char-cast*
23 //! * `e` has type `&[T; n]` and `U` is `*const T`; *array-ptr-cast*
24 //! * `e` is a function pointer type and `U` has type `*T`,
25 //! while `T: Sized`; *fptr-ptr-cast*
26 //! * `e` is a function pointer type and `U` is an integer; *fptr-addr-cast*
28 //! where `&.T` and `*T` are references of either mutability,
29 //! and where unsize_kind(`T`) is the kind of the unsize info
30 //! in `T` - the vtable for a trait definition (e.g. `fmt::Display` or
31 //! `Iterator`, not `Iterator<Item=u8>`) or a length (or `()` if `T: Sized`).
33 //! Note that lengths are not adjusted when casting raw slices -
34 //! `T: *const [u16] as *const [u8]` creates a slice that only includes
35 //! half of the original memory.
37 //! Casting is not transitive, that is, even if `e as U1 as U2` is a valid
38 //! expression, `e as U2` is not necessarily so (in fact it will only be valid if
39 //! `U1` coerces to `U2`).
41 use super::{Diverges, FnCtxt}
;
44 use hir
::def_id
::DefId
;
47 use rustc
::ty
::{self, Ty, TypeFoldable}
;
48 use rustc
::ty
::cast
::{CastKind, CastTy}
;
49 use rustc
::middle
::lang_items
;
52 use util
::common
::ErrorReported
;
54 /// Reifies a cast check to be checked once we have full type information for
55 /// a function context.
56 pub struct CastCheck
<'tcx
> {
57 expr
: &'tcx hir
::Expr
,
59 expr_diverges
: Diverges
,
65 /// The kind of the unsize info (length or vtable) - we only allow casts between
66 /// fat pointers if their unsize-infos have the same kind.
67 #[derive(Copy, Clone, PartialEq, Eq)]
68 enum UnsizeKind
<'tcx
> {
69 Vtable(Option
<DefId
>),
71 /// The unsize info of this projection
72 OfProjection(&'tcx ty
::ProjectionTy
<'tcx
>),
73 /// The unsize info of this parameter
74 OfParam(&'tcx ty
::ParamTy
),
77 impl<'a
, 'gcx
, 'tcx
> FnCtxt
<'a
, 'gcx
, 'tcx
> {
78 /// Returns the kind of unsize information of t, or None
79 /// if t is sized or it is unknown.
80 fn unsize_kind(&self, t
: Ty
<'tcx
>) -> Option
<UnsizeKind
<'tcx
>> {
82 ty
::TySlice(_
) | ty
::TyStr
=> Some(UnsizeKind
::Length
),
83 ty
::TyDynamic(ref tty
, ..) =>
84 Some(UnsizeKind
::Vtable(tty
.principal().map(|p
| p
.def_id()))),
85 ty
::TyAdt(def
, substs
) if def
.is_struct() => {
86 // FIXME(arielb1): do some kind of normalization
87 match def
.struct_variant().fields
.last() {
89 Some(f
) => self.unsize_kind(f
.ty(self.tcx
, substs
)),
92 // We should really try to normalize here.
93 ty
::TyProjection(ref pi
) => Some(UnsizeKind
::OfProjection(pi
)),
94 ty
::TyParam(ref p
) => Some(UnsizeKind
::OfParam(p
)),
100 #[derive(Copy, Clone)]
105 /// Cast of thin to fat raw ptr (eg. `*const () as *const [u8]`)
115 impl<'a
, 'gcx
, 'tcx
> CastCheck
<'tcx
> {
116 pub fn new(fcx
: &FnCtxt
<'a
, 'gcx
, 'tcx
>,
117 expr
: &'tcx hir
::Expr
,
119 expr_diverges
: Diverges
,
123 -> Result
<CastCheck
<'tcx
>, ErrorReported
> {
124 let check
= CastCheck
{
127 expr_diverges
: expr_diverges
,
129 cast_span
: cast_span
,
133 // For better error messages, check for some obviously unsized
134 // cases now. We do a more thorough check at the end, once
135 // inference is more completely known.
137 ty
::TyDynamic(..) | ty
::TySlice(..) => {
138 check
.report_cast_to_unsized_type(fcx
);
145 fn report_cast_error(&self, fcx
: &FnCtxt
<'a
, 'gcx
, 'tcx
>, e
: CastError
) {
147 CastError
::NeedDeref
=> {
148 let error_span
= self.span
;
149 let cast_ty
= fcx
.ty_to_string(self.cast_ty
);
150 let mut err
= fcx
.type_error_struct(error_span
,
152 format
!("casting `{}` as `{}` is invalid",
157 err
.span_label(error_span
,
158 &format
!("cannot cast `{}` as `{}`",
159 fcx
.ty_to_string(self.expr_ty
),
161 if let Ok(snippet
) = fcx
.sess().codemap().span_to_snippet(self.expr
.span
) {
162 err
.span_help(self.expr
.span
,
163 &format
!("did you mean `*{}`?", snippet
));
167 CastError
::NeedViaThinPtr
|
168 CastError
::NeedViaPtr
=> {
169 let mut err
= fcx
.type_error_struct(self.span
,
171 format
!("casting `{}` as `{}` is invalid",
173 fcx
.ty_to_string(self.cast_ty
))
176 if self.cast_ty
.is_uint() {
177 err
.help(&format
!("cast through {} first",
179 CastError
::NeedViaPtr
=> "a raw pointer",
180 CastError
::NeedViaThinPtr
=> "a thin pointer",
186 CastError
::NeedViaInt
=> {
187 fcx
.type_error_struct(self.span
,
189 format
!("casting `{}` as `{}` is invalid",
191 fcx
.ty_to_string(self.cast_ty
))
194 .help(&format
!("cast through {} first",
196 CastError
::NeedViaInt
=> "an integer",
201 CastError
::CastToBool
=> {
202 struct_span_err
!(fcx
.tcx
.sess
, self.span
, E0054
, "cannot cast as `bool`")
203 .span_label(self.span
, &format
!("unsupported cast"))
204 .help("compare with zero instead")
207 CastError
::CastToChar
=> {
208 fcx
.type_error_message(self.span
,
210 format
!("only `u8` can be cast as `char`, not `{}`",
215 CastError
::NonScalar
=> {
216 fcx
.type_error_message(self.span
,
218 format
!("non-scalar cast: `{}` as `{}`",
220 fcx
.ty_to_string(self.cast_ty
))
224 CastError
::IllegalCast
=> {
225 fcx
.type_error_message(self.span
,
227 format
!("casting `{}` as `{}` is invalid",
229 fcx
.ty_to_string(self.cast_ty
))
233 CastError
::SizedUnsizedCast
=> {
234 fcx
.type_error_message(self.span
,
236 format
!("cannot cast thin pointer `{}` to fat pointer \
239 fcx
.ty_to_string(self.cast_ty
))
243 CastError
::DifferingKinds
=> {
244 fcx
.type_error_struct(self.span
,
246 format
!("casting `{}` as `{}` is invalid",
248 fcx
.ty_to_string(self.cast_ty
))
251 .note("vtable kinds may not match")
257 fn report_cast_to_unsized_type(&self, fcx
: &FnCtxt
<'a
, 'gcx
, 'tcx
>) {
258 if self.cast_ty
.references_error() || self.expr_ty
.references_error() {
262 let tstr
= fcx
.ty_to_string(self.cast_ty
);
264 fcx
.type_error_struct(self.span
,
266 format
!("cast to unsized type: `{}` as `{}`", actual
, tstr
)
269 match self.expr_ty
.sty
{
270 ty
::TyRef(_
, ty
::TypeAndMut { mutbl: mt, .. }
) => {
271 let mtstr
= match mt
{
272 hir
::MutMutable
=> "mut ",
273 hir
::MutImmutable
=> "",
275 if self.cast_ty
.is_trait() {
276 match fcx
.tcx
.sess
.codemap().span_to_snippet(self.cast_span
) {
278 err
.span_suggestion(self.cast_span
,
279 "try casting to a reference instead:",
280 format
!("&{}{}", mtstr
, s
));
283 span_help
!(err
, self.cast_span
, "did you mean `&{}{}`?", mtstr
, tstr
)
289 "consider using an implicit coercion to `&{}{}` instead",
294 ty
::TyAdt(def
, ..) if def
.is_box() => {
295 match fcx
.tcx
.sess
.codemap().span_to_snippet(self.cast_span
) {
297 err
.span_suggestion(self.cast_span
,
298 "try casting to a `Box` instead:",
299 format
!("Box<{}>", s
));
301 Err(_
) => span_help
!(err
, self.cast_span
, "did you mean `Box<{}>`?", tstr
),
307 "consider using a box or reference as appropriate");
313 fn trivial_cast_lint(&self, fcx
: &FnCtxt
<'a
, 'gcx
, 'tcx
>) {
314 let t_cast
= self.cast_ty
;
315 let t_expr
= self.expr_ty
;
316 if t_cast
.is_numeric() && t_expr
.is_numeric() {
317 fcx
.tables
.borrow_mut().lints
.add_lint(
318 lint
::builtin
::TRIVIAL_NUMERIC_CASTS
,
321 format
!("trivial numeric cast: `{}` as `{}`. Cast can be \
322 replaced by coercion, this might require type \
323 ascription or a temporary variable",
324 fcx
.ty_to_string(t_expr
),
325 fcx
.ty_to_string(t_cast
)));
327 fcx
.tables
.borrow_mut().lints
.add_lint(
328 lint
::builtin
::TRIVIAL_CASTS
,
331 format
!("trivial cast: `{}` as `{}`. Cast can be \
332 replaced by coercion, this might require type \
333 ascription or a temporary variable",
334 fcx
.ty_to_string(t_expr
),
335 fcx
.ty_to_string(t_cast
)));
340 pub fn check(mut self, fcx
: &FnCtxt
<'a
, 'gcx
, 'tcx
>) {
341 self.expr_ty
= fcx
.structurally_resolved_type(self.span
, self.expr_ty
);
342 self.cast_ty
= fcx
.structurally_resolved_type(self.span
, self.cast_ty
);
344 debug
!("check_cast({}, {:?} as {:?})",
349 if !fcx
.type_is_known_to_be_sized(self.cast_ty
, self.span
) {
350 self.report_cast_to_unsized_type(fcx
);
351 } else if self.expr_ty
.references_error() || self.cast_ty
.references_error() {
352 // No sense in giving duplicate error messages
353 } else if self.try_coercion_cast(fcx
) {
354 self.trivial_cast_lint(fcx
);
355 debug
!(" -> CoercionCast");
356 fcx
.tables
.borrow_mut().cast_kinds
.insert(self.expr
.id
, CastKind
::CoercionCast
);
358 match self.do_check(fcx
) {
360 debug
!(" -> {:?}", k
);
361 fcx
.tables
.borrow_mut().cast_kinds
.insert(self.expr
.id
, k
);
363 Err(e
) => self.report_cast_error(fcx
, e
),
368 /// Check a cast, and report an error if one exists. In some cases, this
369 /// can return Ok and create type errors in the fcx rather than returning
370 /// directly. coercion-cast is handled in check instead of here.
371 fn do_check(&self, fcx
: &FnCtxt
<'a
, 'gcx
, 'tcx
>) -> Result
<CastKind
, CastError
> {
372 use rustc
::ty
::cast
::IntTy
::*;
373 use rustc
::ty
::cast
::CastTy
::*;
375 let (t_from
, t_cast
) = match (CastTy
::from_ty(self.expr_ty
),
376 CastTy
::from_ty(self.cast_ty
)) {
377 (Some(t_from
), Some(t_cast
)) => (t_from
, t_cast
),
378 // Function item types may need to be reified before casts.
379 (None
, Some(t_cast
)) => {
380 if let ty
::TyFnDef(.., f
) = self.expr_ty
.sty
{
381 // Attempt a coercion to a fn pointer type.
382 let res
= fcx
.try_coerce(self.expr
,
385 fcx
.tcx
.mk_fn_ptr(f
));
387 return Err(CastError
::NonScalar
);
391 return Err(CastError
::NonScalar
);
394 _
=> return Err(CastError
::NonScalar
),
397 match (t_from
, t_cast
) {
398 // These types have invariants! can't cast into them.
399 (_
, RPtr(_
)) | (_
, Int(CEnum
)) | (_
, FnPtr
) => Err(CastError
::NonScalar
),
402 (_
, Int(Bool
)) => Err(CastError
::CastToBool
),
405 (Int(U(ast
::UintTy
::U8
)), Int(Char
)) => Ok(CastKind
::U8CharCast
), // u8-char-cast
406 (_
, Int(Char
)) => Err(CastError
::CastToChar
),
410 (Int(CEnum
), Float
) |
411 (Int(Char
), Float
) => Err(CastError
::NeedViaInt
),
413 (Int(Bool
), Ptr(_
)) |
414 (Int(CEnum
), Ptr(_
)) |
415 (Int(Char
), Ptr(_
)) |
418 (Float
, Ptr(_
)) => Err(CastError
::IllegalCast
),
421 (Ptr(m_e
), Ptr(m_c
)) => self.check_ptr_ptr_cast(fcx
, m_e
, m_c
), // ptr-ptr-cast
422 (Ptr(m_expr
), Int(_
)) => self.check_ptr_addr_cast(fcx
, m_expr
), // ptr-addr-cast
423 (FnPtr
, Int(_
)) => Ok(CastKind
::FnPtrAddrCast
),
425 (RPtr(p
), Float
) => {
427 ty
::TypeVariants
::TyInt(_
) |
428 ty
::TypeVariants
::TyUint(_
) |
429 ty
::TypeVariants
::TyFloat(_
) => {
430 Err(CastError
::NeedDeref
)
432 ty
::TypeVariants
::TyInfer(t
) => {
434 ty
::InferTy
::IntVar(_
) |
435 ty
::InferTy
::FloatVar(_
) |
436 ty
::InferTy
::FreshIntTy(_
) |
437 ty
::InferTy
::FreshFloatTy(_
) => {
438 Err(CastError
::NeedDeref
)
440 _
=> Err(CastError
::NeedViaPtr
),
443 _
=> Err(CastError
::NeedViaPtr
),
447 (Int(_
), Ptr(mt
)) => self.check_addr_ptr_cast(fcx
, mt
), // addr-ptr-cast
448 (FnPtr
, Ptr(mt
)) => self.check_fptr_ptr_cast(fcx
, mt
),
449 (RPtr(rmt
), Ptr(mt
)) => self.check_ref_cast(fcx
, rmt
, mt
), // array-ptr-cast
452 (Int(CEnum
), Int(_
)) => Ok(CastKind
::EnumCast
),
453 (Int(Char
), Int(_
)) |
454 (Int(Bool
), Int(_
)) => Ok(CastKind
::PrimIntCast
),
456 (Int(_
), Int(_
)) | (Int(_
), Float
) | (Float
, Int(_
)) | (Float
, Float
) => {
457 Ok(CastKind
::NumericCast
)
462 fn check_ptr_ptr_cast(&self,
463 fcx
: &FnCtxt
<'a
, 'gcx
, 'tcx
>,
464 m_expr
: &'tcx ty
::TypeAndMut
<'tcx
>,
465 m_cast
: &'tcx ty
::TypeAndMut
<'tcx
>)
466 -> Result
<CastKind
, CastError
> {
467 debug
!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr
, m_cast
);
468 // ptr-ptr cast. vtables must match.
470 // Cast to sized is OK
471 if fcx
.type_is_known_to_be_sized(m_cast
.ty
, self.span
) {
472 return Ok(CastKind
::PtrPtrCast
);
475 // sized -> unsized? report invalid cast (don't complain about vtable kinds)
476 if fcx
.type_is_known_to_be_sized(m_expr
.ty
, self.span
) {
477 return Err(CastError
::SizedUnsizedCast
);
480 // vtable kinds must match
481 match (fcx
.unsize_kind(m_cast
.ty
), fcx
.unsize_kind(m_expr
.ty
)) {
482 (Some(a
), Some(b
)) if a
== b
=> Ok(CastKind
::PtrPtrCast
),
483 _
=> Err(CastError
::DifferingKinds
),
487 fn check_fptr_ptr_cast(&self,
488 fcx
: &FnCtxt
<'a
, 'gcx
, 'tcx
>,
489 m_cast
: &'tcx ty
::TypeAndMut
<'tcx
>)
490 -> Result
<CastKind
, CastError
> {
491 // fptr-ptr cast. must be to sized ptr
493 if fcx
.type_is_known_to_be_sized(m_cast
.ty
, self.span
) {
494 Ok(CastKind
::FnPtrPtrCast
)
496 Err(CastError
::IllegalCast
)
500 fn check_ptr_addr_cast(&self,
501 fcx
: &FnCtxt
<'a
, 'gcx
, 'tcx
>,
502 m_expr
: &'tcx ty
::TypeAndMut
<'tcx
>)
503 -> Result
<CastKind
, CastError
> {
504 // ptr-addr cast. must be from sized ptr
506 if fcx
.type_is_known_to_be_sized(m_expr
.ty
, self.span
) {
507 Ok(CastKind
::PtrAddrCast
)
509 Err(CastError
::NeedViaThinPtr
)
513 fn check_ref_cast(&self,
514 fcx
: &FnCtxt
<'a
, 'gcx
, 'tcx
>,
515 m_expr
: &'tcx ty
::TypeAndMut
<'tcx
>,
516 m_cast
: &'tcx ty
::TypeAndMut
<'tcx
>)
517 -> Result
<CastKind
, CastError
> {
520 if m_expr
.mutbl
== hir
::MutImmutable
&& m_cast
.mutbl
== hir
::MutImmutable
{
521 if let ty
::TyArray(ety
, _
) = m_expr
.ty
.sty
{
522 // Due to the limitations of LLVM global constants,
523 // region pointers end up pointing at copies of
524 // vector elements instead of the original values.
525 // To allow raw pointers to work correctly, we
526 // need to special-case obtaining a raw pointer
527 // from a region pointer to a vector.
529 // this will report a type mismatch if needed
530 fcx
.demand_eqtype(self.span
, ety
, m_cast
.ty
);
531 return Ok(CastKind
::ArrayPtrCast
);
535 Err(CastError
::IllegalCast
)
538 fn check_addr_ptr_cast(&self,
539 fcx
: &FnCtxt
<'a
, 'gcx
, 'tcx
>,
540 m_cast
: &'tcx ty
::TypeAndMut
<'tcx
>)
541 -> Result
<CastKind
, CastError
> {
542 // ptr-addr cast. pointer must be thin.
543 if fcx
.type_is_known_to_be_sized(m_cast
.ty
, self.span
) {
544 Ok(CastKind
::AddrPtrCast
)
546 Err(CastError
::IllegalCast
)
550 fn try_coercion_cast(&self, fcx
: &FnCtxt
<'a
, 'gcx
, 'tcx
>) -> bool
{
551 fcx
.try_coerce(self.expr
, self.expr_ty
, self.expr_diverges
, self.cast_ty
).is_ok()
555 impl<'a
, 'gcx
, 'tcx
> FnCtxt
<'a
, 'gcx
, 'tcx
> {
556 fn type_is_known_to_be_sized(&self, ty
: Ty
<'tcx
>, span
: Span
) -> bool
{
557 let lang_item
= self.tcx
.require_lang_item(lang_items
::SizedTraitLangItem
);
558 traits
::type_known_to_meet_bound(self, ty
, lang_item
, span
)