]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/redundant_clone.rs
Rollup merge of #106410 - clubby789:borrow-mut-self-mut-self-diag, r=compiler-errors
[rust.git] / src / tools / clippy / clippy_lints / src / redundant_clone.rs
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};
15 use rustc_span::sym;
16
17 macro_rules! unwrap_or_continue {
18     ($x:expr) => {
19         match $x {
20             Some(x) => x,
21             None => continue,
22         }
23     };
24 }
25
26 declare_clippy_lint! {
27     /// ### What it does
28     /// Checks for a redundant `clone()` (and its relatives) which clones an owned
29     /// value that is going to be dropped without further use.
30     ///
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.
34     ///
35     /// ### Known problems
36     /// False-negatives: analysis performed by this lint is conservative and limited.
37     ///
38     /// ### Example
39     /// ```rust
40     /// # use std::path::Path;
41     /// # #[derive(Clone)]
42     /// # struct Foo;
43     /// # impl Foo {
44     /// #     fn new() -> Self { Foo {} }
45     /// # }
46     /// # fn call(x: Foo) {}
47     /// {
48     ///     let x = Foo::new();
49     ///     call(x.clone());
50     ///     call(x.clone()); // this can just pass `x`
51     /// }
52     ///
53     /// ["lorem", "ipsum"].join(" ").to_string();
54     ///
55     /// Path::new("/a/b").join("c").to_path_buf();
56     /// ```
57     #[clippy::version = "1.32.0"]
58     pub REDUNDANT_CLONE,
59     perf,
60     "`clone()` of an owned value that is going to be dropped immediately"
61 }
62
63 declare_lint_pass!(RedundantClone => [REDUNDANT_CLONE]);
64
65 impl<'tcx> LateLintPass<'tcx> for RedundantClone {
66     #[expect(clippy::too_many_lines)]
67     fn check_fn(
68         &mut self,
69         cx: &LateContext<'tcx>,
70         _: FnKind<'tcx>,
71         _: &'tcx FnDecl<'_>,
72         body: &'tcx Body<'_>,
73         _: Span,
74         _: HirId,
75     ) {
76         let def_id = cx.tcx.hir().body_owner_def_id(body.id());
77
78         // Building MIR for `fn`s with unsatisfiable preds results in ICE.
79         if fn_has_unsatisfiable_preds(cx, def_id.to_def_id()) {
80             return;
81         }
82
83         let mir = cx.tcx.optimized_mir(def_id.to_def_id());
84
85         let mut possible_borrower = PossibleBorrowerMap::new(cx, mir);
86
87         for (bb, bbdata) in mir.basic_blocks.iter_enumerated() {
88             let terminator = bbdata.terminator();
89
90             if terminator.source_info.span.from_expansion() {
91                 continue;
92             }
93
94             // Give up on loops
95             if terminator.successors().any(|s| s == bb) {
96                 continue;
97             }
98
99             let (fn_def_id, arg, arg_ty, clone_ret) =
100                 unwrap_or_continue!(is_call_with_ref_arg(cx, mir, &terminator.kind));
101
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));
106
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));
110
111             if !from_borrow && !from_deref {
112                 continue;
113             }
114
115             if let ty::Adt(def, _) = arg_ty.kind() {
116                 if def.is_manually_drop() {
117                     continue;
118                 }
119             }
120
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));
123
124             let loc = mir::Location {
125                 block: bb,
126                 statement_index: bbdata.statements.len(),
127             };
128
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.
133
134                 if cannot_move_out || !possible_borrower.at_most_borrowers(cx, &[arg], cloned, loc) {
135                     continue;
136                 }
137
138                 (cloned, clone_ret)
139             } else {
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.
142
143                 let ps = &mir.basic_blocks.predecessors()[bb];
144                 if ps.len() != 1 {
145                     continue;
146                 }
147                 let pred_terminator = mir[ps[0]].terminator();
148
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);
153                     if res == cloned;
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);
157                     then {
158                         (pred_arg, res)
159                     } else {
160                         continue;
161                     }
162                 };
163
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 {
167                     block: bb,
168                     statement_index: mir.basic_blocks[bb].statements.len(),
169                 };
170
171                 // This can be turned into `res = move local` if `arg` and `cloned` are not borrowed
172                 // at the last statement:
173                 //
174                 // ```
175                 // pred_arg = &local;
176                 // cloned = deref(pred_arg);
177                 // arg = &cloned;
178                 // StorageDead(pred_arg);
179                 // res = to_path_buf(cloned);
180                 // ```
181                 if cannot_move_out || !possible_borrower.at_most_borrowers(cx, &[arg, cloned], local, loc) {
182                     continue;
183                 }
184
185                 (local, deref_clone_ret)
186             };
187
188             let clone_usage = if local == ret_local {
189                 CloneUsage {
190                     cloned_used: false,
191                     cloned_consume_or_mutate_loc: None,
192                     clone_consumed_or_mutated: true,
193                 }
194             } else {
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
198                     continue;
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) {
202                         continue;
203                     }
204                 }
205                 clone_usage
206             };
207
208             let span = terminator.source_info.span;
209             let scope = terminator.source_info.scope;
210             let node = mir.source_scopes[scope]
211                 .local_data
212                 .as_ref()
213                 .assert_crate_local()
214                 .lint_root;
215
216             if_chain! {
217                 if let Some(snip) = snippet_opt(cx, span);
218                 if let Some(dot) = snip.rfind('.');
219                 then {
220                     let sugg_span = span.with_lo(
221                         span.lo() + BytePos(u32::try_from(dot).unwrap())
222                     );
223                     let mut app = Applicability::MaybeIncorrect;
224
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;
230                         }
231                     }
232
233                     span_lint_hir_and_then(cx, REDUNDANT_CLONE, node, sugg_span, "redundant clone", |diag| {
234                         diag.span_suggestion(
235                             sugg_span,
236                             "remove this",
237                             "",
238                             app,
239                         );
240                         if clone_usage.cloned_used {
241                             diag.span_note(
242                                 span,
243                                 "cloned value is neither consumed nor mutated",
244                             );
245                         } else {
246                             diag.span_note(
247                                 span.with_hi(span.lo() + BytePos(u32::try_from(dot).unwrap())),
248                                 "this value is dropped without further use",
249                             );
250                         }
251                     });
252                 } else {
253                     span_lint_hir(cx, REDUNDANT_CLONE, node, span, "redundant clone");
254                 }
255             }
256         }
257     }
258 }
259
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)> {
266     if_chain! {
267         if let mir::TerminatorKind::Call { func, args, destination, .. } = kind;
268         if args.len() == 1;
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);
273         then {
274             Some((def_id, *local, inner_ty, destination.as_local()?))
275         } else {
276             None
277         }
278     }
279 }
280
281 type CannotMoveOut = bool;
282
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,
289     by_ref: bool,
290     bb: mir::BasicBlock,
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 };
295         }
296
297         None
298     })?;
299
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))
303         },
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))
307             } else {
308                 None
309             }
310         },
311         _ => None,
312     }
313 }
314
315 /// Extracts and returns the undermost base `Local` of given `place`. Returns `place` itself
316 /// if it is already a `Local`.
317 ///
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;
325
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;
333
334     let PlaceRef { local, mut projection } = place.as_ref();
335     while let [base @ .., elem] = projection {
336         projection = base;
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);
342     }
343
344     (local, deref || field || slice)
345 }
346
347 #[derive(Default)]
348 struct CloneUsage {
349     /// Whether the cloned value is used after the clone.
350     cloned_used: bool,
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,
355 }
356
357 fn visit_clone_usage(cloned: mir::Local, clone: mir::Local, mir: &mir::Body<'_>, bb: mir::BasicBlock) -> CloneUsage {
358     if let Some((
359         LocalUsage {
360             local_use_locs: cloned_use_locs,
361             local_consume_or_mutate_locs: cloned_consume_or_mutate_locs,
362         },
363         LocalUsage {
364             local_use_locs: _,
365             local_consume_or_mutate_locs: clone_consume_or_mutate_locs,
366         },
367     )) = visit_local_usage(
368         &[cloned, clone],
369         mir,
370         mir::Location {
371             block: bb,
372             statement_index: mir.basic_blocks[bb].statements.len(),
373         },
374     )
375     .map(|mut vec| (vec.remove(0), vec.remove(0)))
376     {
377         CloneUsage {
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(),
384         }
385     } else {
386         CloneUsage {
387             cloned_used: true,
388             cloned_consume_or_mutate_loc: None,
389             clone_consumed_or_mutated: true,
390         }
391     }
392 }