Skip to content

Commit db0bb45

Browse files
committed
New lint: mutable_borrow_of_copy
1 parent 6753e16 commit db0bb45

17 files changed

+521
-30
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6065,6 +6065,7 @@ Released 2018-09-13
60656065
[`mut_mut`]: https://rust-lang.github.io/rust-clippy/master/index.html#mut_mut
60666066
[`mut_mutex_lock`]: https://rust-lang.github.io/rust-clippy/master/index.html#mut_mutex_lock
60676067
[`mut_range_bound`]: https://rust-lang.github.io/rust-clippy/master/index.html#mut_range_bound
6068+
[`mutable_borrow_of_copy`]: https://rust-lang.github.io/rust-clippy/master/index.html#mutable_borrow_of_copy
60686069
[`mutable_key_type`]: https://rust-lang.github.io/rust-clippy/master/index.html#mutable_key_type
60696070
[`mutex_atomic`]: https://rust-lang.github.io/rust-clippy/master/index.html#mutex_atomic
60706071
[`mutex_integer`]: https://rust-lang.github.io/rust-clippy/master/index.html#mutex_integer
@@ -6512,6 +6513,7 @@ Released 2018-09-13
65126513
[`cargo-ignore-publish`]: https://doc.rust-lang.org/clippy/lint_configuration.html#cargo-ignore-publish
65136514
[`check-incompatible-msrv-in-tests`]: https://doc.rust-lang.org/clippy/lint_configuration.html#check-incompatible-msrv-in-tests
65146515
[`check-inconsistent-struct-field-initializers`]: https://doc.rust-lang.org/clippy/lint_configuration.html#check-inconsistent-struct-field-initializers
6516+
[`check-mutable-borrow-of-copy-in-tests`]: https://doc.rust-lang.org/clippy/lint_configuration.html#check-mutable-borrow-of-copy-in-tests
65156517
[`check-private-items`]: https://doc.rust-lang.org/clippy/lint_configuration.html#check-private-items
65166518
[`cognitive-complexity-threshold`]: https://doc.rust-lang.org/clippy/lint_configuration.html#cognitive-complexity-threshold
65176519
[`disallowed-macros`]: https://doc.rust-lang.org/clippy/lint_configuration.html#disallowed-macros

