Skip to content

Commit 410fe93

Browse files
committed
New lint: copy_then_borrow_mut
1 parent a8b1782 commit 410fe93

17 files changed

+333
-67
lines changed

CHANGELOG.md

+2
Original file line numberDiff line numberDiff line change
@@ -5497,6 +5497,7 @@ Released 2018-09-13
54975497
[`const_is_empty`]: https://rust-lang.github.io/rust-clippy/master/index.html#const_is_empty
54985498
[`const_static_lifetime`]: https://rust-lang.github.io/rust-clippy/master/index.html#const_static_lifetime
54995499
[`copy_iterator`]: https://rust-lang.github.io/rust-clippy/master/index.html#copy_iterator
5500+
[`copy_then_borrow_mut`]: https://rust-lang.github.io/rust-clippy/master/index.html#copy_then_borrow_mut
55005501
[`crate_in_macro_def`]: https://rust-lang.github.io/rust-clippy/master/index.html#crate_in_macro_def
55015502
[`create_dir`]: https://rust-lang.github.io/rust-clippy/master/index.html#create_dir
55025503
[`crosspointer_transmute`]: https://rust-lang.github.io/rust-clippy/master/index.html#crosspointer_transmute
@@ -6296,6 +6297,7 @@ Released 2018-09-13
62966297
[`avoid-breaking-exported-api`]: https://doc.rust-lang.org/clippy/lint_configuration.html#avoid-breaking-exported-api
62976298
[`await-holding-invalid-types`]: https://doc.rust-lang.org/clippy/lint_configuration.html#await-holding-invalid-types
62986299
[`cargo-ignore-publish`]: https://doc.rust-lang.org/clippy/lint_configuration.html#cargo-ignore-publish
6300+
[`check-copy-then-borrow-mut-in-test`]: https://doc.rust-lang.org/clippy/lint_configuration.html#check-copy-then-borrow-mut-in-test
62996301
[`check-private-items`]: https://doc.rust-lang.org/clippy/lint_configuration.html#check-private-items
63006302
[`cognitive-complexity-threshold`]: https://doc.rust-lang.org/clippy/lint_configuration.html#cognitive-complexity-threshold
63016303
[`disallowed-macros`]: https://doc.rust-lang.org/clippy/lint_configuration.html#disallowed-macros

book/src/lint_configuration.md

+10
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,16 @@ For internal testing only, ignores the current `publish` settings in the Cargo m
414414
* [`cargo_common_metadata`](https://rust-lang.github.io/rust-clippy/master/index.html#cargo_common_metadata)
415415

416416

417+
## `check-copy-then-borrow-mut-in-test`
418+
Whether to search for mutable borrows of freshly copied data in tests.
419+
420+
**Default Value:** `true`
421+
422+
---
423+
**Affected lints:**
424+
* [`copy_then_borrow_mut`](https://rust-lang.github.io/rust-clippy/master/index.html#copy_then_borrow_mut)
425+
426+
417427
## `check-private-items`
418428
Whether to also run the listed lints on private items.
419429

clippy_config/src/conf.rs

+3
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,9 @@ define_Conf! {
463463
/// For internal testing only, ignores the current `publish` settings in the Cargo manifest.
464464
#[lints(cargo_common_metadata)]
465465
cargo_ignore_publish: bool = false,
466+
/// Whether to search for mutable borrows of freshly copied data in tests.
467+
#[lints(copy_then_borrow_mut)]
468+
check_copy_then_borrow_mut_in_test: bool = true,
466469
/// Whether to also run the listed lints on private items.
467470
#[lints(missing_errors_doc, missing_panics_doc, missing_safety_doc, unnecessary_safety_doc)]
468471
check_private_items: bool = false,
+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
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+
}

clippy_lints/src/declared_lints.rs

+1
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ pub static LINTS: &[&crate::LintInfo] = &[
113113
crate::copies::IF_SAME_THEN_ELSE_INFO,
114114
crate::copies::SAME_FUNCTIONS_IN_IF_CONDITION_INFO,
115115
crate::copy_iterator::COPY_ITERATOR_INFO,
116+
crate::copy_then_borrow_mut::COPY_THEN_BORROW_MUT_INFO,
116117
crate::crate_in_macro_def::CRATE_IN_MACRO_DEF_INFO,
117118
crate::create_dir::CREATE_DIR_INFO,
118119
crate::dbg_macro::DBG_MACRO_INFO,

clippy_lints/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ mod collection_is_never_read;
103103
mod comparison_chain;
104104
mod copies;
105105
mod copy_iterator;
106+
mod copy_then_borrow_mut;
106107
mod crate_in_macro_def;
107108
mod create_dir;
108109
mod dbg_macro;
@@ -980,5 +981,6 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
980981
store.register_late_pass(move |_| Box::new(non_std_lazy_statics::NonStdLazyStatic::new(conf)));
981982
store.register_late_pass(|_| Box::new(manual_option_as_slice::ManualOptionAsSlice::new(conf)));
982983
store.register_late_pass(|_| Box::new(single_option_map::SingleOptionMap));
984+
store.register_late_pass(|_| Box::new(copy_then_borrow_mut::CopyThenBorrowMut::new(conf)));
983985
// add lints here, do not remove this comment, it's used in `new_lint`
984986
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
check-copy-then-borrow-mut-in-test = false
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#[test]
2+
fn in_test() {
3+
let _ = &mut { 42 }; // Do not lint
4+
}
5+
6+
fn main() {
7+
let _ = &mut { 42 }; //~ ERROR: mutable borrow
8+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
error: mutable borrow of a value which was just copied
2+
--> tests/ui-toml/copy_then_borrow_mut/copy_then_borrow_mut.rs:7:13
3+
|
4+
LL | let _ = &mut { 42 };
5+
| ^^^^^^^^^^^
6+
|
7+
note: the return value of the block implements `Copy` and will be copied
8+
--> tests/ui-toml/copy_then_borrow_mut/copy_then_borrow_mut.rs:7:20
9+
|
10+
LL | let _ = &mut { 42 };
11+
| ^^
12+
= note: `-D clippy::copy-then-borrow-mut` implied by `-D warnings`
13+
= help: to override `-D warnings` add `#[allow(clippy::copy_then_borrow_mut)]`
14+
15+
error: aborting due to 1 previous error
16+

tests/ui-toml/excessive_nesting/excessive_nesting.rs

+1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
clippy::collapsible_if,
1414
clippy::blocks_in_conditions,
1515
clippy::single_match,
16+
clippy::copy_then_borrow_mut
1617
)]
1718

1819
#[macro_use]

0 commit comments

Comments
 (0)