|
| 1 | +use clippy_utils::diagnostics::span_lint; |
| 2 | +use clippy_utils::sym; |
| 3 | +use rustc_hir::{Expr, LangItem}; |
| 4 | +use rustc_lint::{LateContext, LateLintPass}; |
| 5 | +use rustc_middle::ty::{self, ExistentialPredicate, Ty}; |
| 6 | +use rustc_session::declare_lint_pass; |
| 7 | + |
| 8 | +declare_clippy_lint! { |
| 9 | + /// ### What it does |
| 10 | + /// |
| 11 | + /// ### Why is this bad? |
| 12 | + /// |
| 13 | + /// ### Example |
| 14 | + /// ```no_run |
| 15 | + /// // example code where clippy issues a warning |
| 16 | + /// ``` |
| 17 | + /// Use instead: |
| 18 | + /// ```no_run |
| 19 | + /// // example code which does not raise clippy warning |
| 20 | + /// ``` |
| 21 | + #[clippy::version = "1.88.0"] |
| 22 | + pub COERCE_ANY_REF_TO_ANY, |
| 23 | + nursery, |
| 24 | + "default lint description" |
| 25 | +} |
| 26 | +declare_lint_pass!(CoerceAnyRefToAny => [COERCE_ANY_REF_TO_ANY]); |
| 27 | + |
| 28 | +impl<'tcx> LateLintPass<'tcx> for CoerceAnyRefToAny { |
| 29 | + fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) { |
| 30 | + { |
| 31 | + let coerced_ty = cx.typeck_results().expr_ty_adjusted(e); |
| 32 | + |
| 33 | + let ty::Ref(_, coerced_ref_ty, _) = *coerced_ty.kind() else { |
| 34 | + return; |
| 35 | + }; |
| 36 | + if !is_dyn_any(cx, coerced_ref_ty) { |
| 37 | + return; |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + let expr_ty = cx.typeck_results().expr_ty(e); |
| 42 | + let ty::Ref(_, expr_ref_ty, _) = expr_ty.kind() else { |
| 43 | + return; |
| 44 | + }; |
| 45 | + let ty::Adt(adt, ty_params) = expr_ref_ty.kind() else { |
| 46 | + return; |
| 47 | + }; |
| 48 | + if !cx.tcx.is_lang_item(adt.did(), LangItem::OwnedBox) { |
| 49 | + return; |
| 50 | + } |
| 51 | + if !is_dyn_any(cx, ty_params.first().unwrap().as_type().unwrap()) { |
| 52 | + return; |
| 53 | + } |
| 54 | + |
| 55 | + span_lint( |
| 56 | + cx, |
| 57 | + COERCE_ANY_REF_TO_ANY, |
| 58 | + e.span, |
| 59 | + "coercing &Box<dyn Any> to &dyn Any rather than dereferencing the Box", |
| 60 | + ); |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +fn is_dyn_any(cx: &LateContext<'_>, ty: Ty<'_>) -> bool { |
| 65 | + let ty::Dynamic(traits, ..) = ty.kind() else { |
| 66 | + return false; |
| 67 | + }; |
| 68 | + if traits.iter().all(|binder| { |
| 69 | + let Some(predicate) = binder.no_bound_vars() else { |
| 70 | + return false; |
| 71 | + }; |
| 72 | + let ExistentialPredicate::Trait(t) = predicate else { |
| 73 | + return false; |
| 74 | + }; |
| 75 | + !cx.tcx.is_diagnostic_item(sym::Any, t.def_id) |
| 76 | + }) { |
| 77 | + return false; |
| 78 | + } |
| 79 | + true |
| 80 | +} |
0 commit comments