Skip to content

Commit ec135bc

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

17 files changed

+520
-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+
correctness,
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::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+
}
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: 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/mutable_borrow_of_copy/mutable_borrow_of_copy.rs:9:13
3+
|
4+
LL | let _ = &mut { a };
5+
| ^^^^^^^^^^
6+
|
7+
= note: `#[deny(clippy::mutable_borrow_of_copy)]` 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+

0 commit comments

Comments
 (0)