Skip to content

Commit 03e6eac

Browse files
committed
New lint: copy_then_borrow_mut
1 parent 6753e16 commit 03e6eac

17 files changed

+520
-30
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5697,6 +5697,7 @@ Released 2018-09-13
56975697
[`const_is_empty`]: https://rust-lang.github.io/rust-clippy/master/index.html#const_is_empty
56985698
[`const_static_lifetime`]: https://rust-lang.github.io/rust-clippy/master/index.html#const_static_lifetime
56995699
[`copy_iterator`]: https://rust-lang.github.io/rust-clippy/master/index.html#copy_iterator
5700+
[`copy_then_borrow_mut`]: https://rust-lang.github.io/rust-clippy/master/index.html#copy_then_borrow_mut
57005701
[`crate_in_macro_def`]: https://rust-lang.github.io/rust-clippy/master/index.html#crate_in_macro_def
57015702
[`create_dir`]: https://rust-lang.github.io/rust-clippy/master/index.html#create_dir
57025703
[`crosspointer_transmute`]: https://rust-lang.github.io/rust-clippy/master/index.html#crosspointer_transmute
@@ -6510,6 +6511,7 @@ Released 2018-09-13
65106511
[`avoid-breaking-exported-api`]: https://doc.rust-lang.org/clippy/lint_configuration.html#avoid-breaking-exported-api
65116512
[`await-holding-invalid-types`]: https://doc.rust-lang.org/clippy/lint_configuration.html#await-holding-invalid-types
65126513
[`cargo-ignore-publish`]: https://doc.rust-lang.org/clippy/lint_configuration.html#cargo-ignore-publish
6514+
[`check-copy-then-borrow-mut-in-tests`]: https://doc.rust-lang.org/clippy/lint_configuration.html#check-copy-then-borrow-mut-in-tests
65136515
[`check-incompatible-msrv-in-tests`]: https://doc.rust-lang.org/clippy/lint_configuration.html#check-incompatible-msrv-in-tests
65146516
[`check-inconsistent-struct-field-initializers`]: https://doc.rust-lang.org/clippy/lint_configuration.html#check-inconsistent-struct-field-initializers
65156517
[`check-private-items`]: https://doc.rust-lang.org/clippy/lint_configuration.html#check-private-items