book/src/lint_configuration.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -462,6 +462,16 @@ fn main() {
462462
* [`inconsistent_struct_constructor`](https://rust-lang.github.io/rust-clippy/master/index.html#inconsistent_struct_constructor)
463463

464464

465+
## `check-mutable-borrow-of-copy-in-tests`
466+
Whether to search for mutable borrows of freshly copied data in tests.
467+
468+
**Default Value:** `true`
469+
470+
---
471+
**Affected lints:**
472+
* [`mutable_borrow_of_copy`](https://rust-lang.github.io/rust-clippy/master/index.html#mutable_borrow_of_copy)
473+
474+
465475
## `check-private-items`
466476
Whether to also run the listed lints on private items.
467477

clippy_config/src/conf.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -563,6 +563,9 @@ define_Conf! {
563563
/// [from rust-clippy#11846]: https://github.com/rust-lang/rust-clippy/issues/11846#issuecomment-1820747924
564564
#[lints(inconsistent_struct_constructor)]
565565
check_inconsistent_struct_field_initializers: bool = false,
566+
/// Whether to search for mutable borrows of freshly copied data in tests.
567+
#[lints(mutable_borrow_of_copy)]
568+
check_mutable_borrow_of_copy_in_tests: bool = true,
566569
/// Whether to also run the listed lints on private items.
567570
#[lints(missing_errors_doc, missing_panics_doc, missing_safety_doc, unnecessary_safety_doc)]
568571
check_private_items: bool = false,

clippy_lints/src/declared_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -527,6 +527,7 @@ pub static LINTS: &[&crate::LintInfo] = &[
527527
crate::mut_key::MUTABLE_KEY_TYPE_INFO,
528528
crate::mut_mut::MUT_MUT_INFO,
529529
crate::mut_reference::UNNECESSARY_MUT_PASSED_INFO,
530+
crate::mutable_borrow_of_copy::MUTABLE_BORROW_OF_COPY_INFO,
530531
crate::mutable_debug_assertion::DEBUG_ASSERT_WITH_MUT_CALL_INFO,
531532
crate::mutex_atomic::MUTEX_ATOMIC_INFO,
532533
crate::mutex_atomic::MUTEX_INTEGER_INFO,

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,7 @@ mod multiple_unsafe_ops_per_block;
252252
mod mut_key;
253253
mod mut_mut;
254254
mod mut_reference;
255+
mod mutable_borrow_of_copy;
255256
mod mutable_debug_assertion;
256257
mod mutex_atomic;
257258
mod needless_arbitrary_self_type;
@@ -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(mutable_borrow_of_copy::MutableBorrowOfCopy::new(conf)));
949951
// add lints here, do not remove this comment, it's used in `new_lint`
950952
}
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 MUTABLE_BORROW_OF_COPY,
41+
suspicious,
42+
"mutable borrow of a data which was just copied"
43+
}
44+
45+
pub struct MutableBorrowOfCopy {
46+
check_in_tests: bool,
47+
}
48+
49+
impl MutableBorrowOfCopy {
50+
pub const fn new(conf: &Conf) -> Self {
51+
Self {
52+
check_in_tests: conf.check_mutable_borrow_of_copy_in_tests,
53+
}
54+
}
55+
}
56+
57+
impl_lint_pass!(MutableBorrowOfCopy => [MUTABLE_BORROW_OF_COPY]);
58+
59+
impl LateLintPass<'_> for MutableBorrowOfCopy {
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+
MUTABLE_BORROW_OF_COPY,
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::MaybeIncorrect,
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+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
check-mutable-borrow-of-copy-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 }; //~ mutable_borrow_of_copy
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 }; //~ mutable_borrow_of_copy
10+
}
Lines changed: 16 additions & 0 deletions
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/mutable_borrow_of_copy/mutable_borrow_of_copy.rs:9:13
3+
|
4+
LL | let _ = &mut { a };
5+
| ^^^^^^^^^^
6+
|
7+
= note: `-D clippy::mutable-borrow-of-copy` implied by `-D warnings`
8+
= help: to override `-D warnings` add `#[allow(clippy::mutable_borrow_of_copy)]`
9+
help: try building the reference inside the block
10+
|
11+
LL - let _ = &mut { a };
12+
LL + let _ = { &mut a };
13+
|
14+
15+
error: aborting due to 1 previous error
16+

tests/ui-toml/toml_unknown_key/conf_unknown_key.stderr

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ error: error reading Clippy's configuration file: unknown field `foobar`, expect
3333
cargo-ignore-publish
3434
check-incompatible-msrv-in-tests
3535
check-inconsistent-struct-field-initializers
36+
check-mutable-borrow-of-copy-in-tests
3637
check-private-items
3738
cognitive-complexity-threshold
3839
disallowed-macros
@@ -127,6 +128,7 @@ error: error reading Clippy's configuration file: unknown field `barfoo`, expect
127128
cargo-ignore-publish
128129
check-incompatible-msrv-in-tests
129130
check-inconsistent-struct-field-initializers
131+
check-mutable-borrow-of-copy-in-tests
130132
check-private-items
131133
cognitive-complexity-threshold
132134
disallowed-macros
@@ -221,6 +223,7 @@ error: error reading Clippy's configuration file: unknown field `allow_mixed_uni
221223
cargo-ignore-publish
222224
check-incompatible-msrv-in-tests
223225
check-inconsistent-struct-field-initializers
226+
check-mutable-borrow-of-copy-in-tests
224227
check-private-items
225228
cognitive-complexity-threshold
226229
disallowed-macros

tests/ui/mutable_borrow_of_copy.fixed

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
#![warn(clippy::mutable_borrow_of_copy)]
2+
#![allow(clippy::deref_addrof)]
3+
4+
fn main() {
5+
let mut a = [0u8; 2];
6+
let _ = { &mut a }; //~ mutable_borrow_of_copy
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+
//~^ mutable_borrow_of_copy
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)