]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/redundant_clone.rs
non_copy_const: remove incorrect suggestion
[rust.git] / clippy_lints / src / redundant_clone.rs
1 use crate::utils::{
2     has_drop, is_copy, match_def_path, match_type, paths, snippet_opt, span_lint_hir, span_lint_hir_and_then,
3     walk_ptrs_ty_depth,
4 };
5 use if_chain::if_chain;
6 use matches::matches;
7 use rustc::hir::intravisit::FnKind;
8 use rustc::hir::{def_id, Body, FnDecl, HirId};
9 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
10 use rustc::mir::{
11     self, traversal,
12     visit::{MutatingUseContext, PlaceContext, Visitor},
13     TerminatorKind,
14 };
15 use rustc::ty::{self, Ty};
16 use rustc::{declare_lint_pass, declare_tool_lint};
17 use rustc_errors::Applicability;
18 use std::convert::TryFrom;
19 use syntax::source_map::{BytePos, Span};
20
21 macro_rules! unwrap_or_continue {
22     ($x:expr) => {
23         match $x {
24             Some(x) => x,
25             None => continue,
26         }
27     };
28 }
29
30 declare_clippy_lint! {
31     /// **What it does:** Checks for a redudant `clone()` (and its relatives) which clones an owned
32     /// value that is going to be dropped without further use.
33     ///
34     /// **Why is this bad?** It is not always possible for the compiler to eliminate useless
35     /// allocations and deallocations generated by redundant `clone()`s.
36     ///
37     /// **Known problems:**
38     ///
39     /// * Suggestions made by this lint could require NLL to be enabled.
40     /// * False-positive if there is a borrow preventing the value from moving out.
41     ///
42     /// ```rust
43     /// # fn foo(x: String) {}
44     /// let x = String::new();
45     ///
46     /// let y = &x;
47     ///
48     /// foo(x.clone()); // This lint suggests to remove this `clone()`
49     /// ```
50     ///
51     /// **Example:**
52     /// ```rust
53     /// # use std::path::Path;
54     /// # #[derive(Clone)]
55     /// # struct Foo;
56     /// # impl Foo {
57     /// #     fn new() -> Self { Foo {} }
58     /// # }
59     /// # fn call(x: Foo) {}
60     /// {
61     ///     let x = Foo::new();
62     ///     call(x.clone());
63     ///     call(x.clone()); // this can just pass `x`
64     /// }
65     ///
66     /// ["lorem", "ipsum"].join(" ").to_string();
67     ///
68     /// Path::new("/a/b").join("c").to_path_buf();
69     /// ```
70     pub REDUNDANT_CLONE,
71     nursery,
72     "`clone()` of an owned value that is going to be dropped immediately"
73 }
74
75 declare_lint_pass!(RedundantClone => [REDUNDANT_CLONE]);
76
77 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RedundantClone {
78     #[allow(clippy::too_many_lines)]
79     fn check_fn(
80         &mut self,
81         cx: &LateContext<'a, 'tcx>,
82         _: FnKind<'tcx>,
83         _: &'tcx FnDecl,
84         body: &'tcx Body,
85         _: Span,
86         _: HirId,
87     ) {
88         let def_id = cx.tcx.hir().body_owner_def_id(body.id());
89         let mir = cx.tcx.optimized_mir(def_id);
90
91         for (bb, bbdata) in mir.basic_blocks().iter_enumerated() {
92             let terminator = bbdata.terminator();
93
94             if terminator.source_info.span.from_expansion() {
95                 continue;
96             }
97
98             // Give up on loops
99             if terminator.successors().any(|s| *s == bb) {
100                 continue;
101             }
102
103             let (fn_def_id, arg, arg_ty, _) = unwrap_or_continue!(is_call_with_ref_arg(cx, mir, &terminator.kind));
104
105             let from_borrow = match_def_path(cx, fn_def_id, &paths::CLONE_TRAIT_METHOD)
106                 || match_def_path(cx, fn_def_id, &paths::TO_OWNED_METHOD)
107                 || (match_def_path(cx, fn_def_id, &paths::TO_STRING_METHOD) && match_type(cx, arg_ty, &paths::STRING));
108
109             let from_deref = !from_borrow
110                 && (match_def_path(cx, fn_def_id, &paths::PATH_TO_PATH_BUF)
111                     || match_def_path(cx, fn_def_id, &paths::OS_STR_TO_OS_STRING));
112
113             if !from_borrow && !from_deref {
114                 continue;
115             }
116
117             // _1 in MIR `{ _2 = &_1; clone(move _2); }` or `{ _2 = _1; to_path_buf(_2); } (from_deref)
118             // In case of `from_deref`, `arg` is already a reference since it is `deref`ed in the previous
119             // block.
120             let (cloned, cannot_move_out) = unwrap_or_continue!(find_stmt_assigns_to(
121                 cx,
122                 mir,
123                 arg,
124                 from_borrow,
125                 bbdata.statements.iter()
126             ));
127
128             if from_borrow && cannot_move_out {
129                 continue;
130             }
131
132             // _1 in MIR `{ _2 = &_1; _3 = deref(move _2); } -> { _4 = _3; to_path_buf(move _4); }`
133             let referent = if from_deref {
134                 let ps = mir.predecessors_for(bb);
135                 if ps.len() != 1 {
136                     continue;
137                 }
138                 let pred_terminator = mir[ps[0]].terminator();
139
140                 let pred_arg = if_chain! {
141                     if let Some((pred_fn_def_id, pred_arg, pred_arg_ty, Some(res))) =
142                         is_call_with_ref_arg(cx, mir, &pred_terminator.kind);
143                     if res.base == mir::PlaceBase::Local(cloned);
144                     if match_def_path(cx, pred_fn_def_id, &paths::DEREF_TRAIT_METHOD);
145                     if match_type(cx, pred_arg_ty, &paths::PATH_BUF)
146                         || match_type(cx, pred_arg_ty, &paths::OS_STRING);
147                     then {
148                         pred_arg
149                     } else {
150                         continue;
151                     }
152                 };
153
154                 let (local, cannot_move_out) = unwrap_or_continue!(find_stmt_assigns_to(
155                     cx,
156                     mir,
157                     pred_arg,
158                     true,
159                     mir[ps[0]].statements.iter()
160                 ));
161                 if cannot_move_out {
162                     continue;
163                 }
164                 local
165             } else {
166                 cloned
167             };
168
169             let used_later = traversal::ReversePostorder::new(&mir, bb).skip(1).any(|(tbb, tdata)| {
170                 // Give up on loops
171                 if tdata.terminator().successors().any(|s| *s == bb) {
172                     return true;
173                 }
174
175                 let mut vis = LocalUseVisitor {
176                     local: referent,
177                     used_other_than_drop: false,
178                 };
179                 vis.visit_basic_block_data(tbb, tdata);
180                 vis.used_other_than_drop
181             });
182
183             if !used_later {
184                 let span = terminator.source_info.span;
185                 let node = if let mir::ClearCrossCrate::Set(scope_local_data) = &mir.source_scope_local_data {
186                     scope_local_data[terminator.source_info.scope].lint_root
187                 } else {
188                     unreachable!()
189                 };
190
191                 if_chain! {
192                     if let Some(snip) = snippet_opt(cx, span);
193                     if let Some(dot) = snip.rfind('.');
194                     then {
195                         let sugg_span = span.with_lo(
196                             span.lo() + BytePos(u32::try_from(dot).unwrap())
197                         );
198
199                         span_lint_hir_and_then(cx, REDUNDANT_CLONE, node, sugg_span, "redundant clone", |db| {
200                             db.span_suggestion(
201                                 sugg_span,
202                                 "remove this",
203                                 String::new(),
204                                 Applicability::MaybeIncorrect,
205                             );
206                             db.span_note(
207                                 span.with_hi(span.lo() + BytePos(u32::try_from(dot).unwrap())),
208                                 "this value is dropped without further use",
209                             );
210                         });
211                     } else {
212                         span_lint_hir(cx, REDUNDANT_CLONE, node, span, "redundant clone");
213                     }
214                 }
215             }
216         }
217     }
218 }
219
220 /// If `kind` is `y = func(x: &T)` where `T: !Copy`, returns `(DefId of func, x, T, y)`.
221 fn is_call_with_ref_arg<'tcx>(
222     cx: &LateContext<'_, 'tcx>,
223     mir: &'tcx mir::Body<'tcx>,
224     kind: &'tcx mir::TerminatorKind<'tcx>,
225 ) -> Option<(def_id::DefId, mir::Local, Ty<'tcx>, Option<&'tcx mir::Place<'tcx>>)> {
226     if_chain! {
227         if let TerminatorKind::Call { func, args, destination, .. } = kind;
228         if args.len() == 1;
229         if let mir::Operand::Move(mir::Place { base: mir::PlaceBase::Local(local), .. }) = &args[0];
230         if let ty::FnDef(def_id, _) = func.ty(&*mir, cx.tcx).sty;
231         if let (inner_ty, 1) = walk_ptrs_ty_depth(args[0].ty(&*mir, cx.tcx));
232         if !is_copy(cx, inner_ty);
233         then {
234             Some((def_id, *local, inner_ty, destination.as_ref().map(|(dest, _)| dest)))
235         } else {
236             None
237         }
238     }
239 }
240
241 type CannotMoveOut = bool;
242
243 /// Finds the first `to = (&)from`, and returns
244 /// ``Some((from, [`true` if `from` cannot be moved out]))``.
245 fn find_stmt_assigns_to<'a, 'tcx: 'a>(
246     cx: &LateContext<'_, 'tcx>,
247     mir: &mir::Body<'tcx>,
248     to: mir::Local,
249     by_ref: bool,
250     stmts: impl DoubleEndedIterator<Item = &'a mir::Statement<'tcx>>,
251 ) -> Option<(mir::Local, CannotMoveOut)> {
252     stmts
253         .rev()
254         .find_map(|stmt| {
255             if let mir::StatementKind::Assign(box (
256                 mir::Place {
257                     base: mir::PlaceBase::Local(local),
258                     ..
259                 },
260                 v,
261             )) = &stmt.kind
262             {
263                 if *local == to {
264                     return Some(v);
265                 }
266             }
267
268             None
269         })
270         .and_then(|v| {
271             if by_ref {
272                 if let mir::Rvalue::Ref(_, _, ref place) = v {
273                     return base_local_and_movability(cx, mir, place);
274                 }
275             } else if let mir::Rvalue::Use(mir::Operand::Copy(ref place)) = v {
276                 return base_local_and_movability(cx, mir, place);
277             }
278             None
279         })
280 }
281
282 /// Extracts and returns the undermost base `Local` of given `place`. Returns `place` itself
283 /// if it is already a `Local`.
284 ///
285 /// Also reports whether given `place` cannot be moved out.
286 fn base_local_and_movability<'tcx>(
287     cx: &LateContext<'_, 'tcx>,
288     mir: &mir::Body<'tcx>,
289     place: &mir::Place<'tcx>,
290 ) -> Option<(mir::Local, CannotMoveOut)> {
291     use rustc::mir::Place;
292     use rustc::mir::PlaceBase;
293     use rustc::mir::PlaceRef;
294
295     // Dereference. You cannot move things out from a borrowed value.
296     let mut deref = false;
297     // Accessing a field of an ADT that has `Drop`. Moving the field out will cause E0509.
298     let mut field = false;
299
300     let PlaceRef {
301         base: place_base,
302         mut projection,
303     } = place.as_ref();
304     if let PlaceBase::Local(local) = place_base {
305         while let [base @ .., elem] = projection {
306             projection = base;
307             deref = matches!(elem, mir::ProjectionElem::Deref);
308             field = !field
309                 && matches!(elem, mir::ProjectionElem::Field(..))
310                 && has_drop(cx, Place::ty_from(place_base, projection, &mir.local_decls, cx.tcx).ty);
311         }
312
313         Some((*local, deref || field))
314     } else {
315         None
316     }
317 }
318
319 struct LocalUseVisitor {
320     local: mir::Local,
321     used_other_than_drop: bool,
322 }
323
324 impl<'tcx> mir::visit::Visitor<'tcx> for LocalUseVisitor {
325     fn visit_basic_block_data(&mut self, block: mir::BasicBlock, data: &mir::BasicBlockData<'tcx>) {
326         let statements = &data.statements;
327         for (statement_index, statement) in statements.iter().enumerate() {
328             self.visit_statement(statement, mir::Location { block, statement_index });
329
330             // Once flagged, skip remaining statements
331             if self.used_other_than_drop {
332                 return;
333             }
334         }
335
336         self.visit_terminator(
337             data.terminator(),
338             mir::Location {
339                 block,
340                 statement_index: statements.len(),
341             },
342         );
343     }
344
345     fn visit_local(&mut self, local: &mir::Local, ctx: PlaceContext, _: mir::Location) {
346         match ctx {
347             PlaceContext::MutatingUse(MutatingUseContext::Drop) | PlaceContext::NonUse(_) => return,
348             _ => {},
349         }
350
351         if *local == self.local {
352             self.used_other_than_drop = true;
353         }
354     }
355 }