book/src/lint_configuration.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -425,6 +425,16 @@ For internal testing only, ignores the current `publish` settings in the Cargo m
425425
* [`cargo_common_metadata`](https://rust-lang.github.io/rust-clippy/master/index.html#cargo_common_metadata)
426426

427427

428+
## `check-copy-then-borrow-mut-in-tests`
429+
Whether to search for mutable borrows of freshly copied data in tests.
430+
431+
**Default Value:** `true`
432+
433+
---
434+
**Affected lints:**
435+
* [`copy_then_borrow_mut`](https://rust-lang.github.io/rust-clippy/master/index.html#copy_then_borrow_mut)
436+
437+
428438
## `check-incompatible-msrv-in-tests`
429439
Whether to check MSRV compatibility in `#[test]` and `#[cfg(test)]` code.
430440

clippy_config/src/conf.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -540,6 +540,9 @@ define_Conf! {
540540
/// For internal testing only, ignores the current `publish` settings in the Cargo manifest.
541541
#[lints(cargo_common_metadata)]
542542
cargo_ignore_publish: bool = false,
543+
/// Whether to search for mutable borrows of freshly copied data in tests.
544+
#[lints(copy_then_borrow_mut)]
545+
check_copy_then_borrow_mut_in_tests: bool = true,
543546
/// Whether to check MSRV compatibility in `#[test]` and `#[cfg(test)]` code.
544547
#[lints(incompatible_msrv)]
545548
check_incompatible_msrv_in_tests: bool = false,
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
use clippy_config::Conf;
2+
use clippy_utils::diagnostics::span_lint_and_then;
3+
use clippy_utils::ty::is_copy;
4+
use clippy_utils::{get_enclosing_block, is_in_test, path_to_local};
5+
use rustc_ast::BindingMode;
6+
use rustc_errors::Applicability;
7+
use rustc_hir::{Block, BorrowKind, Expr, ExprKind, Mutability, Node, PatKind};
8+
use rustc_lint::{LateContext, LateLintPass};
9+
use rustc_session::impl_lint_pass;
10+
11+
declare_clippy_lint! {
12+
/// ### What it does
13+
/// Checks for taking a mutable reference on a freshly copied variable due to the use of a block returning a value implementing `Copy`.
14+
///
15+
/// ### Why is this bad?
16+
/// Using a block will make a copy of the block result if its type
17+
/// implements `Copy`. This might be an indication of a failed attempt
18+
/// to borrow a variable.
19+
///
20+
/// ### Example
21+
/// ```no_run
22+
/// # unsafe fn unsafe_func(_: &mut i32) {}
23+
/// let mut a = 10;
24+
/// let double_a_ref = &mut unsafe { // Unsafe block needed to call `unsafe_func`
25+
/// unsafe_func(&mut a);
26+
/// a
27+
/// };
28+
/// ```
29+
/// If you intend to take a reference on `a` and you need the block,
30+
/// create the reference inside the block instead:
31+
/// ```no_run
32+
/// # unsafe fn unsafe_func(_: &mut i32) {}
33+
/// let mut a = 10;
34+
/// let double_a_ref = unsafe { // Unsafe block needed to call `unsafe_func`
35+
/// unsafe_func(&mut a);
36+
/// &mut a
37+
/// };
38+
/// ```
39+
#[clippy::version = "1.89.0"]
40+
pub COPY_THEN_BORROW_MUT,
41+
correctness,
42+
"mutable borrow of a data which was just copied"
43+
}
44+
45+
pub struct CopyThenBorrowMut {
46+
check_in_tests: bool,
47+
}
48+
49+
impl CopyThenBorrowMut {
50+
pub const fn new(conf: &Conf) -> Self {
51+
Self {
52+
check_in_tests: conf.check_copy_then_borrow_mut_in_tests,
53+
}
54+
}
55+
}
56+
57+
impl_lint_pass!(CopyThenBorrowMut => [COPY_THEN_BORROW_MUT]);
58+
59+
impl LateLintPass<'_> for CopyThenBorrowMut {
60+
fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
61+
if !expr.span.from_expansion()
62+
&& let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, sub_expr) = expr.kind
63+
&& let ExprKind::Block(block, _) = sub_expr.kind
64+
&& !block.targeted_by_break
65+
&& block.span.eq_ctxt(expr.span)
66+
&& let Some(block_expr) = block.expr
67+
&& let block_ty = cx.typeck_results().expr_ty_adjusted(block_expr)
68+
&& is_copy(cx, block_ty)
69+
&& is_copied_defined_outside_block(cx, block_expr, block)
70+
&& (self.check_in_tests || !is_in_test(cx.tcx, expr.hir_id))
71+
{
72+
span_lint_and_then(
73+
cx,
74+
COPY_THEN_BORROW_MUT,
75+
expr.span,
76+
"mutable borrow of a value which was just copied",
77+
|diag| {
78+
diag.multipart_suggestion(
79+
"try building the reference inside the block",
80+
vec![
81+
(expr.span.until(block.span), String::new()),
82+
(block_expr.span.shrink_to_lo(), String::from("&mut ")),
83+
],
84+
Applicability::MachineApplicable,
85+
);
86+
},
87+
);
88+
}
89+
}
90+
}
91+
92+
/// Checks if `expr` denotes a mutable variable defined outside `block`. This peels away field
93+
/// accesses or indexing of such a variable first.
94+
fn is_copied_defined_outside_block(cx: &LateContext<'_>, mut expr: &Expr<'_>, block: &Block<'_>) -> bool {
95+
while let ExprKind::Field(base, _) | ExprKind::Index(base, _, _) = expr.kind {
96+
expr = base;
97+
}
98+
if let Some(mut current) = path_to_local(expr)
99+
&& let Node::Pat(pat) = cx.tcx.hir_node(current)
100+
&& matches!(pat.kind, PatKind::Binding(BindingMode::MUT, ..))
101+
{
102+
// Scan enclosing blocks until we find `block` (if so, the local is defined within it), or we loop
103+
// or can't find blocks anymore.
104+
loop {
105+
match get_enclosing_block(cx, current).map(|b| b.hir_id) {
106+
Some(parent) if parent == block.hir_id => return false,
107+
Some(parent) if parent != current => current = parent,
108+
_ => return true,
109+
}
110+
}
111+
}
112+
false
113+
}

