|
| 1 | +use clippy_config::Conf; |
| 2 | +use clippy_utils::diagnostics::span_lint_and_note; |
| 3 | +use clippy_utils::is_in_test; |
| 4 | +use clippy_utils::ty::is_copy; |
| 5 | +use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability}; |
| 6 | +use rustc_lint::{LateContext, LateLintPass}; |
| 7 | +use rustc_session::impl_lint_pass; |
| 8 | + |
| 9 | +declare_clippy_lint! { |
| 10 | + /// ### What it does |
| 11 | + /// Checks for mutable reference on a freshly copied data due to |
| 12 | + /// the use of a block to return an value implementing `Copy`. |
| 13 | + /// |
| 14 | + /// ### Why is this bad? |
| 15 | + /// Using a block will make a copy of the block result if its type |
| 16 | + /// implements `Copy`. This might be an indication of a failed attempt |
| 17 | + /// to borrow the original data instead. |
| 18 | + /// |
| 19 | + /// ### Example |
| 20 | + /// ```no_run |
| 21 | + /// # fn f(_: &mut [i32]) {} |
| 22 | + /// let arr = &mut [10, 20, 30]; |
| 23 | + /// f(&mut { *arr }); |
| 24 | + /// ``` |
| 25 | + /// If you intend to modify `arr` in `f`, use instead: |
| 26 | + /// ```no_run |
| 27 | + /// # fn f(_: &mut [i32]) {} |
| 28 | + /// let arr = &mut [10, 20, 30]; |
| 29 | + /// f(arr); |
| 30 | + /// ``` |
| 31 | + #[clippy::version = "1.86.0"] |
| 32 | + pub COPY_THEN_BORROW_MUT, |
| 33 | + suspicious, |
| 34 | + "mutable borrow of a data which was just copied" |
| 35 | +} |
| 36 | + |
| 37 | +pub struct CopyThenBorrowMut { |
| 38 | + check_in_test: bool, |
| 39 | +} |
| 40 | + |
| 41 | +impl CopyThenBorrowMut { |
| 42 | + pub const fn new(conf: &Conf) -> Self { |
| 43 | + Self { |
| 44 | + check_in_test: conf.check_copy_then_borrow_mut_in_test, |
| 45 | + } |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +impl_lint_pass!(CopyThenBorrowMut => [COPY_THEN_BORROW_MUT]); |
| 50 | + |
| 51 | +impl LateLintPass<'_> for CopyThenBorrowMut { |
| 52 | + fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) { |
| 53 | + if !expr.span.from_expansion() |
| 54 | + && let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, sub_expr) = expr.kind |
| 55 | + && let ExprKind::Block(block, _) = sub_expr.kind |
| 56 | + && block.span.eq_ctxt(expr.span) |
| 57 | + && let Some(block_expr) = block.expr |
| 58 | + && let block_ty = cx.typeck_results().expr_ty_adjusted(block_expr) |
| 59 | + && is_copy(cx, block_ty) |
| 60 | + && (self.check_in_test || !is_in_test(cx.tcx, expr.hir_id)) |
| 61 | + { |
| 62 | + span_lint_and_note( |
| 63 | + cx, |
| 64 | + COPY_THEN_BORROW_MUT, |
| 65 | + expr.span, |
| 66 | + "mutable borrow of a value which was just copied", |
| 67 | + (!block.targeted_by_break).then_some(block_expr.span), |
| 68 | + "the return value of the block implements `Copy` and will be copied", |
| 69 | + ); |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments