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