clippy_lints/src/declared_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ pub static LINTS: &[&crate::LintInfo] = &[
8787
crate::copies::IF_SAME_THEN_ELSE_INFO,
8888
crate::copies::SAME_FUNCTIONS_IN_IF_CONDITION_INFO,
8989
crate::copy_iterator::COPY_ITERATOR_INFO,
90+
crate::copy_then_borrow_mut::COPY_THEN_BORROW_MUT_INFO,
9091
crate::crate_in_macro_def::CRATE_IN_MACRO_DEF_INFO,
9192
crate::create_dir::CREATE_DIR_INFO,
9293
crate::dbg_macro::DBG_MACRO_INFO,

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ mod collection_is_never_read;
101101
mod comparison_chain;
102102
mod copies;
103103
mod copy_iterator;
104+
mod copy_then_borrow_mut;
104105
mod crate_in_macro_def;
105106
mod create_dir;
106107
mod dbg_macro;
@@ -946,5 +947,6 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
946947
store.register_late_pass(|_| Box::new(single_option_map::SingleOptionMap));
947948
store.register_late_pass(move |_| Box::new(redundant_test_prefix::RedundantTestPrefix));
948949
store.register_late_pass(|_| Box::new(cloned_ref_to_slice_refs::ClonedRefToSliceRefs::new(conf)));
950+
store.register_late_pass(|_| Box::new(copy_then_borrow_mut::CopyThenBorrowMut::new(conf)));
949951
// add lints here, do not remove this comment, it's used in `new_lint`
950952
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
check-copy-then-borrow-mut-in-tests = false
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#[test]
2+
fn in_test() {
3+
let mut a = [10; 2];
4+
let _ = &mut { a }; // Do not lint
5+
}
6+
7+
fn main() {
8+
let mut a = [10; 2];
9+
let _ = { &mut a }; //~ ERROR: mutable borrow
10+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#[test]
2+
fn in_test() {
3+
let mut a = [10; 2];
4+
let _ = &mut { a }; // Do not lint
5+
}
6+
7+
fn main() {
8+
let mut a = [10; 2];
9+
let _ = &mut { a }; //~ ERROR: mutable borrow
10+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
error: mutable borrow of a value which was just copied
2+
--> tests/ui-toml/copy_then_borrow_mut/copy_then_borrow_mut.rs:9:13
3+
|
4+
LL | let _ = &mut { a };
5+
| ^^^^^^^^^^
6+
|
7+
= note: `#[deny(clippy::copy_then_borrow_mut)]` on by default
8+
help: try building the reference inside the block
9+
|
10+
LL - let _ = &mut { a };
11+
LL + let _ = { &mut a };
12+
|
13+
14+
error: aborting due to 1 previous error
15+

tests/ui-toml/toml_unknown_key/conf_unknown_key.stderr

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ error: error reading Clippy's configuration file: unknown field `foobar`, expect
3131
avoid-breaking-exported-api
3232
await-holding-invalid-types
3333
cargo-ignore-publish
34+
check-copy-then-borrow-mut-in-tests
3435
check-incompatible-msrv-in-tests
3536
check-inconsistent-struct-field-initializers
3637
check-private-items
@@ -125,6 +126,7 @@ error: error reading Clippy's configuration file: unknown field `barfoo`, expect
125126
avoid-breaking-exported-api
126127
await-holding-invalid-types
127128
cargo-ignore-publish
129+
check-copy-then-borrow-mut-in-tests
128130
check-incompatible-msrv-in-tests
129131
check-inconsistent-struct-field-initializers
130132
check-private-items
@@ -219,6 +221,7 @@ error: error reading Clippy's configuration file: unknown field `allow_mixed_uni
219221
avoid-breaking-exported-api
220222
await-holding-invalid-types
221223
cargo-ignore-publish
224+
check-copy-then-borrow-mut-in-tests
222225
check-incompatible-msrv-in-tests
223226
check-inconsistent-struct-field-initializers
224227
check-private-items

tests/ui/copy_then_borrow_mut.fixed

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
#![warn(clippy::copy_then_borrow_mut)]
2+
#![allow(clippy::deref_addrof)]
3+
4+
fn main() {
5+
let mut a = [0u8; 2];
6+
let _ = { &mut a }; //~ ERROR: mutable borrow
7+
8+
let _ = &mut 'label: {
9+
// Block is targeted by break
10+
if a[0] == 1 {
11+
break 'label 42u8;
12+
}
13+
a[0]
14+
};
15+
16+
let mut a = vec![0u8; 2];
17+
let _ = &mut { a }; // `a` is not `Copy`
18+
19+
let a = [0u8; 2];
20+
let _ = &mut { a }; // `a` is not mutable
21+
22+
let _ = &mut { 42 }; // Do not lint on non-place expression
23+
24+
let _ = &mut {}; // Do not lint on empty block
25+
26+
macro_rules! mac {
27+
($a:expr) => {{ a }};
28+
}
29+
let _ = &mut mac!(a); // Do not lint on borrowed macro result
30+
31+
macro_rules! mac2 {
32+
// Do not lint, as it depends on `Copy`-ness of `a`
33+
($x:expr) => {
34+
&mut unsafe { $x }
35+
};
36+
}
37+
let mut a = 0u8;
38+
let _ = &mut mac2!(a);
39+
40+
let _ = &mut {
41+
// Do not lint, the variable is defined inside the block
42+
let mut a: [i32; 5] = (1, 2, 3, 4, 5).into();
43+
a
44+
};
45+
46+
let _ = &mut {
47+
// Do not lint, the variable is defined inside the block
48+
{
49+
let mut a: [i32; 5] = (1, 2, 3, 4, 5).into();
50+
a
51+
}
52+
};
53+
54+
struct S {
55+
a: u32,
56+
}
57+
58+
let mut s = S { a: 0 };
59+
let _ = {
60+
//~^ ERROR: mutable borrow
61+
s.a = 32;
62+
&mut s.a
63+
};
64+
65+
let _ = &mut {
66+
// Do not lint, the variable is defined inside the block
67+
let mut s = S { a: 0 };
68+
s.a
69+
};
70+
71+
let mut c = (10, 20);
72+
let _ = {
73+
//~^ ERROR: mutable borrow
74+
&mut c.0
75+
};
76+
77+
let _ = &mut {
78+
// Do not lint, the variable is defined inside the block
79+
let mut c = (10, 20);
80+
c.0
81+
};
82+
83+
let mut t = [10, 20];
84+
let _ = {
85+
//~^ ERROR: mutable borrow
86+
&mut t[0]
87+
};
88+
89+
let _ = &mut {
90+
// Do not lint, the variable is defined inside the block
91+
let mut t = [10, 20];
92+
t[0]
93+
};
94+
95+
unsafe fn unsafe_func(_: &mut i32) {}
96+
let mut a = 10;
97+
// Unsafe block needed to call `unsafe_func`
98+
let double_a_ref = unsafe {
99+
//~^ ERROR: mutable borrow
100+
unsafe_func(&mut a);
101+
&mut a
102+
};
103+
}
104+
105+
#[test]
106+
fn in_test() {
107+
let mut a = [10; 2];
108+
let _ = { &mut a }; //~ ERROR: mutable borrow
109+
}

0 commit comments

Comments
 (0)