|
| 1 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 2 | +use clippy_utils::qpath_generic_tys; |
| 3 | +use clippy_utils::source::snippet; |
| 4 | +use clippy_utils::ty::approx_ty_size; |
| 5 | +use rustc_errors::Applicability; |
| 6 | +use rustc_hir::{AmbigArg, Expr, ExprKind, TyKind}; |
| 7 | +use rustc_lint::{LateContext, LateLintPass, LintContext}; |
| 8 | +use rustc_middle::ty::Ty; |
| 9 | +use rustc_session::declare_lint_pass; |
| 10 | + |
| 11 | +declare_clippy_lint! { |
| 12 | + /// ### What it does |
| 13 | + /// |
| 14 | + /// ### Why is this bad? |
| 15 | + /// |
| 16 | + /// ### Example |
| 17 | + /// ```no_run |
| 18 | + /// // example code where clippy issues a warning |
| 19 | + /// ``` |
| 20 | + /// Use instead: |
| 21 | + /// ```no_run |
| 22 | + /// // example code which does not raise clippy warning |
| 23 | + /// ``` |
| 24 | + #[clippy::version = "1.88.0"] |
| 25 | + pub REDUNDANT_BOX, |
| 26 | + nursery, |
| 27 | + "default lint description" |
| 28 | +} |
| 29 | + |
| 30 | +// TODO Rename lint as we are not just checking references anymore |
| 31 | +declare_lint_pass!(RedundantBox => [REDUNDANT_BOX]); |
| 32 | + |
| 33 | +// TODO could we do everything with only check_ty() xor check_expr()? |
| 34 | +impl LateLintPass<'_> for RedundantBox { |
| 35 | + fn check_ty<'tcx>(&mut self, cx: &LateContext<'tcx>, hir_ty: &rustc_hir::Ty<'tcx, AmbigArg>) { |
| 36 | + let ty = clippy_utils::ty::ty_from_hir_ty(cx, hir_ty.as_unambig_ty()); |
| 37 | + if let Some(boxed_ty) = ty.boxed_ty() |
| 38 | + && is_thin_type(cx, boxed_ty) |
| 39 | + && let TyKind::Path(path) = hir_ty.kind |
| 40 | + && let Some(boxed_ty) = qpath_generic_tys(&path).next() |
| 41 | + { |
| 42 | + emit_lint(cx, hir_ty.span, boxed_ty.span); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + fn check_expr(&mut self, cx: &LateContext<'_>, expr: &'_ Expr<'_>) { |
| 47 | + let ty = cx.typeck_results().expr_ty(expr); |
| 48 | + if let Some(boxed_ty) = ty.boxed_ty() |
| 49 | + && is_thin_type(cx, boxed_ty) |
| 50 | + && let ExprKind::Call(_, &[Expr { span, .. }]) = expr.kind |
| 51 | + { |
| 52 | + emit_lint(cx, expr.span, span); |
| 53 | + } |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +fn is_thin_type<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { |
| 58 | + ty.is_sized(cx.tcx, cx.typing_env()) && { |
| 59 | + let size = 8 * approx_ty_size(cx, ty); |
| 60 | + 0 < size && size <= u64::from(cx.sess().target.pointer_width) |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +fn emit_lint(cx: &LateContext<'_>, from_span: rustc_span::Span, to_span: rustc_span::Span) { |
| 65 | + span_lint_and_sugg( |
| 66 | + cx, |
| 67 | + REDUNDANT_BOX, |
| 68 | + from_span, |
| 69 | + "TODO: lint msg", |
| 70 | + "Remove Box", |
| 71 | + format!("{}", snippet(cx, to_span, "<default>")), |
| 72 | + Applicability::MachineApplicable, |
| 73 | + ); |
| 74 | +} |
0 commit comments