1 use clippy_utils::diagnostics::{span_lint_hir, span_lint_hir_and_then};
2 use clippy_utils::mir::{visit_local_usage, LocalUsage, PossibleBorrowerMap};
3 use clippy_utils::source::snippet_opt;
4 use clippy_utils::ty::{has_drop, is_copy, is_type_diagnostic_item, is_type_lang_item, walk_ptrs_ty_depth};
5 use clippy_utils::{fn_has_unsatisfiable_preds, match_def_path, paths};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir::intravisit::FnKind;
9 use rustc_hir::{def_id, Body, FnDecl, HirId, LangItem};
10 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_middle::mir;
12 use rustc_middle::ty::{self, Ty};
13 use rustc_session::{declare_lint_pass, declare_tool_lint};
14 use rustc_span::source_map::{BytePos, Span};
17 macro_rules! unwrap_or_continue {
26 declare_clippy_lint! {
28 /// Checks for a redundant `clone()` (and its relatives) which clones an owned
29 /// value that is going to be dropped without further use.
31 /// ### Why is this bad?
32 /// It is not always possible for the compiler to eliminate useless
33 /// allocations and deallocations generated by redundant `clone()`s.
35 /// ### Known problems
36 /// False-negatives: analysis performed by this lint is conservative and limited.
40 /// # use std::path::Path;
41 /// # #[derive(Clone)]
44 /// # fn new() -> Self { Foo {} }
46 /// # fn call(x: Foo) {}
48 /// let x = Foo::new();
50 /// call(x.clone()); // this can just pass `x`
53 /// ["lorem", "ipsum"].join(" ").to_string();
55 /// Path::new("/a/b").join("c").to_path_buf();
57 #[clippy::version = "1.32.0"]
60 "`clone()` of an owned value that is going to be dropped immediately"
63 declare_lint_pass!(RedundantClone => [REDUNDANT_CLONE]);
65 impl<'tcx> LateLintPass<'tcx> for RedundantClone {
66 #[expect(clippy::too_many_lines)]
69 cx: &LateContext<'tcx>,
76 let def_id = cx.tcx.hir().body_owner_def_id(body.id());
78 // Building MIR for `fn`s with unsatisfiable preds results in ICE.
79 if fn_has_unsatisfiable_preds(cx, def_id.to_def_id()) {
83 let mir = cx.tcx.optimized_mir(def_id.to_def_id());
85 let mut possible_borrower = PossibleBorrowerMap::new(cx, mir);
87 for (bb, bbdata) in mir.basic_blocks.iter_enumerated() {
88 let terminator = bbdata.terminator();
90 if terminator.source_info.span.from_expansion() {
95 if terminator.successors().any(|s| s == bb) {
99 let (fn_def_id, arg, arg_ty, clone_ret) =
100 unwrap_or_continue!(is_call_with_ref_arg(cx, mir, &terminator.kind));
102 let from_borrow = match_def_path(cx, fn_def_id, &paths::CLONE_TRAIT_METHOD)
103 || match_def_path(cx, fn_def_id, &paths::TO_OWNED_METHOD)
104 || (match_def_path(cx, fn_def_id, &paths::TO_STRING_METHOD)
105 && is_type_lang_item(cx, arg_ty, LangItem::String));
107 let from_deref = !from_borrow
108 && (match_def_path(cx, fn_def_id, &paths::PATH_TO_PATH_BUF)
109 || match_def_path(cx, fn_def_id, &paths::OS_STR_TO_OS_STRING));
111 if !from_borrow && !from_deref {
115 if let ty::Adt(def, _) = arg_ty.kind() {
116 if def.is_manually_drop() {
121 // `{ arg = &cloned; clone(move arg); }` or `{ arg = &cloned; to_path_buf(arg); }`
122 let (cloned, cannot_move_out) = unwrap_or_continue!(find_stmt_assigns_to(cx, mir, arg, from_borrow, bb));
124 let loc = mir::Location {
126 statement_index: bbdata.statements.len(),
129 // `Local` to be cloned, and a local of `clone` call's destination
130 let (local, ret_local) = if from_borrow {
131 // `res = clone(arg)` can be turned into `res = move arg;`
132 // if `arg` is the only borrow of `cloned` at this point.
134 if cannot_move_out || !possible_borrower.at_most_borrowers(cx, &[arg], cloned, loc) {
140 // `arg` is a reference as it is `.deref()`ed in the previous block.
141 // Look into the predecessor block and find out the source of deref.
143 let ps = &mir.basic_blocks.predecessors()[bb];
147 let pred_terminator = mir[ps[0]].terminator();
149 // receiver of the `deref()` call
150 let (pred_arg, deref_clone_ret) = if_chain! {
151 if let Some((pred_fn_def_id, pred_arg, pred_arg_ty, res)) =
152 is_call_with_ref_arg(cx, mir, &pred_terminator.kind);
154 if cx.tcx.is_diagnostic_item(sym::deref_method, pred_fn_def_id);
155 if is_type_diagnostic_item(cx, pred_arg_ty, sym::PathBuf)
156 || is_type_diagnostic_item(cx, pred_arg_ty, sym::OsString);
164 let (local, cannot_move_out) =
165 unwrap_or_continue!(find_stmt_assigns_to(cx, mir, pred_arg, true, ps[0]));
166 let loc = mir::Location {
168 statement_index: mir.basic_blocks[bb].statements.len(),
171 // This can be turned into `res = move local` if `arg` and `cloned` are not borrowed
172 // at the last statement:
175 // pred_arg = &local;
176 // cloned = deref(pred_arg);
178 // StorageDead(pred_arg);
179 // res = to_path_buf(cloned);
181 if cannot_move_out || !possible_borrower.at_most_borrowers(cx, &[arg, cloned], local, loc) {
185 (local, deref_clone_ret)
188 let clone_usage = if local == ret_local {
191 cloned_consume_or_mutate_loc: None,
192 clone_consumed_or_mutated: true,
195 let clone_usage = visit_clone_usage(local, ret_local, mir, bb);
196 if clone_usage.cloned_used && clone_usage.clone_consumed_or_mutated {
197 // cloned value is used, and the clone is modified or moved
199 } else if let Some(loc) = clone_usage.cloned_consume_or_mutate_loc {
200 // cloned value is mutated, and the clone is alive.
201 if possible_borrower.local_is_alive_at(ret_local, loc) {
208 let span = terminator.source_info.span;
209 let scope = terminator.source_info.scope;
210 let node = mir.source_scopes[scope]
213 .assert_crate_local()
217 if let Some(snip) = snippet_opt(cx, span);
218 if let Some(dot) = snip.rfind('.');
220 let sugg_span = span.with_lo(
221 span.lo() + BytePos(u32::try_from(dot).unwrap())
223 let mut app = Applicability::MaybeIncorrect;
225 let call_snip = &snip[dot + 1..];
226 // Machine applicable when `call_snip` looks like `foobar()`
227 if let Some(call_snip) = call_snip.strip_suffix("()").map(str::trim) {
228 if call_snip.as_bytes().iter().all(|b| b.is_ascii_alphabetic() || *b == b'_') {
229 app = Applicability::MachineApplicable;
233 span_lint_hir_and_then(cx, REDUNDANT_CLONE, node, sugg_span, "redundant clone", |diag| {
234 diag.span_suggestion(
240 if clone_usage.cloned_used {
243 "cloned value is neither consumed nor mutated",
247 span.with_hi(span.lo() + BytePos(u32::try_from(dot).unwrap())),
248 "this value is dropped without further use",
253 span_lint_hir(cx, REDUNDANT_CLONE, node, span, "redundant clone");
260 /// If `kind` is `y = func(x: &T)` where `T: !Copy`, returns `(DefId of func, x, T, y)`.
261 fn is_call_with_ref_arg<'tcx>(
262 cx: &LateContext<'tcx>,
263 mir: &'tcx mir::Body<'tcx>,
264 kind: &'tcx mir::TerminatorKind<'tcx>,
265 ) -> Option<(def_id::DefId, mir::Local, Ty<'tcx>, mir::Local)> {
267 if let mir::TerminatorKind::Call { func, args, destination, .. } = kind;
269 if let mir::Operand::Move(mir::Place { local, .. }) = &args[0];
270 if let ty::FnDef(def_id, _) = *func.ty(mir, cx.tcx).kind();
271 if let (inner_ty, 1) = walk_ptrs_ty_depth(args[0].ty(mir, cx.tcx));
272 if !is_copy(cx, inner_ty);
274 Some((def_id, *local, inner_ty, destination.as_local()?))
281 type CannotMoveOut = bool;
283 /// Finds the first `to = (&)from`, and returns
284 /// ``Some((from, whether `from` cannot be moved out))``.
285 fn find_stmt_assigns_to<'tcx>(
286 cx: &LateContext<'tcx>,
287 mir: &mir::Body<'tcx>,
288 to_local: mir::Local,
291 ) -> Option<(mir::Local, CannotMoveOut)> {
292 let rvalue = mir.basic_blocks[bb].statements.iter().rev().find_map(|stmt| {
293 if let mir::StatementKind::Assign(box (mir::Place { local, .. }, v)) = &stmt.kind {
294 return if *local == to_local { Some(v) } else { None };
300 match (by_ref, rvalue) {
301 (true, mir::Rvalue::Ref(_, _, place)) | (false, mir::Rvalue::Use(mir::Operand::Copy(place))) => {
302 Some(base_local_and_movability(cx, mir, *place))
304 (false, mir::Rvalue::Ref(_, _, place)) => {
305 if let [mir::ProjectionElem::Deref] = place.as_ref().projection {
306 Some(base_local_and_movability(cx, mir, *place))
315 /// Extracts and returns the undermost base `Local` of given `place`. Returns `place` itself
316 /// if it is already a `Local`.
318 /// Also reports whether given `place` cannot be moved out.
319 fn base_local_and_movability<'tcx>(
320 cx: &LateContext<'tcx>,
321 mir: &mir::Body<'tcx>,
322 place: mir::Place<'tcx>,
323 ) -> (mir::Local, CannotMoveOut) {
324 use rustc_middle::mir::PlaceRef;
326 // Dereference. You cannot move things out from a borrowed value.
327 let mut deref = false;
328 // Accessing a field of an ADT that has `Drop`. Moving the field out will cause E0509.
329 let mut field = false;
330 // If projection is a slice index then clone can be removed only if the
331 // underlying type implements Copy
332 let mut slice = false;
334 let PlaceRef { local, mut projection } = place.as_ref();
335 while let [base @ .., elem] = projection {
337 deref |= matches!(elem, mir::ProjectionElem::Deref);
338 field |= matches!(elem, mir::ProjectionElem::Field(..))
339 && has_drop(cx, mir::Place::ty_from(local, projection, &mir.local_decls, cx.tcx).ty);
340 slice |= matches!(elem, mir::ProjectionElem::Index(..))
341 && !is_copy(cx, mir::Place::ty_from(local, projection, &mir.local_decls, cx.tcx).ty);
344 (local, deref || field || slice)
349 /// Whether the cloned value is used after the clone.
351 /// The first location where the cloned value is consumed or mutated, if any.
352 cloned_consume_or_mutate_loc: Option<mir::Location>,
353 /// Whether the clone value is mutated.
354 clone_consumed_or_mutated: bool,
357 fn visit_clone_usage(cloned: mir::Local, clone: mir::Local, mir: &mir::Body<'_>, bb: mir::BasicBlock) -> CloneUsage {
360 local_use_locs: cloned_use_locs,
361 local_consume_or_mutate_locs: cloned_consume_or_mutate_locs,
365 local_consume_or_mutate_locs: clone_consume_or_mutate_locs,
367 )) = visit_local_usage(
372 statement_index: mir.basic_blocks[bb].statements.len(),
375 .map(|mut vec| (vec.remove(0), vec.remove(0)))
378 cloned_used: !cloned_use_locs.is_empty(),
379 cloned_consume_or_mutate_loc: cloned_consume_or_mutate_locs.first().copied(),
380 // Consider non-temporary clones consumed.
381 // TODO: Actually check for mutation of non-temporaries.
382 clone_consumed_or_mutated: mir.local_kind(clone) != mir::LocalKind::Temp
383 || !clone_consume_or_mutate_locs.is_empty(),
388 cloned_consume_or_mutate_loc: None,
389 clone_consumed_or_mutated: true,