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