1 //! Code for type-checking cast expressions.
3 //! A cast `e as U` is valid if one of the following holds:
4 //! * `e` has type `T` and `T` coerces to `U`; *coercion-cast*
5 //! * `e` has type `*T`, `U` is `*U_0`, and either `U_0: Sized` or
6 //! pointer_kind(`T`) = pointer_kind(`U_0`); *ptr-ptr-cast*
7 //! * `e` has type `*T` and `U` is a numeric type, while `T: Sized`; *ptr-addr-cast*
8 //! * `e` is an integer and `U` is `*U_0`, while `U_0: Sized`; *addr-ptr-cast*
9 //! * `e` has type `T` and `T` and `U` are any numeric types; *numeric-cast*
10 //! * `e` is a C-like enum and `U` is an integer type; *enum-cast*
11 //! * `e` has type `bool` or `char` and `U` is an integer; *prim-int-cast*
12 //! * `e` has type `u8` and `U` is `char`; *u8-char-cast*
13 //! * `e` has type `&[T; n]` and `U` is `*const T`; *array-ptr-cast*
14 //! * `e` is a function pointer type and `U` has type `*T`,
15 //! while `T: Sized`; *fptr-ptr-cast*
16 //! * `e` is a function pointer type and `U` is an integer; *fptr-addr-cast*
18 //! where `&.T` and `*T` are references of either mutability,
19 //! and where pointer_kind(`T`) is the kind of the unsize info
20 //! in `T` - the vtable for a trait definition (e.g., `fmt::Display` or
21 //! `Iterator`, not `Iterator<Item=u8>`) or a length (or `()` if `T: Sized`).
23 //! Note that lengths are not adjusted when casting raw slices -
24 //! `T: *const [u16] as *const [u8]` creates a slice that only includes
25 //! half of the original memory.
27 //! Casting is not transitive, that is, even if `e as U1 as U2` is a valid
28 //! expression, `e as U2` is not necessarily so (in fact it will only be valid if
29 //! `U1` coerces to `U2`).
33 use crate::hir::def_id::DefId;
34 use crate::type_error_struct;
35 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, ErrorReported};
37 use rustc_hir::lang_items::LangItem;
38 use rustc_middle::mir::Mutability;
39 use rustc_middle::ty::adjustment::AllowTwoPhase;
40 use rustc_middle::ty::cast::{CastKind, CastTy};
41 use rustc_middle::ty::error::TypeError;
42 use rustc_middle::ty::subst::SubstsRef;
43 use rustc_middle::ty::{self, Ty, TypeAndMut, TypeFoldable};
44 use rustc_session::lint;
45 use rustc_session::Session;
46 use rustc_span::symbol::sym;
48 use rustc_trait_selection::infer::InferCtxtExt;
49 use rustc_trait_selection::traits;
50 use rustc_trait_selection::traits::error_reporting::report_object_safety_error;
52 /// Reifies a cast check to be checked once we have full type information for
53 /// a function context.
55 pub struct CastCheck<'tcx> {
56 expr: &'tcx hir::Expr<'tcx>,
63 /// The kind of pointer and associated metadata (thin, length or vtable) - we
64 /// only allow casts between fat pointers if their metadata have the same
66 #[derive(Copy, Clone, PartialEq, Eq)]
67 enum PointerKind<'tcx> {
68 /// No metadata attached, ie pointer to sized type or foreign type
71 Vtable(Option<DefId>),
74 /// The unsize info of this projection
75 OfProjection(&'tcx ty::ProjectionTy<'tcx>),
76 /// The unsize info of this opaque ty
77 OfOpaque(DefId, SubstsRef<'tcx>),
78 /// The unsize info of this parameter
79 OfParam(&'tcx ty::ParamTy),
82 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
83 /// Returns the kind of unsize information of t, or None
89 ) -> Result<Option<PointerKind<'tcx>>, ErrorReported> {
90 debug!("pointer_kind({:?}, {:?})", t, span);
92 let t = self.resolve_vars_if_possible(t);
94 if t.references_error() {
95 return Err(ErrorReported);
98 if self.type_is_known_to_be_sized_modulo_regions(t, span) {
99 return Ok(Some(PointerKind::Thin));
103 ty::Slice(_) | ty::Str => Some(PointerKind::Length),
104 ty::Dynamic(ref tty, ..) => Some(PointerKind::Vtable(tty.principal_def_id())),
105 ty::Adt(def, substs) if def.is_struct() => match def.non_enum_variant().fields.last() {
106 None => Some(PointerKind::Thin),
108 let field_ty = self.field_ty(span, f, substs);
109 self.pointer_kind(field_ty, span)?
112 ty::Tuple(fields) => match fields.last() {
113 None => Some(PointerKind::Thin),
114 Some(f) => self.pointer_kind(f.expect_ty(), span)?,
117 // Pointers to foreign types are thin, despite being unsized
118 ty::Foreign(..) => Some(PointerKind::Thin),
119 // We should really try to normalize here.
120 ty::Projection(ref pi) => Some(PointerKind::OfProjection(pi)),
121 ty::Opaque(def_id, substs) => Some(PointerKind::OfOpaque(def_id, substs)),
122 ty::Param(ref p) => Some(PointerKind::OfParam(p)),
123 // Insufficient type information.
124 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(_) => None,
132 | ty::GeneratorWitness(..)
144 .delay_span_bug(span, &format!("`{:?}` should be sized but is not?", t));
145 return Err(ErrorReported);
151 #[derive(Copy, Clone)]
158 /// Cast of thin to fat raw ptr (e.g., `*const () as *const [u8]`).
170 impl From<ErrorReported> for CastError {
171 fn from(ErrorReported: ErrorReported) -> Self {
172 CastError::ErrorReported
176 fn make_invalid_casting_error<'a, 'tcx>(
181 fcx: &FnCtxt<'a, 'tcx>,
182 ) -> DiagnosticBuilder<'a> {
188 "casting `{}` as `{}` is invalid",
189 fcx.ty_to_string(expr_ty),
190 fcx.ty_to_string(cast_ty)
194 impl<'a, 'tcx> CastCheck<'tcx> {
196 fcx: &FnCtxt<'a, 'tcx>,
197 expr: &'tcx hir::Expr<'tcx>,
202 ) -> Result<CastCheck<'tcx>, ErrorReported> {
203 let check = CastCheck { expr, expr_ty, cast_ty, cast_span, span };
205 // For better error messages, check for some obviously unsized
206 // cases now. We do a more thorough check at the end, once
207 // inference is more completely known.
208 match cast_ty.kind() {
209 ty::Dynamic(..) | ty::Slice(..) => {
210 check.report_cast_to_unsized_type(fcx);
217 fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError) {
219 CastError::ErrorReported => {
220 // an error has already been reported
222 CastError::NeedDeref => {
223 let error_span = self.span;
224 let mut err = make_invalid_casting_error(
231 let cast_ty = fcx.ty_to_string(self.cast_ty);
234 format!("cannot cast `{}` as `{}`", fcx.ty_to_string(self.expr_ty), cast_ty),
236 if let Ok(snippet) = fcx.sess().source_map().span_to_snippet(self.expr.span) {
239 "dereference the expression",
240 format!("*{}", snippet),
241 Applicability::MaybeIncorrect,
244 err.span_help(self.expr.span, "dereference the expression with `*`");
248 CastError::NeedViaThinPtr | CastError::NeedViaPtr => {
249 let mut err = make_invalid_casting_error(
256 if self.cast_ty.is_integral() {
258 "cast through {} first",
260 CastError::NeedViaPtr => "a raw pointer",
261 CastError::NeedViaThinPtr => "a thin pointer",
268 CastError::NeedViaInt => {
269 make_invalid_casting_error(
277 "cast through {} first",
279 CastError::NeedViaInt => "an integer",
285 CastError::IllegalCast => {
286 make_invalid_casting_error(
295 CastError::DifferingKinds => {
296 make_invalid_casting_error(
303 .note("vtable kinds may not match")
306 CastError::CastToBool => {
308 struct_span_err!(fcx.tcx.sess, self.span, E0054, "cannot cast as `bool`");
310 if self.expr_ty.is_numeric() {
311 match fcx.tcx.sess.source_map().span_to_snippet(self.expr.span) {
315 "compare with zero instead",
316 format!("{} != 0", snippet),
317 Applicability::MachineApplicable,
321 err.span_help(self.span, "compare with zero instead");
325 err.span_label(self.span, "unsupported cast");
330 CastError::CastToChar => {
331 let mut err = type_error_struct!(
336 "only `u8` can be cast as `char`, not `{}`",
339 err.span_label(self.span, "invalid cast");
340 if self.expr_ty.is_numeric() {
343 if self.expr_ty == fcx.tcx.types.i8 {
344 "try casting from `u8` instead"
345 } else if self.expr_ty == fcx.tcx.types.u32 {
346 "try `char::from_u32` instead"
348 "try `char::from_u32` instead (via a `u32`)"
354 CastError::NonScalar => {
355 let mut err = type_error_struct!(
360 "non-primitive cast: `{}` as `{}`",
362 fcx.ty_to_string(self.cast_ty)
365 let mut sugg_mutref = false;
366 if let ty::Ref(reg, cast_ty, mutbl) = *self.cast_ty.kind() {
367 if let ty::RawPtr(TypeAndMut { ty: expr_ty, .. }) = *self.expr_ty.kind() {
372 fcx.tcx.lifetimes.re_erased,
373 TypeAndMut { ty: expr_ty, mutbl },
381 sugg = Some((format!("&{}*", mutbl.prefix_str()), cast_ty == expr_ty));
383 } else if let ty::Ref(expr_reg, expr_ty, expr_mutbl) = *self.expr_ty.kind() {
384 if expr_mutbl == Mutability::Not
385 && mutbl == Mutability::Mut
391 TypeAndMut { ty: expr_ty, mutbl: Mutability::Mut },
408 fcx.tcx.mk_ref(reg, TypeAndMut { ty: self.expr_ty, mutbl }),
415 sugg = Some((format!("&{}", mutbl.prefix_str()), false));
417 } else if let ty::RawPtr(TypeAndMut { mutbl, .. }) = *self.cast_ty.kind() {
422 fcx.tcx.lifetimes.re_erased,
423 TypeAndMut { ty: self.expr_ty, mutbl },
431 sugg = Some((format!("&{}", mutbl.prefix_str()), false));
435 err.span_label(self.span, "invalid cast");
436 err.span_note(self.expr.span, "this reference is immutable");
437 err.span_note(self.cast_span, "trying to cast to a mutable reference type");
438 } else if let Some((sugg, remove_cast)) = sugg {
439 err.span_label(self.span, "invalid cast");
445 .span_to_snippet(self.expr.span)
446 .map_or(false, |snip| snip.starts_with('('));
448 // Very crude check to see whether the expression must be wrapped
449 // in parentheses for the suggestion to work (issue #89497).
450 // Can/should be extended in the future.
452 !has_parens && matches!(self.expr.kind, hir::ExprKind::Cast(..));
454 let mut suggestion = vec![(self.expr.span.shrink_to_lo(), sugg)];
456 suggestion[0].1 += "(";
457 suggestion.push((self.expr.span.shrink_to_hi(), ")".to_string()));
461 self.expr.span.shrink_to_hi().to(self.cast_span),
466 err.multipart_suggestion_verbose(
467 "consider borrowing the value",
469 Applicability::MachineApplicable,
473 ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..)
475 let mut label = true;
476 // Check `impl From<self.expr_ty> for self.cast_ty {}` for accurate suggestion:
477 if let Ok(snippet) = fcx.tcx.sess.source_map().span_to_snippet(self.expr.span) {
478 if let Some(from_trait) = fcx.tcx.get_diagnostic_item(sym::From) {
479 let ty = fcx.resolve_vars_if_possible(self.cast_ty);
480 // Erase regions to avoid panic in `prove_value` when calling
481 // `type_implements_trait`.
482 let ty = fcx.tcx.erase_regions(ty);
483 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
484 let expr_ty = fcx.tcx.erase_regions(expr_ty);
485 let ty_params = fcx.tcx.mk_substs_trait(expr_ty, &[]);
488 .type_implements_trait(from_trait, ty, ty_params, fcx.param_env)
489 .must_apply_modulo_regions()
494 "consider using the `From` trait instead",
495 format!("{}::from({})", self.cast_ty, snippet),
496 Applicability::MaybeIncorrect,
501 let msg = "an `as` expression can only be used to convert between primitive \
502 types or to coerce to a specific trait object";
504 err.span_label(self.span, msg);
509 err.span_label(self.span, "invalid cast");
513 CastError::SizedUnsizedCast => {
514 use crate::structured_errors::{SizedUnsizedCast, StructuredDiagnostic};
519 expr_ty: self.expr_ty,
520 cast_ty: fcx.ty_to_string(self.cast_ty),
525 CastError::UnknownCastPtrKind | CastError::UnknownExprPtrKind => {
526 let unknown_cast_to = match e {
527 CastError::UnknownCastPtrKind => true,
528 CastError::UnknownExprPtrKind => false,
531 let mut err = struct_span_err!(
533 if unknown_cast_to { self.cast_span } else { self.span },
535 "cannot cast {} a pointer of an unknown kind",
536 if unknown_cast_to { "to" } else { "from" }
539 err.span_label(self.cast_span, "needs more type information");
541 "the type information given here is insufficient to check whether \
542 the pointer cast is valid",
547 "the type information given here is insufficient to check whether \
548 the pointer cast is valid",
556 fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) {
557 if self.cast_ty.references_error() || self.expr_ty.references_error() {
561 let tstr = fcx.ty_to_string(self.cast_ty);
562 let mut err = type_error_struct!(
567 "cast to unsized type: `{}` as `{}`",
568 fcx.resolve_vars_if_possible(self.expr_ty),
571 match self.expr_ty.kind() {
572 ty::Ref(_, _, mt) => {
573 let mtstr = mt.prefix_str();
574 if self.cast_ty.is_trait() {
575 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
579 "try casting to a reference instead",
580 format!("&{}{}", mtstr, s),
581 Applicability::MachineApplicable,
585 let msg = &format!("did you mean `&{}{}`?", mtstr, tstr);
586 err.span_help(self.cast_span, msg);
591 "consider using an implicit coercion to `&{}{}` instead",
594 err.span_help(self.span, msg);
597 ty::Adt(def, ..) if def.is_box() => {
598 match fcx.tcx.sess.source_map().span_to_snippet(self.cast_span) {
602 "you can cast to a `Box` instead",
603 format!("Box<{}>", s),
604 Applicability::MachineApplicable,
610 &format!("you might have meant `Box<{}>`", tstr),
616 err.span_help(self.expr.span, "consider using a box or reference as appropriate");
622 fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
623 let t_cast = self.cast_ty;
624 let t_expr = self.expr_ty;
626 if fcx.tcx.features().type_ascription { "type ascription or " } else { "" };
627 let (adjective, lint) = if t_cast.is_numeric() && t_expr.is_numeric() {
628 ("numeric ", lint::builtin::TRIVIAL_NUMERIC_CASTS)
630 ("", lint::builtin::TRIVIAL_CASTS)
632 fcx.tcx.struct_span_lint_hir(lint, self.expr.hir_id, self.span, |err| {
634 "trivial {}cast: `{}` as `{}`",
636 fcx.ty_to_string(t_expr),
637 fcx.ty_to_string(t_cast)
640 "cast can be replaced by coercion; this might \
641 require {}a temporary variable",
648 #[instrument(skip(fcx), level = "debug")]
649 pub fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
650 self.expr_ty = fcx.structurally_resolved_type(self.expr.span, self.expr_ty);
651 self.cast_ty = fcx.structurally_resolved_type(self.cast_span, self.cast_ty);
653 debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);
655 if !fcx.type_is_known_to_be_sized_modulo_regions(self.cast_ty, self.span)
656 && !self.cast_ty.has_infer_types()
658 self.report_cast_to_unsized_type(fcx);
659 } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
660 // No sense in giving duplicate error messages
662 match self.try_coercion_cast(fcx) {
664 self.trivial_cast_lint(fcx);
665 debug!(" -> CoercionCast");
666 fcx.typeck_results.borrow_mut().set_coercion_cast(self.expr.hir_id.local_id);
668 Err(ty::error::TypeError::ObjectUnsafeCoercion(did)) => {
669 self.report_object_unsafe_cast(&fcx, did);
672 match self.do_check(fcx) {
674 debug!(" -> {:?}", k);
676 Err(e) => self.report_cast_error(fcx, e),
683 fn report_object_unsafe_cast(&self, fcx: &FnCtxt<'a, 'tcx>, did: DefId) {
684 let violations = fcx.tcx.object_safety_violations(did);
685 let mut err = report_object_safety_error(fcx.tcx, self.cast_span, did, violations);
686 err.note(&format!("required by cast to type '{}'", fcx.ty_to_string(self.cast_ty)));
690 /// Checks a cast, and report an error if one exists. In some cases, this
691 /// can return Ok and create type errors in the fcx rather than returning
692 /// directly. coercion-cast is handled in check instead of here.
693 pub fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError> {
694 use rustc_middle::ty::cast::CastTy::*;
695 use rustc_middle::ty::cast::IntTy::*;
697 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
699 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
700 // Function item types may need to be reified before casts.
701 (None, Some(t_cast)) => {
702 match *self.expr_ty.kind() {
704 // Attempt a coercion to a fn pointer type.
705 let f = fcx.normalize_associated_types_in(
707 self.expr_ty.fn_sig(fcx.tcx),
709 let res = fcx.try_coerce(
712 fcx.tcx.mk_fn_ptr(f),
716 if let Err(TypeError::IntrinsicCast) = res {
717 return Err(CastError::IllegalCast);
720 return Err(CastError::NonScalar);
724 // Special case some errors for references, and check for
725 // array-ptr-casts. `Ref` is not a CastTy because the cast
726 // is split into a coercion to a pointer type, followed by
728 ty::Ref(_, inner_ty, mutbl) => {
729 return match t_cast {
730 Int(_) | Float => match *inner_ty.kind() {
734 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) => {
735 Err(CastError::NeedDeref)
737 _ => Err(CastError::NeedViaPtr),
741 self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
743 _ => Err(CastError::NonScalar),
746 _ => return Err(CastError::NonScalar),
749 _ => return Err(CastError::NonScalar),
752 match (t_from, t_cast) {
753 // These types have invariants! can't cast into them.
754 (_, Int(CEnum) | FnPtr) => Err(CastError::NonScalar),
757 (_, Int(Bool)) => Err(CastError::CastToBool),
760 (Int(U(ty::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
761 (_, Int(Char)) => Err(CastError::CastToChar),
764 (Int(Bool) | Int(CEnum) | Int(Char), Float) => Err(CastError::NeedViaInt),
766 (Int(Bool) | Int(CEnum) | Int(Char) | Float, Ptr(_)) | (Ptr(_) | FnPtr, Float) => {
767 Err(CastError::IllegalCast)
771 (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
772 (Ptr(m_expr), Int(_)) => self.check_ptr_addr_cast(fcx, m_expr), // ptr-addr-cast
773 (FnPtr, Int(_)) => Ok(CastKind::FnPtrAddrCast),
776 (Int(_), Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt), // addr-ptr-cast
777 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
780 (Int(CEnum), Int(_)) => {
781 self.cenum_impl_drop_lint(fcx);
782 Ok(CastKind::EnumCast)
784 (Int(Char) | Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
786 (Int(_) | Float, Int(_) | Float) => Ok(CastKind::NumericCast),
790 fn check_ptr_ptr_cast(
792 fcx: &FnCtxt<'a, 'tcx>,
793 m_expr: ty::TypeAndMut<'tcx>,
794 m_cast: ty::TypeAndMut<'tcx>,
795 ) -> Result<CastKind, CastError> {
796 debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast);
797 // ptr-ptr cast. vtables must match.
799 let expr_kind = fcx.pointer_kind(m_expr.ty, self.span)?;
800 let cast_kind = fcx.pointer_kind(m_cast.ty, self.span)?;
802 let cast_kind = match cast_kind {
803 // We can't cast if target pointer kind is unknown
804 None => return Err(CastError::UnknownCastPtrKind),
805 Some(cast_kind) => cast_kind,
808 // Cast to thin pointer is OK
809 if cast_kind == PointerKind::Thin {
810 return Ok(CastKind::PtrPtrCast);
813 let expr_kind = match expr_kind {
814 // We can't cast to fat pointer if source pointer kind is unknown
815 None => return Err(CastError::UnknownExprPtrKind),
816 Some(expr_kind) => expr_kind,
819 // thin -> fat? report invalid cast (don't complain about vtable kinds)
820 if expr_kind == PointerKind::Thin {
821 return Err(CastError::SizedUnsizedCast);
824 // vtable kinds must match
825 if cast_kind == expr_kind {
826 Ok(CastKind::PtrPtrCast)
828 Err(CastError::DifferingKinds)
832 fn check_fptr_ptr_cast(
834 fcx: &FnCtxt<'a, 'tcx>,
835 m_cast: ty::TypeAndMut<'tcx>,
836 ) -> Result<CastKind, CastError> {
837 // fptr-ptr cast. must be to thin ptr
839 match fcx.pointer_kind(m_cast.ty, self.span)? {
840 None => Err(CastError::UnknownCastPtrKind),
841 Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
842 _ => Err(CastError::IllegalCast),
846 fn check_ptr_addr_cast(
848 fcx: &FnCtxt<'a, 'tcx>,
849 m_expr: ty::TypeAndMut<'tcx>,
850 ) -> Result<CastKind, CastError> {
851 // ptr-addr cast. must be from thin ptr
853 match fcx.pointer_kind(m_expr.ty, self.span)? {
854 None => Err(CastError::UnknownExprPtrKind),
855 Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
856 _ => Err(CastError::NeedViaThinPtr),
862 fcx: &FnCtxt<'a, 'tcx>,
863 m_expr: ty::TypeAndMut<'tcx>,
864 m_cast: ty::TypeAndMut<'tcx>,
865 ) -> Result<CastKind, CastError> {
866 // array-ptr-cast: allow mut-to-mut, mut-to-const, const-to-const
867 if m_expr.mutbl == hir::Mutability::Mut || m_cast.mutbl == hir::Mutability::Not {
868 if let ty::Array(ety, _) = m_expr.ty.kind() {
869 // Due to the limitations of LLVM global constants,
870 // region pointers end up pointing at copies of
871 // vector elements instead of the original values.
872 // To allow raw pointers to work correctly, we
873 // need to special-case obtaining a raw pointer
874 // from a region pointer to a vector.
876 // Coerce to a raw pointer so that we generate AddressOf in MIR.
877 let array_ptr_type = fcx.tcx.mk_ptr(m_expr);
878 fcx.try_coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No, None)
879 .unwrap_or_else(|_| {
881 "could not cast from reference to array to pointer to array ({:?} to {:?})",
887 // this will report a type mismatch if needed
888 fcx.demand_eqtype(self.span, *ety, m_cast.ty);
889 return Ok(CastKind::ArrayPtrCast);
893 Err(CastError::IllegalCast)
896 fn check_addr_ptr_cast(
898 fcx: &FnCtxt<'a, 'tcx>,
899 m_cast: TypeAndMut<'tcx>,
900 ) -> Result<CastKind, CastError> {
901 // ptr-addr cast. pointer must be thin.
902 match fcx.pointer_kind(m_cast.ty, self.span)? {
903 None => Err(CastError::UnknownCastPtrKind),
904 Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
905 _ => Err(CastError::IllegalCast),
909 fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'_>> {
910 match fcx.try_coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No, None) {
912 Err(err) => Err(err),
916 fn cenum_impl_drop_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
917 if let ty::Adt(d, _) = self.expr_ty.kind() {
918 if d.has_dtor(fcx.tcx) {
919 fcx.tcx.struct_span_lint_hir(
920 lint::builtin::CENUM_IMPL_DROP_CAST,
925 "cannot cast enum `{}` into integer `{}` because it implements `Drop`",
926 self.expr_ty, self.cast_ty
936 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
937 fn type_is_known_to_be_sized_modulo_regions(&self, ty: Ty<'tcx>, span: Span) -> bool {
938 let lang_item = self.tcx.require_lang_item(LangItem::Sized, None);
939 traits::type_known_to_meet_bound_modulo_regions(self, self.param_env, ty, lang_item, span)