1use rustc_ast::util::parser::ExprPrecedence;
32use rustc_data_structures::fx::FxHashSet;
33use rustc_errors::codes::*;
34use rustc_errors::{Applicability, Diag, ErrorGuaranteed};
35use rustc_hir::def_id::DefId;
36use rustc_hir::{self as hir, ExprKind};
37use rustc_infer::infer::DefineOpaqueTypes;
38use rustc_macros::{TypeFoldable, TypeVisitable};
39use rustc_middle::mir::Mutability;
40use rustc_middle::ty::adjustment::AllowTwoPhase;
41use rustc_middle::ty::cast::{CastKind, CastTy};
42use rustc_middle::ty::error::TypeError;
43use rustc_middle::ty::{self, Ty, TyCtxt, TypeAndMut, TypeVisitableExt, VariantDef, elaborate};
44use rustc_middle::{bug, span_bug};
45use rustc_session::lint;
46use rustc_span::{DUMMY_SP, Span, sym};
47use rustc_trait_selection::infer::InferCtxtExt;
48use tracing::{debug, instrument};
49
50use super::FnCtxt;
51use crate::{errors, type_error_struct};
52
53#[derive(Debug)]
56pub(crate) struct CastCheck<'tcx> {
57 expr: &'tcx hir::Expr<'tcx>,
59 expr_ty: Ty<'tcx>,
61 expr_span: Span,
62 cast_ty: Ty<'tcx>,
64 cast_span: Span,
65 span: Span,
66}
67
68#[derive(Debug, Copy, Clone, PartialEq, Eq, TypeVisitable, TypeFoldable)]
72enum PointerKind<'tcx> {
73 Thin,
75 VTable(&'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>),
77 Length,
79 OfAlias(ty::AliasTy<'tcx>),
81 OfParam(ty::ParamTy),
83}
84
85impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
86 fn pointer_kind(
89 &self,
90 t: Ty<'tcx>,
91 span: Span,
92 ) -> Result<Option<PointerKind<'tcx>>, ErrorGuaranteed> {
93 debug!("pointer_kind({:?}, {:?})", t, span);
94
95 let t = self.resolve_vars_if_possible(t);
96 t.error_reported()?;
97
98 if self.type_is_sized_modulo_regions(self.param_env, t) {
99 return Ok(Some(PointerKind::Thin));
100 }
101
102 let t = self.try_structurally_resolve_type(span, t);
103
104 Ok(match *t.kind() {
105 ty::Slice(_) | ty::Str => Some(PointerKind::Length),
106 ty::Dynamic(tty, _, ty::Dyn) => Some(PointerKind::VTable(tty)),
107 ty::Adt(def, args) if def.is_struct() => match def.non_enum_variant().tail_opt() {
108 None => Some(PointerKind::Thin),
109 Some(f) => {
110 let field_ty = self.field_ty(span, f, args);
111 self.pointer_kind(field_ty, span)?
112 }
113 },
114 ty::Tuple(fields) => match fields.last() {
115 None => Some(PointerKind::Thin),
116 Some(&f) => self.pointer_kind(f, span)?,
117 },
118
119 ty::UnsafeBinder(_) => todo!("FIXME(unsafe_binder)"),
120
121 ty::Foreign(..) => Some(PointerKind::Thin),
123 ty::Alias(_, pi) => Some(PointerKind::OfAlias(pi)),
125 ty::Param(p) => Some(PointerKind::OfParam(p)),
126 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(_) => None,
128
129 ty::Bool
130 | ty::Char
131 | ty::Int(..)
132 | ty::Uint(..)
133 | ty::Float(_)
134 | ty::Array(..)
135 | ty::CoroutineWitness(..)
136 | ty::RawPtr(_, _)
137 | ty::Ref(..)
138 | ty::Pat(..)
139 | ty::FnDef(..)
140 | ty::FnPtr(..)
141 | ty::Closure(..)
142 | ty::CoroutineClosure(..)
143 | ty::Coroutine(..)
144 | ty::Adt(..)
145 | ty::Never
146 | ty::Error(_) => {
147 let guar = self
148 .dcx()
149 .span_delayed_bug(span, format!("`{t:?}` should be sized but is not?"));
150 return Err(guar);
151 }
152 })
153 }
154}
155
156#[derive(Debug)]
157enum CastError<'tcx> {
158 ErrorGuaranteed(ErrorGuaranteed),
159
160 CastToBool,
161 CastToChar,
162 DifferingKinds {
163 src_kind: PointerKind<'tcx>,
164 dst_kind: PointerKind<'tcx>,
165 },
166 SizedUnsizedCast,
168 IllegalCast,
169 NeedDeref,
170 NeedViaPtr,
171 NeedViaThinPtr,
172 NeedViaInt,
173 NonScalar,
174 UnknownExprPtrKind,
175 UnknownCastPtrKind,
176 IntToWideCast(Option<&'static str>),
182 ForeignNonExhaustiveAdt,
183 PtrPtrAddingAutoTrait(Vec<DefId>),
184}
185
186impl From<ErrorGuaranteed> for CastError<'_> {
187 fn from(err: ErrorGuaranteed) -> Self {
188 CastError::ErrorGuaranteed(err)
189 }
190}
191
192fn make_invalid_casting_error<'a, 'tcx>(
193 span: Span,
194 expr_ty: Ty<'tcx>,
195 cast_ty: Ty<'tcx>,
196 fcx: &FnCtxt<'a, 'tcx>,
197) -> Diag<'a> {
198 type_error_struct!(
199 fcx.dcx(),
200 span,
201 expr_ty,
202 E0606,
203 "casting `{}` as `{}` is invalid",
204 fcx.ty_to_string(expr_ty),
205 fcx.ty_to_string(cast_ty)
206 )
207}
208
209pub fn check_cast<'tcx>(
214 tcx: TyCtxt<'tcx>,
215 param_env: ty::ParamEnv<'tcx>,
216 e: &'tcx hir::Expr<'tcx>,
217 from_ty: Ty<'tcx>,
218 to_ty: Ty<'tcx>,
219) -> Option<CastKind> {
220 let hir_id = e.hir_id;
221 let local_def_id = hir_id.owner.def_id;
222
223 let root_ctxt = crate::TypeckRootCtxt::new(tcx, local_def_id);
224 let fn_ctxt = FnCtxt::new(&root_ctxt, param_env, local_def_id);
225
226 if let Ok(check) = CastCheck::new(
227 &fn_ctxt, e, from_ty, to_ty,
228 DUMMY_SP, DUMMY_SP,
230 ) {
231 check.do_check(&fn_ctxt).ok()
232 } else {
233 None
234 }
235}
236
237impl<'a, 'tcx> CastCheck<'tcx> {
238 pub(crate) fn new(
239 fcx: &FnCtxt<'a, 'tcx>,
240 expr: &'tcx hir::Expr<'tcx>,
241 expr_ty: Ty<'tcx>,
242 cast_ty: Ty<'tcx>,
243 cast_span: Span,
244 span: Span,
245 ) -> Result<CastCheck<'tcx>, ErrorGuaranteed> {
246 let expr_span = expr.span.find_ancestor_inside(span).unwrap_or(expr.span);
247 let check = CastCheck { expr, expr_ty, expr_span, cast_ty, cast_span, span };
248
249 match cast_ty.kind() {
253 ty::Dynamic(_, _, ty::Dyn) | ty::Slice(..) => {
254 Err(check.report_cast_to_unsized_type(fcx))
255 }
256 _ => Ok(check),
257 }
258 }
259
260 fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError<'tcx>) {
261 match e {
262 CastError::ErrorGuaranteed(_) => {
263 }
265 CastError::NeedDeref => {
266 let mut err =
267 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
268
269 if matches!(self.expr.kind, ExprKind::AddrOf(..)) {
270 let span = self.expr_span.with_hi(self.expr.peel_borrows().span.lo());
272 err.span_suggestion_verbose(
273 span,
274 "remove the unneeded borrow",
275 "",
276 Applicability::MachineApplicable,
277 );
278 } else {
279 err.span_suggestion_verbose(
280 self.expr_span.shrink_to_lo(),
281 "dereference the expression",
282 "*",
283 Applicability::MachineApplicable,
284 );
285 }
286
287 err.emit();
288 }
289 CastError::NeedViaThinPtr | CastError::NeedViaPtr => {
290 let mut err =
291 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
292 if self.cast_ty.is_integral() {
293 err.help(format!("cast through {} first", match e {
294 CastError::NeedViaPtr => "a raw pointer",
295 CastError::NeedViaThinPtr => "a thin pointer",
296 e => unreachable!("control flow means we should never encounter a {e:?}"),
297 }));
298 }
299
300 self.try_suggest_collection_to_bool(fcx, &mut err);
301
302 err.emit();
303 }
304 CastError::NeedViaInt => {
305 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx)
306 .with_help("cast through an integer first")
307 .emit();
308 }
309 CastError::IllegalCast => {
310 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx).emit();
311 }
312 CastError::DifferingKinds { src_kind, dst_kind } => {
313 let mut err =
314 make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx);
315
316 match (src_kind, dst_kind) {
317 (PointerKind::VTable(_), PointerKind::VTable(_)) => {
318 err.note("the trait objects may have different vtables");
319 }
320 (
321 PointerKind::OfParam(_) | PointerKind::OfAlias(_),
322 PointerKind::OfParam(_)
323 | PointerKind::OfAlias(_)
324 | PointerKind::VTable(_)
325 | PointerKind::Length,
326 )
327 | (
328 PointerKind::VTable(_) | PointerKind::Length,
329 PointerKind::OfParam(_) | PointerKind::OfAlias(_),
330 ) => {
331 err.note("the pointers may have different metadata");
332 }
333 (PointerKind::VTable(_), PointerKind::Length)
334 | (PointerKind::Length, PointerKind::VTable(_)) => {
335 err.note("the pointers have different metadata");
336 }
337 (
338 PointerKind::Thin,
339 PointerKind::Thin
340 | PointerKind::VTable(_)
341 | PointerKind::Length
342 | PointerKind::OfParam(_)
343 | PointerKind::OfAlias(_),
344 )
345 | (
346 PointerKind::VTable(_)
347 | PointerKind::Length
348 | PointerKind::OfParam(_)
349 | PointerKind::OfAlias(_),
350 PointerKind::Thin,
351 )
352 | (PointerKind::Length, PointerKind::Length) => {
353 span_bug!(self.span, "unexpected cast error: {e:?}")
354 }
355 }
356
357 err.emit();
358 }
359 CastError::CastToBool => {
360 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
361 let help = if self.expr_ty.is_numeric() {
362 errors::CannotCastToBoolHelp::Numeric(
363 self.expr_span.shrink_to_hi().with_hi(self.span.hi()),
364 )
365 } else {
366 errors::CannotCastToBoolHelp::Unsupported(self.span)
367 };
368 fcx.dcx().emit_err(errors::CannotCastToBool { span: self.span, expr_ty, help });
369 }
370 CastError::CastToChar => {
371 let mut err = type_error_struct!(
372 fcx.dcx(),
373 self.span,
374 self.expr_ty,
375 E0604,
376 "only `u8` can be cast as `char`, not `{}`",
377 self.expr_ty
378 );
379 err.span_label(self.span, "invalid cast");
380 if self.expr_ty.is_numeric() {
381 if self.expr_ty == fcx.tcx.types.u32 {
382 err.multipart_suggestion(
383 "consider using `char::from_u32` instead",
384 vec![
385 (self.expr_span.shrink_to_lo(), "char::from_u32(".to_string()),
386 (self.expr_span.shrink_to_hi().to(self.cast_span), ")".to_string()),
387 ],
388 Applicability::MachineApplicable,
389 );
390 } else if self.expr_ty == fcx.tcx.types.i8 {
391 err.span_help(self.span, "consider casting from `u8` instead");
392 } else {
393 err.span_help(
394 self.span,
395 "consider using `char::from_u32` instead (via a `u32`)",
396 );
397 };
398 }
399 err.emit();
400 }
401 CastError::NonScalar => {
402 let mut err = type_error_struct!(
403 fcx.dcx(),
404 self.span,
405 self.expr_ty,
406 E0605,
407 "non-primitive cast: `{}` as `{}`",
408 self.expr_ty,
409 fcx.ty_to_string(self.cast_ty)
410 );
411
412 if let Ok(snippet) = fcx.tcx.sess.source_map().span_to_snippet(self.expr_span)
413 && matches!(self.expr.kind, ExprKind::AddrOf(..))
414 {
415 err.note(format!(
416 "casting reference expression `{}` because `&` binds tighter than `as`",
417 snippet
418 ));
419 }
420
421 let mut sugg = None;
422 let mut sugg_mutref = false;
423 if let ty::Ref(reg, cast_ty, mutbl) = *self.cast_ty.kind() {
424 if let ty::RawPtr(expr_ty, _) = *self.expr_ty.kind()
425 && fcx.may_coerce(
426 Ty::new_ref(fcx.tcx, fcx.tcx.lifetimes.re_erased, expr_ty, mutbl),
427 self.cast_ty,
428 )
429 {
430 sugg = Some((format!("&{}*", mutbl.prefix_str()), cast_ty == expr_ty));
431 } else if let ty::Ref(expr_reg, expr_ty, expr_mutbl) = *self.expr_ty.kind()
432 && expr_mutbl == Mutability::Not
433 && mutbl == Mutability::Mut
434 && fcx.may_coerce(Ty::new_mut_ref(fcx.tcx, expr_reg, expr_ty), self.cast_ty)
435 {
436 sugg_mutref = true;
437 }
438
439 if !sugg_mutref
440 && sugg == None
441 && fcx.may_coerce(
442 Ty::new_ref(fcx.tcx, reg, self.expr_ty, mutbl),
443 self.cast_ty,
444 )
445 {
446 sugg = Some((format!("&{}", mutbl.prefix_str()), false));
447 }
448 } else if let ty::RawPtr(_, mutbl) = *self.cast_ty.kind()
449 && fcx.may_coerce(
450 Ty::new_ref(fcx.tcx, fcx.tcx.lifetimes.re_erased, self.expr_ty, mutbl),
451 self.cast_ty,
452 )
453 {
454 sugg = Some((format!("&{}", mutbl.prefix_str()), false));
455 }
456 if sugg_mutref {
457 err.span_label(self.span, "invalid cast");
458 err.span_note(self.expr_span, "this reference is immutable");
459 err.span_note(self.cast_span, "trying to cast to a mutable reference type");
460 } else if let Some((sugg, remove_cast)) = sugg {
461 err.span_label(self.span, "invalid cast");
462
463 let has_parens = fcx
464 .tcx
465 .sess
466 .source_map()
467 .span_to_snippet(self.expr_span)
468 .is_ok_and(|snip| snip.starts_with('('));
469
470 let needs_parens =
474 !has_parens && matches!(self.expr.kind, hir::ExprKind::Cast(..));
475
476 let mut suggestion = vec![(self.expr_span.shrink_to_lo(), sugg)];
477 if needs_parens {
478 suggestion[0].1 += "(";
479 suggestion.push((self.expr_span.shrink_to_hi(), ")".to_string()));
480 }
481 if remove_cast {
482 suggestion.push((
483 self.expr_span.shrink_to_hi().to(self.cast_span),
484 String::new(),
485 ));
486 }
487
488 err.multipart_suggestion_verbose(
489 "consider borrowing the value",
490 suggestion,
491 Applicability::MachineApplicable,
492 );
493 } else if !matches!(
494 self.cast_ty.kind(),
495 ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..)
496 ) {
497 if let Some(from_trait) = fcx.tcx.get_diagnostic_item(sym::From) {
499 let ty = fcx.resolve_vars_if_possible(self.cast_ty);
500 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
501 if fcx
502 .infcx
503 .type_implements_trait(from_trait, [ty, expr_ty], fcx.param_env)
504 .must_apply_modulo_regions()
505 {
506 let to_ty = if let ty::Adt(def, args) = self.cast_ty.kind() {
507 fcx.tcx.value_path_str_with_args(def.did(), args)
508 } else {
509 self.cast_ty.to_string()
510 };
511 err.multipart_suggestion(
512 "consider using the `From` trait instead",
513 vec![
514 (self.expr_span.shrink_to_lo(), format!("{to_ty}::from(")),
515 (
516 self.expr_span.shrink_to_hi().to(self.cast_span),
517 ")".to_string(),
518 ),
519 ],
520 Applicability::MaybeIncorrect,
521 );
522 }
523 }
524
525 let (msg, note) = if let ty::Adt(adt, _) = self.expr_ty.kind()
526 && adt.is_enum()
527 && self.cast_ty.is_numeric()
528 {
529 (
530 "an `as` expression can be used to convert enum types to numeric \
531 types only if the enum type is unit-only or field-less",
532 Some(
533 "see https://doc.rust-lang.org/reference/items/enumerations.html#casting for more information",
534 ),
535 )
536 } else {
537 (
538 "an `as` expression can only be used to convert between primitive \
539 types or to coerce to a specific trait object",
540 None,
541 )
542 };
543
544 err.span_label(self.span, msg);
545
546 if let Some(note) = note {
547 err.note(note);
548 }
549 } else {
550 err.span_label(self.span, "invalid cast");
551 }
552
553 fcx.suggest_no_capture_closure(&mut err, self.cast_ty, self.expr_ty);
554 self.try_suggest_collection_to_bool(fcx, &mut err);
555
556 err.emit();
557 }
558 CastError::SizedUnsizedCast => {
559 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
560 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
561 fcx.dcx().emit_err(errors::CastThinPointerToWidePointer {
562 span: self.span,
563 expr_ty,
564 cast_ty,
565 teach: fcx.tcx.sess.teach(E0607),
566 });
567 }
568 CastError::IntToWideCast(known_metadata) => {
569 let expr_if_nightly = fcx.tcx.sess.is_nightly_build().then_some(self.expr_span);
570 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
571 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
572 let metadata = known_metadata.unwrap_or("type-specific metadata");
573 let known_wide = known_metadata.is_some();
574 let span = self.cast_span;
575 fcx.dcx().emit_err(errors::IntToWide {
576 span,
577 metadata,
578 expr_ty,
579 cast_ty,
580 expr_if_nightly,
581 known_wide,
582 });
583 }
584 CastError::UnknownCastPtrKind | CastError::UnknownExprPtrKind => {
585 let unknown_cast_to = match e {
586 CastError::UnknownCastPtrKind => true,
587 CastError::UnknownExprPtrKind => false,
588 e => unreachable!("control flow means we should never encounter a {e:?}"),
589 };
590 let (span, sub) = if unknown_cast_to {
591 (self.cast_span, errors::CastUnknownPointerSub::To(self.cast_span))
592 } else {
593 (self.cast_span, errors::CastUnknownPointerSub::From(self.span))
594 };
595 fcx.dcx().emit_err(errors::CastUnknownPointer { span, to: unknown_cast_to, sub });
596 }
597 CastError::ForeignNonExhaustiveAdt => {
598 make_invalid_casting_error(
599 self.span,
600 self.expr_ty,
601 self.cast_ty,
602 fcx,
603 )
604 .with_note("cannot cast an enum with a non-exhaustive variant when it's defined in another crate")
605 .emit();
606 }
607 CastError::PtrPtrAddingAutoTrait(added) => {
608 fcx.dcx().emit_err(errors::PtrCastAddAutoToObject {
609 span: self.span,
610 traits_len: added.len(),
611 traits: {
612 let mut traits: Vec<_> = added
613 .into_iter()
614 .map(|trait_did| fcx.tcx.def_path_str(trait_did))
615 .collect();
616
617 traits.sort();
618 traits.into()
619 },
620 });
621 }
622 }
623 }
624
625 fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'tcx>) -> ErrorGuaranteed {
626 if let Err(err) = self.cast_ty.error_reported() {
627 return err;
628 }
629 if let Err(err) = self.expr_ty.error_reported() {
630 return err;
631 }
632
633 let tstr = fcx.ty_to_string(self.cast_ty);
634 let mut err = type_error_struct!(
635 fcx.dcx(),
636 self.span,
637 self.expr_ty,
638 E0620,
639 "cast to unsized type: `{}` as `{}`",
640 fcx.resolve_vars_if_possible(self.expr_ty),
641 tstr
642 );
643 match self.expr_ty.kind() {
644 ty::Ref(_, _, mt) => {
645 let mtstr = mt.prefix_str();
646 err.span_suggestion_verbose(
647 self.cast_span.shrink_to_lo(),
648 "consider casting to a reference instead",
649 format!("&{mtstr}"),
650 Applicability::MachineApplicable,
651 );
652 }
653 ty::Adt(def, ..) if def.is_box() => {
654 err.multipart_suggestion(
655 "you can cast to a `Box` instead",
656 vec![
657 (self.cast_span.shrink_to_lo(), "Box<".to_string()),
658 (self.cast_span.shrink_to_hi(), ">".to_string()),
659 ],
660 Applicability::MachineApplicable,
661 );
662 }
663 _ => {
664 err.span_help(self.expr_span, "consider using a box or reference as appropriate");
665 }
666 }
667 err.emit()
668 }
669
670 fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
671 let (numeric, lint) = if self.cast_ty.is_numeric() && self.expr_ty.is_numeric() {
672 (true, lint::builtin::TRIVIAL_NUMERIC_CASTS)
673 } else {
674 (false, lint::builtin::TRIVIAL_CASTS)
675 };
676 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
677 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
678 fcx.tcx.emit_node_span_lint(
679 lint,
680 self.expr.hir_id,
681 self.span,
682 errors::TrivialCast { numeric, expr_ty, cast_ty },
683 );
684 }
685
686 #[instrument(skip(fcx), level = "debug")]
687 pub(crate) fn check(mut self, fcx: &FnCtxt<'a, 'tcx>) {
688 self.expr_ty = fcx.structurally_resolve_type(self.expr_span, self.expr_ty);
689 self.cast_ty = fcx.structurally_resolve_type(self.cast_span, self.cast_ty);
690
691 debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);
692
693 if !fcx.type_is_sized_modulo_regions(fcx.param_env, self.cast_ty)
694 && !self.cast_ty.has_infer_types()
695 {
696 self.report_cast_to_unsized_type(fcx);
697 } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
698 } else {
700 match self.try_coercion_cast(fcx) {
701 Ok(()) => {
702 if self.expr_ty.is_raw_ptr() && self.cast_ty.is_raw_ptr() {
703 debug!(" -> PointerCast");
710 } else {
711 self.trivial_cast_lint(fcx);
712 debug!(" -> CoercionCast");
713 fcx.typeck_results
714 .borrow_mut()
715 .set_coercion_cast(self.expr.hir_id.local_id);
716 }
717 }
718 Err(_) => {
719 match self.do_check(fcx) {
720 Ok(k) => {
721 debug!(" -> {:?}", k);
722 }
723 Err(e) => self.report_cast_error(fcx, e),
724 };
725 }
726 };
727 }
728 }
729 fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError<'tcx>> {
733 use rustc_middle::ty::cast::CastTy::*;
734 use rustc_middle::ty::cast::IntTy::*;
735
736 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty))
737 {
738 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
739 (None, Some(t_cast)) => {
741 match *self.expr_ty.kind() {
742 ty::FnDef(..) => {
743 let f = fcx.normalize(self.expr_span, self.expr_ty.fn_sig(fcx.tcx));
745 let res = fcx.coerce(
746 self.expr,
747 self.expr_ty,
748 Ty::new_fn_ptr(fcx.tcx, f),
749 AllowTwoPhase::No,
750 None,
751 );
752 if let Err(TypeError::IntrinsicCast) = res {
753 return Err(CastError::IllegalCast);
754 }
755 if res.is_err() {
756 return Err(CastError::NonScalar);
757 }
758 (FnPtr, t_cast)
759 }
760 ty::Ref(_, inner_ty, mutbl) => {
765 return match t_cast {
766 Int(_) | Float => match *inner_ty.kind() {
767 ty::Int(_)
768 | ty::Uint(_)
769 | ty::Float(_)
770 | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) => {
771 Err(CastError::NeedDeref)
772 }
773 _ => Err(CastError::NeedViaPtr),
774 },
775 Ptr(mt) => {
777 if !fcx.type_is_sized_modulo_regions(fcx.param_env, mt.ty) {
778 return Err(CastError::IllegalCast);
779 }
780 self.check_ref_cast(fcx, TypeAndMut { mutbl, ty: inner_ty }, mt)
781 }
782 _ => Err(CastError::NonScalar),
783 };
784 }
785 _ => return Err(CastError::NonScalar),
786 }
787 }
788 _ => return Err(CastError::NonScalar),
789 };
790 if let ty::Adt(adt_def, _) = *self.expr_ty.kind()
791 && !adt_def.did().is_local()
792 && adt_def.variants().iter().any(VariantDef::is_field_list_non_exhaustive)
793 {
794 return Err(CastError::ForeignNonExhaustiveAdt);
795 }
796 match (t_from, t_cast) {
797 (_, Int(CEnum) | FnPtr) => Err(CastError::NonScalar),
799
800 (_, Int(Bool)) => Err(CastError::CastToBool),
802
803 (Int(U(ty::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), (_, Int(Char)) => Err(CastError::CastToChar),
806
807 (Int(Bool) | Int(CEnum) | Int(Char), Float) => Err(CastError::NeedViaInt),
809
810 (Int(Bool) | Int(CEnum) | Int(Char) | Float, Ptr(_)) | (Ptr(_) | FnPtr, Float) => {
811 Err(CastError::IllegalCast)
812 }
813
814 (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), (Ptr(m_expr), Int(t_c)) => {
819 self.lossy_provenance_ptr2int_lint(fcx, t_c);
820 self.check_ptr_addr_cast(fcx, m_expr)
821 }
822 (FnPtr, Int(_)) => {
823 Ok(CastKind::FnPtrAddrCast)
825 }
826 (Int(_), Ptr(mt)) => {
828 self.fuzzy_provenance_int2ptr_lint(fcx);
829 self.check_addr_ptr_cast(fcx, mt)
830 }
831 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
833
834 (Int(CEnum), Int(_)) => {
836 self.err_if_cenum_impl_drop(fcx);
837 Ok(CastKind::EnumCast)
838 }
839 (Int(Char) | Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
840
841 (Int(_) | Float, Int(_) | Float) => Ok(CastKind::NumericCast),
842 }
843 }
844
845 fn check_ptr_ptr_cast(
846 &self,
847 fcx: &FnCtxt<'a, 'tcx>,
848 m_src: ty::TypeAndMut<'tcx>,
849 m_dst: ty::TypeAndMut<'tcx>,
850 ) -> Result<CastKind, CastError<'tcx>> {
851 debug!("check_ptr_ptr_cast m_src={m_src:?} m_dst={m_dst:?}");
852 let src_kind = fcx.tcx.erase_regions(fcx.pointer_kind(m_src.ty, self.span)?);
855 let dst_kind = fcx.tcx.erase_regions(fcx.pointer_kind(m_dst.ty, self.span)?);
856
857 let Some(dst_kind) = dst_kind else {
859 return Err(CastError::UnknownCastPtrKind);
860 };
861
862 if dst_kind == PointerKind::Thin {
864 return Ok(CastKind::PtrPtrCast);
865 }
866
867 let Some(src_kind) = src_kind else {
869 return Err(CastError::UnknownCastPtrKind);
870 };
871
872 match (src_kind, dst_kind) {
873 (PointerKind::Thin, _) => Err(CastError::SizedUnsizedCast),
875
876 (PointerKind::VTable(src_tty), PointerKind::VTable(dst_tty)) => {
878 match (src_tty.principal(), dst_tty.principal()) {
879 (Some(src_principal), Some(_)) => {
888 let tcx = fcx.tcx;
889
890 let src_obj = Ty::new_dynamic(
898 tcx,
899 tcx.mk_poly_existential_predicates(
900 &src_tty.without_auto_traits().collect::<Vec<_>>(),
901 ),
902 tcx.lifetimes.re_erased,
903 ty::Dyn,
904 );
905 let dst_obj = Ty::new_dynamic(
906 tcx,
907 tcx.mk_poly_existential_predicates(
908 &dst_tty.without_auto_traits().collect::<Vec<_>>(),
909 ),
910 tcx.lifetimes.re_erased,
911 ty::Dyn,
912 );
913
914 let cause = fcx.misc(self.span);
917 if fcx
918 .at(&cause, fcx.param_env)
919 .eq(DefineOpaqueTypes::Yes, src_obj, dst_obj)
920 .map(|infer_ok| fcx.register_infer_ok_obligations(infer_ok))
921 .is_err()
922 {
923 return Err(CastError::DifferingKinds { src_kind, dst_kind });
924 }
925
926 let src_auto: FxHashSet<_> = src_tty
929 .auto_traits()
930 .chain(
931 elaborate::supertrait_def_ids(tcx, src_principal.def_id())
932 .filter(|def_id| tcx.trait_is_auto(*def_id)),
933 )
934 .collect();
935
936 let added = dst_tty
937 .auto_traits()
938 .filter(|trait_did| !src_auto.contains(trait_did))
939 .collect::<Vec<_>>();
940
941 if !added.is_empty() {
942 return Err(CastError::PtrPtrAddingAutoTrait(added));
943 }
944
945 Ok(CastKind::PtrPtrCast)
946 }
947
948 (None, None) => Ok(CastKind::PtrPtrCast),
950
951 (Some(_), None) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
981
982 (None, Some(_)) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
984 }
985 }
986
987 (src_kind, dst_kind) if src_kind == dst_kind => Ok(CastKind::PtrPtrCast),
989
990 (_, _) => Err(CastError::DifferingKinds { src_kind, dst_kind }),
991 }
992 }
993
994 fn check_fptr_ptr_cast(
995 &self,
996 fcx: &FnCtxt<'a, 'tcx>,
997 m_cast: ty::TypeAndMut<'tcx>,
998 ) -> Result<CastKind, CastError<'tcx>> {
999 match fcx.pointer_kind(m_cast.ty, self.span)? {
1002 None => Err(CastError::UnknownCastPtrKind),
1003 Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
1004 _ => Err(CastError::IllegalCast),
1005 }
1006 }
1007
1008 fn check_ptr_addr_cast(
1009 &self,
1010 fcx: &FnCtxt<'a, 'tcx>,
1011 m_expr: ty::TypeAndMut<'tcx>,
1012 ) -> Result<CastKind, CastError<'tcx>> {
1013 match fcx.pointer_kind(m_expr.ty, self.span)? {
1016 None => Err(CastError::UnknownExprPtrKind),
1017 Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
1018 _ => Err(CastError::NeedViaThinPtr),
1019 }
1020 }
1021
1022 fn check_ref_cast(
1023 &self,
1024 fcx: &FnCtxt<'a, 'tcx>,
1025 mut m_expr: ty::TypeAndMut<'tcx>,
1026 mut m_cast: ty::TypeAndMut<'tcx>,
1027 ) -> Result<CastKind, CastError<'tcx>> {
1028 m_expr.ty = fcx.try_structurally_resolve_type(self.expr_span, m_expr.ty);
1030 m_cast.ty = fcx.try_structurally_resolve_type(self.cast_span, m_cast.ty);
1031
1032 if m_expr.mutbl >= m_cast.mutbl
1033 && let ty::Array(ety, _) = m_expr.ty.kind()
1034 && fcx.can_eq(fcx.param_env, *ety, m_cast.ty)
1035 {
1036 let array_ptr_type = Ty::new_ptr(fcx.tcx, m_expr.ty, m_expr.mutbl);
1041 fcx.coerce(self.expr, self.expr_ty, array_ptr_type, AllowTwoPhase::No, None)
1042 .unwrap_or_else(|_| {
1043 bug!(
1044 "could not cast from reference to array to pointer to array ({:?} to {:?})",
1045 self.expr_ty,
1046 array_ptr_type,
1047 )
1048 });
1049
1050 fcx.demand_eqtype(self.span, *ety, m_cast.ty);
1052 return Ok(CastKind::ArrayPtrCast);
1053 }
1054
1055 Err(CastError::IllegalCast)
1056 }
1057
1058 fn check_addr_ptr_cast(
1059 &self,
1060 fcx: &FnCtxt<'a, 'tcx>,
1061 m_cast: TypeAndMut<'tcx>,
1062 ) -> Result<CastKind, CastError<'tcx>> {
1063 match fcx.pointer_kind(m_cast.ty, self.span)? {
1065 None => Err(CastError::UnknownCastPtrKind),
1066 Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
1067 Some(PointerKind::VTable(_)) => Err(CastError::IntToWideCast(Some("a vtable"))),
1068 Some(PointerKind::Length) => Err(CastError::IntToWideCast(Some("a length"))),
1069 Some(PointerKind::OfAlias(_) | PointerKind::OfParam(_)) => {
1070 Err(CastError::IntToWideCast(None))
1071 }
1072 }
1073 }
1074
1075 fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<(), ty::error::TypeError<'tcx>> {
1076 match fcx.coerce(self.expr, self.expr_ty, self.cast_ty, AllowTwoPhase::No, None) {
1077 Ok(_) => Ok(()),
1078 Err(err) => Err(err),
1079 }
1080 }
1081
1082 fn err_if_cenum_impl_drop(&self, fcx: &FnCtxt<'a, 'tcx>) {
1083 if let ty::Adt(d, _) = self.expr_ty.kind()
1084 && d.has_dtor(fcx.tcx)
1085 {
1086 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
1087 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
1088
1089 fcx.dcx().emit_err(errors::CastEnumDrop { span: self.span, expr_ty, cast_ty });
1090 }
1091 }
1092
1093 fn lossy_provenance_ptr2int_lint(&self, fcx: &FnCtxt<'a, 'tcx>, t_c: ty::cast::IntTy) {
1094 let expr_prec = fcx.precedence(self.expr);
1095 let needs_parens = expr_prec < ExprPrecedence::Unambiguous;
1096
1097 let needs_cast = !matches!(t_c, ty::cast::IntTy::U(ty::UintTy::Usize));
1098 let cast_span = self.expr_span.shrink_to_hi().to(self.cast_span);
1099 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
1100 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
1101 let expr_span = self.expr_span.shrink_to_lo();
1102 let sugg = match (needs_parens, needs_cast) {
1103 (true, true) => errors::LossyProvenancePtr2IntSuggestion::NeedsParensCast {
1104 expr_span,
1105 cast_span,
1106 cast_ty,
1107 },
1108 (true, false) => {
1109 errors::LossyProvenancePtr2IntSuggestion::NeedsParens { expr_span, cast_span }
1110 }
1111 (false, true) => {
1112 errors::LossyProvenancePtr2IntSuggestion::NeedsCast { cast_span, cast_ty }
1113 }
1114 (false, false) => errors::LossyProvenancePtr2IntSuggestion::Other { cast_span },
1115 };
1116
1117 let lint = errors::LossyProvenancePtr2Int { expr_ty, cast_ty, sugg };
1118 fcx.tcx.emit_node_span_lint(
1119 lint::builtin::LOSSY_PROVENANCE_CASTS,
1120 self.expr.hir_id,
1121 self.span,
1122 lint,
1123 );
1124 }
1125
1126 fn fuzzy_provenance_int2ptr_lint(&self, fcx: &FnCtxt<'a, 'tcx>) {
1127 let sugg = errors::LossyProvenanceInt2PtrSuggestion {
1128 lo: self.expr_span.shrink_to_lo(),
1129 hi: self.expr_span.shrink_to_hi().to(self.cast_span),
1130 };
1131 let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty);
1132 let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty);
1133 let lint = errors::LossyProvenanceInt2Ptr { expr_ty, cast_ty, sugg };
1134 fcx.tcx.emit_node_span_lint(
1135 lint::builtin::FUZZY_PROVENANCE_CASTS,
1136 self.expr.hir_id,
1137 self.span,
1138 lint,
1139 );
1140 }
1141
1142 fn try_suggest_collection_to_bool(&self, fcx: &FnCtxt<'a, 'tcx>, err: &mut Diag<'_>) {
1145 if self.cast_ty.is_bool() {
1146 let derefed = fcx
1147 .autoderef(self.expr_span, self.expr_ty)
1148 .silence_errors()
1149 .find(|t| matches!(t.0.kind(), ty::Str | ty::Slice(..)));
1150
1151 if let Some((deref_ty, _)) = derefed {
1152 if deref_ty != self.expr_ty.peel_refs() {
1154 err.subdiagnostic(errors::DerefImplsIsEmpty { span: self.expr_span, deref_ty });
1155 }
1156
1157 err.subdiagnostic(errors::UseIsEmpty {
1160 lo: self.expr_span.shrink_to_lo(),
1161 hi: self.span.with_lo(self.expr_span.hi()),
1162 expr_ty: self.expr_ty,
1163 });
1164 }
1165 }
1166 }
1167}