Skip to content

Commit 0dc265f

Browse files
committedJun 15, 2024
Auto merge of rust-lang#12756 - y21:assigning_clones_lifetimes, r=Alexendoo
Avoid emitting `assigning_clones` when cloned data borrows from the place to clone into Fixes rust-lang#12444 Fixes rust-lang#12460 Fixes rust-lang#12749 Fixes rust-lang#12757 Fixes rust-lang#12929 I think the documentation for the function should describe what- and how this is fixing the issues well. It avoids emitting a warning when the data being cloned borrows from the place to clone into, which is information that we can get from `PossibleBorrowerMap`. Unfortunately, it is a tiny bit tedious to match on the MIR like that and I'm not sure if this is possibly relying a bit too much on the exact MIR lowering for assignments. Things left to do: - [x] Handle place projections (or verify that they work as expected) - [x] Handle non-`Drop` types changelog: [`assigning_clones`]: avoid warning when the suggestion would lead to a borrow-check error

File tree

4 files changed

+190
-2
lines changed

4 files changed

+190
-2
lines changed
 

‎clippy_lints/src/assigning_clones.rs

+77-1
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,18 @@
11
use clippy_config::msrvs::{self, Msrv};
22
use clippy_utils::diagnostics::span_lint_and_then;
33
use clippy_utils::macros::HirNode;
4+
use clippy_utils::mir::{enclosing_mir, PossibleBorrowerMap};
45
use clippy_utils::sugg::Sugg;
56
use clippy_utils::{is_trait_method, local_is_initialized, path_to_local};
67
use rustc_errors::Applicability;
78
use rustc_hir::{self as hir, Expr, ExprKind};
89
use rustc_lint::{LateContext, LateLintPass};
10+
use rustc_middle::mir;
911
use rustc_middle::ty::{self, Instance, Mutability};
1012
use rustc_session::impl_lint_pass;
1113
use rustc_span::def_id::DefId;
1214
use rustc_span::symbol::sym;
13-
use rustc_span::{ExpnKind, SyntaxContext};
15+
use rustc_span::{ExpnKind, Span, SyntaxContext};
1416

1517
declare_clippy_lint! {
1618
/// ### What it does
@@ -144,6 +146,7 @@ fn extract_call<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<
144146
};
145147

146148
Some(CallCandidate {
149+
span: expr.span,
147150
target,
148151
kind,
149152
method_def_id: resolved_method.def_id(),
@@ -215,13 +218,85 @@ fn is_ok_to_suggest<'tcx>(cx: &LateContext<'tcx>, lhs: &Expr<'tcx>, call: &CallC
215218
return false;
216219
};
217220

221+
if clone_source_borrows_from_dest(cx, lhs, call.span) {
222+
return false;
223+
}
224+
218225
// Now take a look if the impl block defines an implementation for the method that we're interested
219226
// in. If not, then we're using a default implementation, which is not interesting, so we will
220227
// not suggest the lint.
221228
let implemented_fns = cx.tcx.impl_item_implementor_ids(impl_block);
222229
implemented_fns.contains_key(&provided_fn.def_id)
223230
}
224231

