|
| 1 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 2 | +use clippy_utils::source::snippet; |
| 3 | +use clippy_utils::sym; |
| 4 | +use rustc_errors::Applicability; |
| 5 | +use rustc_hir::{Expr, ExprKind}; |
| 6 | +use rustc_lint::{LateContext, LateLintPass}; |
| 7 | +use rustc_middle::ty::{self, ExistentialPredicate, Ty, TyCtxt}; |
| 8 | +use rustc_session::declare_lint_pass; |
| 9 | + |
| 10 | +declare_clippy_lint! { |
| 11 | + /// ### What it does |
| 12 | + /// |
| 13 | + /// Protects against unintended coercion of references to container types to `&dyn Any` when the |
| 14 | + /// container type dereferences to a `dyn Any` which could be directly referenced instead. |
| 15 | + /// |
| 16 | + /// ### Why is this bad? |
| 17 | + /// |
| 18 | + /// The intention is usually to get a reference to the `dyn Any` the value dereferences to, |
| 19 | + /// rather than coercing a reference to the container itself to `&dyn Any`. |
| 20 | + /// |
| 21 | + /// ### Example |
| 22 | + /// |
| 23 | + /// Because `Box<dyn Any>` itself implements `Any`, `&Box<dyn Any>` |
| 24 | + /// can be coerced to an `&dyn Any` which refers to *the `Box` itself*, rather than the |
| 25 | + /// inner `dyn Any`. |
| 26 | + /// ```no_run |
| 27 | + /// # use std::any::Any; |
| 28 | + /// let x: Box<dyn Any> = Box::new(0u32); |
| 29 | + /// let dyn_any_of_box: &dyn Any = &x; |
| 30 | + /// |
| 31 | + /// // Fails as we have a &dyn Any to the Box, not the u32 |
| 32 | + /// assert_eq!(dyn_any_of_box.downcast_ref::<u32>(), None); |
| 33 | + /// ``` |
| 34 | + /// Use instead: |
| 35 | + /// ```no_run |
| 36 | + /// # use std::any::Any; |
| 37 | + /// let x: Box<dyn Any> = Box::new(0u32); |
| 38 | + /// let dyn_any_of_u32: &dyn Any = &*x; |
| 39 | + /// |
| 40 | + /// // Succeeds since we have a &dyn Any to the inner u32! |
| 41 | + /// assert_eq!(dyn_any_of_u32.downcast_ref::<u32>(), Some(&0u32)); |
| 42 | + /// ``` |
| 43 | + #[clippy::version = "1.88.0"] |
| 44 | + pub COERCE_CONTAINER_TO_ANY, |
| 45 | + suspicious, |
| 46 | + "coercing to `&dyn Any` when dereferencing could produce a `dyn Any` without coercion is usually not intended" |
| 47 | +} |
| 48 | +declare_lint_pass!(CoerceContainerToAny => [COERCE_CONTAINER_TO_ANY]); |
| 49 | + |
| 50 | +impl<'tcx> LateLintPass<'tcx> for CoerceContainerToAny { |
| 51 | + fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) { |
| 52 | + // If this expression has an effective type of `&dyn Any` ... |
| 53 | + { |
| 54 | + let coerced_ty = cx.typeck_results().expr_ty_adjusted(e); |
| 55 | + |
| 56 | + let ty::Ref(_, coerced_ref_ty, _) = *coerced_ty.kind() else { |
| 57 | + return; |
| 58 | + }; |
| 59 | + if !is_dyn_any(cx.tcx, coerced_ref_ty) { |
| 60 | + return; |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + let expr_ty = cx.typeck_results().expr_ty(e); |
| 65 | + let ty::Ref(_, expr_ref_ty, _) = *expr_ty.kind() else { |
| 66 | + return; |
| 67 | + }; |
| 68 | + // ... but only due to coercion ... |
| 69 | + if is_dyn_any(cx.tcx, expr_ref_ty) { |
| 70 | + return; |
| 71 | + } |
| 72 | + // ... and it also *derefs* to `dyn Any` ... |
| 73 | + let Some((depth, target)) = clippy_utils::ty::deref_chain(cx, expr_ref_ty).enumerate().last() else { |
| 74 | + return; |
| 75 | + }; |
| 76 | + if !is_dyn_any(cx.tcx, target) { |
| 77 | + return; |
| 78 | + } |
| 79 | + |
| 80 | + // ... that's probably not intended. |
| 81 | + let (span, deref_count) = match e.kind { |
| 82 | + // If `e` was already an `&` expression, skip `*&` in the suggestion |
| 83 | + ExprKind::AddrOf(_, _, referent) => (referent.span, depth), |
| 84 | + _ => (e.span, depth + 1), |
| 85 | + }; |
| 86 | + span_lint_and_sugg( |
| 87 | + cx, |
| 88 | + COERCE_CONTAINER_TO_ANY, |
| 89 | + e.span, |
| 90 | + format!("coercing `{expr_ty}` to `&dyn Any`"), |
| 91 | + "consider dereferencing", |
| 92 | + format!("&{}{}", str::repeat("*", deref_count), snippet(cx, span, "x")), |
| 93 | + Applicability::MaybeIncorrect, |
| 94 | + ); |
| 95 | + } |
| 96 | +} |
| 97 | + |
| 98 | +fn is_dyn_any(tcx: TyCtxt<'_>, ty: Ty<'_>) -> bool { |
| 99 | + let ty::Dynamic(traits, ..) = ty.kind() else { |
| 100 | + return false; |
| 101 | + }; |
| 102 | + traits.iter().any(|binder| { |
| 103 | + let ExistentialPredicate::Trait(t) = binder.skip_binder() else { |
| 104 | + return false; |
| 105 | + }; |
| 106 | + tcx.is_diagnostic_item(sym::Any, t.def_id) |
| 107 | + }) |
| 108 | +} |
0 commit comments