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