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