232+
/// Checks if the data being cloned borrows from the place that is being assigned to:
233+
///
234+
/// ```
235+
/// let mut s = String::new();
236+
/// let s2 = &s;
237+
/// s = s2.to_owned();
238+
/// ```
239+
///
240+
/// This cannot be written `s2.clone_into(&mut s)` because it has conflicting borrows.
241+
fn clone_source_borrows_from_dest(cx: &LateContext<'_>, lhs: &Expr<'_>, call_span: Span) -> bool {
242+
/// If this basic block only exists to drop a local as part of an assignment, returns its
243+
/// successor. Otherwise returns the basic block that was passed in.
244+
fn skip_drop_block(mir: &mir::Body<'_>, bb: mir::BasicBlock) -> mir::BasicBlock {
245+
if let mir::TerminatorKind::Drop { target, .. } = mir.basic_blocks[bb].terminator().kind {
246+
target
247+
} else {
248+
bb
249+
}
250+
}
251+
252+
let Some(mir) = enclosing_mir(cx.tcx, lhs.hir_id) else {
253+
return false;
254+
};
255+
let PossibleBorrowerMap { map: borrow_map, .. } = PossibleBorrowerMap::new(cx, mir);
256+
257+
// The operation `dest = src.to_owned()` in MIR is split up across 3 blocks *if* the type has `Drop`
258+
// code. For types that don't, the second basic block is simply skipped.
259+
// For the doc example above that would be roughly:
260+
//
261+
// bb0:
262+
// s2 = &s
263+
// s_temp = ToOwned::to_owned(move s2) -> bb1
264+
//
265+
// bb1:
266+
// drop(s) -> bb2 // drop the old string
267+
//
268+
// bb2:
269+
// s = s_temp
270+
for bb in mir.basic_blocks.iter() {
271+
let terminator = bb.terminator();
272+
273+
// Look for the to_owned/clone call.
274+
if terminator.source_info.span != call_span {
275+
continue;
276+
}
277+
278+
if let mir::TerminatorKind::Call { ref args, target: Some(assign_bb), .. } = terminator.kind
279+
&& let [source] = &**args
280+
&& let mir::Operand::Move(source) = &source.node
281+
&& let assign_bb = skip_drop_block(mir, assign_bb)
282+
// Skip any storage statements as they are just noise
283+
&& let Some(assignment) = mir.basic_blocks[assign_bb].statements
284+
.iter()
285+
.find(|stmt| {
286+
!matches!(stmt.kind, mir::StatementKind::StorageDead(_) | mir::StatementKind::StorageLive(_))
287+
})
288+
&& let mir::StatementKind::Assign(box (borrowed, _)) = &assignment.kind
289+
&& let Some(borrowers) = borrow_map.get(&borrowed.local)
290+
&& borrowers.contains(source.local)
291+
{
292+
return true;
293+
}
294+
295+
return false;
296+
}
297+
false
298+
}
299+
225300
fn suggest<'tcx>(
226301
cx: &LateContext<'tcx>,
227302
ctxt: SyntaxContext,
@@ -255,6 +330,7 @@ enum TargetTrait {
255330

256331
#[derive(Debug)]
257332
struct CallCandidate<'tcx> {
333+
span: Span,
258334
target: TargetTrait,
259335
kind: CallKind<'tcx>,
260336
// DefId of the called method from an impl block that implements the target trait

‎clippy_utils/src/mir/possible_borrower.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ impl<'a, 'b, 'tcx> mir::visit::Visitor<'tcx> for PossibleBorrowerVisitor<'a, 'b,
6969
fn visit_assign(&mut self, place: &mir::Place<'tcx>, rvalue: &mir::Rvalue<'_>, _location: mir::Location) {
7070
let lhs = place.local;
7171
match rvalue {
72-
mir::Rvalue::Ref(_, _, borrowed) => {
72+
mir::Rvalue::Ref(_, _, borrowed) | mir::Rvalue::CopyForDeref(borrowed) => {
7373
self.possible_borrower.add(borrowed.local, lhs);
7474
},
7575
other => {

‎tests/ui/assigning_clones.fixed

+56
Original file line numberDiff line numberDiff line change
@@ -272,3 +272,59 @@ impl<'a> Add for &'a mut HasCloneFrom {
272272
self
273273
}
274274
}
275+
276+
mod borrowck_conflicts {
277+
//! Cases where clone_into and friends cannot be used because the src/dest have conflicting
278+
//! borrows.
279+
use std::path::PathBuf;
280+
281+
fn issue12444(mut name: String) {
282+
let parts = name.split(", ").collect::<Vec<_>>();
283+
let first = *parts.first().unwrap();
284+
name = first.to_owned();
285+
}
286+
287+
fn issue12444_simple() {
288+
let mut s = String::new();
289+
let s2 = &s;
290+
s = s2.to_owned();
291+
}
292+
293+
fn issue12444_nodrop_projections() {
294+
struct NoDrop;
295+
296+
impl Clone for NoDrop {
297+
fn clone(&self) -> Self {
298+
todo!()
299+
}
300+
fn clone_from(&mut self, other: &Self) {
301+
todo!()
302+
}
303+
}
304+
305+
let mut s = NoDrop;
306+
let s2 = &s;
307+
s = s2.clone();
308+
309+
let mut s = (NoDrop, NoDrop);
310+
let s2 = &s.0;
311+
s.0 = s2.clone();
312+
313+
// This *could* emit a warning, but PossibleBorrowerMap only works with locals so it
314+
// considers `s` fully borrowed
315+
let mut s = (NoDrop, NoDrop);
316+
let s2 = &s.1;
317+
s.0 = s2.clone();
318+
}
319+
320+
fn issue12460(mut name: String) {
321+
if let Some(stripped_name) = name.strip_prefix("baz-") {
322+
name = stripped_name.to_owned();
323+
}
324+
}
325+
326+
fn issue12749() {
327+
let mut path = PathBuf::from("/a/b/c");
328+
path = path.components().as_path().to_owned();
329+
}
330+
}

‎tests/ui/assigning_clones.rs

+56
Original file line numberDiff line numberDiff line change
@@ -272,3 +272,59 @@ impl<'a> Add for &'a mut HasCloneFrom {
272272
self
273273
}
274274
}
275+
276+
mod borrowck_conflicts {
277+
//! Cases where clone_into and friends cannot be used because the src/dest have conflicting
278+
//! borrows.
279+
use std::path::PathBuf;
280+
281+
fn issue12444(mut name: String) {
282+
let parts = name.split(", ").collect::<Vec<_>>();
283+
let first = *parts.first().unwrap();
284+
name = first.to_owned();
285+
}
286+
287+
fn issue12444_simple() {
288+
let mut s = String::new();
289+
let s2 = &s;
290+
s = s2.to_owned();
291+
}
292+
293+
fn issue12444_nodrop_projections() {
294+
struct NoDrop;
295+
296+
impl Clone for NoDrop {
297+
fn clone(&self) -> Self {
298+
todo!()
299+
}
300+
fn clone_from(&mut self, other: &Self) {
301+
todo!()
302+
}
303+
}
304+
305+
let mut s = NoDrop;
306+
let s2 = &s;
307+
s = s2.clone();
308+
309+
let mut s = (NoDrop, NoDrop);
310+
let s2 = &s.0;
311+
s.0 = s2.clone();
312+
313+
// This *could* emit a warning, but PossibleBorrowerMap only works with locals so it
314+
// considers `s` fully borrowed
315+
let mut s = (NoDrop, NoDrop);
316+
let s2 = &s.1;
317+
s.0 = s2.clone();
318+
}
319+
320+
fn issue12460(mut name: String) {
321+
if let Some(stripped_name) = name.strip_prefix("baz-") {
322+
name = stripped_name.to_owned();
323+
}
324+
}
325+
326+
fn issue12749() {
327+
let mut path = PathBuf::from("/a/b/c");
328+
path = path.components().as_path().to_owned();
329+
}
330+
}

0 commit comments

Comments
 (0)
Please sign in to comment.