]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/redundant_clone.rs
MutImmutable -> Immutable, MutMutable -> Mutable, CaptureClause -> CaptureBy
[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 as _},
13 };
14 use rustc::ty::{self, fold::TypeVisitor, Ty};
15 use rustc::{declare_lint_pass, declare_tool_lint};
16 use rustc_data_structures::{fx::FxHashMap, transitive_relation::TransitiveRelation};
17 use rustc_errors::Applicability;
18 use rustc_index::bit_set::{BitSet, HybridBitSet};
19 use rustc_mir::dataflow::{
20     do_dataflow, BitDenotation, BottomValue, DataflowResults, DataflowResultsCursor, DebugFormatted, GenKillSet,
21 };
22 use std::convert::TryFrom;
23 use syntax::source_map::{BytePos, Span};
24
25 macro_rules! unwrap_or_continue {
26     ($x:expr) => {
27         match $x {
28             Some(x) => x,
29             None => continue,
30         }
31     };
32 }
33
34 declare_clippy_lint! {
35     /// **What it does:** Checks for a redudant `clone()` (and its relatives) which clones an owned
36     /// value that is going to be dropped without further use.
37     ///
38     /// **Why is this bad?** It is not always possible for the compiler to eliminate useless
39     /// allocations and deallocations generated by redundant `clone()`s.
40     ///
41     /// **Known problems:**
42     ///
43     /// False-negatives: analysis performed by this lint is conservative and limited.
44     ///
45     /// **Example:**
46     /// ```rust
47     /// # use std::path::Path;
48     /// # #[derive(Clone)]
49     /// # struct Foo;
50     /// # impl Foo {
51     /// #     fn new() -> Self { Foo {} }
52     /// # }
53     /// # fn call(x: Foo) {}
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     pub REDUNDANT_CLONE,
65     perf,
66     "`clone()` of an owned value that is going to be dropped immediately"
67 }
68
69 declare_lint_pass!(RedundantClone => [REDUNDANT_CLONE]);
70
71 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RedundantClone {
72     #[allow(clippy::too_many_lines)]
73     fn check_fn(
74         &mut self,
75         cx: &LateContext<'a, 'tcx>,
76         _: FnKind<'tcx>,
77         _: &'tcx FnDecl,
78         body: &'tcx Body,
79         _: Span,
80         _: HirId,
81     ) {
82         let def_id = cx.tcx.hir().body_owner_def_id(body.id());
83         let mir = cx.tcx.optimized_mir(def_id);
84
85         let dead_unwinds = BitSet::new_empty(mir.basic_blocks().len());
86         let maybe_storage_live_result = do_dataflow(
87             cx.tcx,
88             mir,
89             def_id,
90             &[],
91             &dead_unwinds,
92             MaybeStorageLive::new(mir),
93             |bd, p| DebugFormatted::new(&bd.body.local_decls[p]),
94         );
95         let mut possible_borrower = {
96             let mut vis = PossibleBorrowerVisitor::new(cx, mir);
97             vis.visit_body(mir);
98             vis.into_map(cx, maybe_storage_live_result)
99         };
100
101         for (bb, bbdata) in mir.basic_blocks().iter_enumerated() {
102             let terminator = bbdata.terminator();
103
104             if terminator.source_info.span.from_expansion() {
105                 continue;
106             }
107
108             // Give up on loops
109             if terminator.successors().any(|s| *s == bb) {
110                 continue;
111             }
112
113             let (fn_def_id, arg, arg_ty, _) = unwrap_or_continue!(is_call_with_ref_arg(cx, mir, &terminator.kind));
114
115             let from_borrow = match_def_path(cx, fn_def_id, &paths::CLONE_TRAIT_METHOD)
116                 || match_def_path(cx, fn_def_id, &paths::TO_OWNED_METHOD)
117                 || (match_def_path(cx, fn_def_id, &paths::TO_STRING_METHOD) && match_type(cx, arg_ty, &paths::STRING));
118
119             let from_deref = !from_borrow
120                 && (match_def_path(cx, fn_def_id, &paths::PATH_TO_PATH_BUF)
121                     || match_def_path(cx, fn_def_id, &paths::OS_STR_TO_OS_STRING));
122
123             if !from_borrow && !from_deref {
124                 continue;
125             }
126
127             // `{ cloned = &arg; clone(move cloned); }` or `{ cloned = &arg; to_path_buf(cloned); }`
128             let (cloned, cannot_move_out) = unwrap_or_continue!(find_stmt_assigns_to(cx, mir, arg, from_borrow, bb));
129
130             let loc = mir::Location {
131                 block: bb,
132                 statement_index: bbdata.statements.len(),
133             };
134
135             // Cloned local
136             let local = if from_borrow {
137                 // `res = clone(arg)` can be turned into `res = move arg;`
138                 // if `arg` is the only borrow of `cloned` at this point.
139
140                 if cannot_move_out || !possible_borrower.only_borrowers(&[arg], cloned, loc) {
141                     continue;
142                 }
143
144                 cloned
145             } else {
146                 // `arg` is a reference as it is `.deref()`ed in the previous block.
147                 // Look into the predecessor block and find out the source of deref.
148
149                 let ps = mir.predecessors_for(bb);
150                 if ps.len() != 1 {
151                     continue;
152                 }
153                 let pred_terminator = mir[ps[0]].terminator();
154
155                 // receiver of the `deref()` call
156                 let pred_arg = if_chain! {
157                     if let Some((pred_fn_def_id, pred_arg, pred_arg_ty, Some(res))) =
158                         is_call_with_ref_arg(cx, mir, &pred_terminator.kind);
159                     if res.base == mir::PlaceBase::Local(cloned);
160                     if match_def_path(cx, pred_fn_def_id, &paths::DEREF_TRAIT_METHOD);
161                     if match_type(cx, pred_arg_ty, &paths::PATH_BUF)
162                         || match_type(cx, pred_arg_ty, &paths::OS_STRING);
163                     then {
164                         pred_arg
165                     } else {
166                         continue;
167                     }
168                 };
169
170                 let (local, cannot_move_out) =
171                     unwrap_or_continue!(find_stmt_assigns_to(cx, mir, pred_arg, true, ps[0]));
172                 let loc = mir::Location {
173                     block: bb,
174                     statement_index: mir.basic_blocks()[bb].statements.len(),
175                 };
176
177                 // This can be turned into `res = move local` if `arg` and `cloned` are not borrowed
178                 // at the last statement:
179                 //
180                 // ```
181                 // pred_arg = &local;
182                 // cloned = deref(pred_arg);
183                 // arg = &cloned;
184                 // StorageDead(pred_arg);
185                 // res = to_path_buf(cloned);
186                 // ```
187                 if cannot_move_out || !possible_borrower.only_borrowers(&[arg, cloned], local, loc) {
188                     continue;
189                 }
190
191                 local
192             };
193
194             // `local` cannot be moved out if it is used later
195             let used_later = traversal::ReversePostorder::new(&mir, bb).skip(1).any(|(tbb, tdata)| {
196                 // Give up on loops
197                 if tdata.terminator().successors().any(|s| *s == bb) {
198                     return true;
199                 }
200
201                 let mut vis = LocalUseVisitor {
202                     local,
203                     used_other_than_drop: false,
204                 };
205                 vis.visit_basic_block_data(tbb, tdata);
206                 vis.used_other_than_drop
207             });
208
209             if !used_later {
210                 let span = terminator.source_info.span;
211                 let node = if let mir::ClearCrossCrate::Set(scope_local_data) = &mir.source_scope_local_data {
212                     scope_local_data[terminator.source_info.scope].lint_root
213                 } else {
214                     unreachable!()
215                 };
216
217                 if_chain! {
218                     if let Some(snip) = snippet_opt(cx, span);
219                     if let Some(dot) = snip.rfind('.');
220                     then {
221                         let sugg_span = span.with_lo(
222                             span.lo() + BytePos(u32::try_from(dot).unwrap())
223                         );
224                         let mut app = Applicability::MaybeIncorrect;
225
226                         let mut call_snip = &snip[dot + 1..];
227                         // Machine applicable when `call_snip` looks like `foobar()`
228                         if call_snip.ends_with("()") {
229                             call_snip = call_snip[..call_snip.len()-2].trim();
230                             if call_snip.as_bytes().iter().all(|b| b.is_ascii_alphabetic() || *b == b'_') {
231                                 app = Applicability::MachineApplicable;
232                             }
233                         }
234
235                         span_lint_hir_and_then(cx, REDUNDANT_CLONE, node, sugg_span, "redundant clone", |db| {
236                             db.span_suggestion(
237                                 sugg_span,
238                                 "remove this",
239                                 String::new(),
240                                 app,
241                             );
242                             db.span_note(
243                                 span.with_hi(span.lo() + BytePos(u32::try_from(dot).unwrap())),
244                                 "this value is dropped without further use",
245                             );
246                         });
247                     } else {
248                         span_lint_hir(cx, REDUNDANT_CLONE, node, span, "redundant clone");
249                     }
250                 }
251             }
252         }
253     }
254 }
255
256 /// If `kind` is `y = func(x: &T)` where `T: !Copy`, returns `(DefId of func, x, T, y)`.
257 fn is_call_with_ref_arg<'tcx>(
258     cx: &LateContext<'_, 'tcx>,
259     mir: &'tcx mir::Body<'tcx>,
260     kind: &'tcx mir::TerminatorKind<'tcx>,
261 ) -> Option<(def_id::DefId, mir::Local, Ty<'tcx>, Option<&'tcx mir::Place<'tcx>>)> {
262     if_chain! {
263         if let mir::TerminatorKind::Call { func, args, destination, .. } = kind;
264         if args.len() == 1;
265         if let mir::Operand::Move(mir::Place { base: mir::PlaceBase::Local(local), .. }) = &args[0];
266         if let ty::FnDef(def_id, _) = func.ty(&*mir, cx.tcx).kind;
267         if let (inner_ty, 1) = walk_ptrs_ty_depth(args[0].ty(&*mir, cx.tcx));
268         if !is_copy(cx, inner_ty);
269         then {
270             Some((def_id, *local, inner_ty, destination.as_ref().map(|(dest, _)| dest)))
271         } else {
272             None
273         }
274     }
275 }
276
277 type CannotMoveOut = bool;
278
279 /// Finds the first `to = (&)from`, and returns
280 /// ``Some((from, whether `from` cannot be moved out))``.
281 fn find_stmt_assigns_to<'tcx>(
282     cx: &LateContext<'_, 'tcx>,
283     mir: &mir::Body<'tcx>,
284     to_local: mir::Local,
285     by_ref: bool,
286     bb: mir::BasicBlock,
287 ) -> Option<(mir::Local, CannotMoveOut)> {
288     let rvalue = mir.basic_blocks()[bb].statements.iter().rev().find_map(|stmt| {
289         if let mir::StatementKind::Assign(box (
290             mir::Place {
291                 base: mir::PlaceBase::Local(local),
292                 ..
293             },
294             v,
295         )) = &stmt.kind
296         {
297             return if *local == to_local { Some(v) } else { None };
298         }
299
300         None
301     })?;
302
303     match (by_ref, &*rvalue) {
304         (true, mir::Rvalue::Ref(_, _, place)) | (false, mir::Rvalue::Use(mir::Operand::Copy(place))) => {
305             base_local_and_movability(cx, mir, place)
306         },
307         _ => None,
308     }
309 }
310
311 /// Extracts and returns the undermost base `Local` of given `place`. Returns `place` itself
312 /// if it is already a `Local`.
313 ///
314 /// Also reports whether given `place` cannot be moved out.
315 fn base_local_and_movability<'tcx>(
316     cx: &LateContext<'_, 'tcx>,
317     mir: &mir::Body<'tcx>,
318     place: &mir::Place<'tcx>,
319 ) -> Option<(mir::Local, CannotMoveOut)> {
320     use rustc::mir::PlaceRef;
321
322     // Dereference. You cannot move things out from a borrowed value.
323     let mut deref = false;
324     // Accessing a field of an ADT that has `Drop`. Moving the field out will cause E0509.
325     let mut field = false;
326
327     let PlaceRef {
328         base: place_base,
329         mut projection,
330     } = place.as_ref();
331     if let mir::PlaceBase::Local(local) = place_base {
332         while let [base @ .., elem] = projection {
333             projection = base;
334             deref |= matches!(elem, mir::ProjectionElem::Deref);
335             field |= matches!(elem, mir::ProjectionElem::Field(..))
336                 && has_drop(
337                     cx,
338                     mir::Place::ty_from(place_base, projection, &mir.local_decls, cx.tcx).ty,
339                 );
340         }
341
342         Some((*local, deref || field))
343     } else {
344         None
345     }
346 }
347
348 struct LocalUseVisitor {
349     local: mir::Local,
350     used_other_than_drop: bool,
351 }
352
353 impl<'tcx> mir::visit::Visitor<'tcx> for LocalUseVisitor {
354     fn visit_basic_block_data(&mut self, block: mir::BasicBlock, data: &mir::BasicBlockData<'tcx>) {
355         let statements = &data.statements;
356         for (statement_index, statement) in statements.iter().enumerate() {
357             self.visit_statement(statement, mir::Location { block, statement_index });
358
359             // Once flagged, skip remaining statements
360             if self.used_other_than_drop {
361                 return;
362             }
363         }
364
365         self.visit_terminator(
366             data.terminator(),
367             mir::Location {
368                 block,
369                 statement_index: statements.len(),
370             },
371         );
372     }
373
374     fn visit_local(&mut self, local: &mir::Local, ctx: PlaceContext, _: mir::Location) {
375         match ctx {
376             PlaceContext::MutatingUse(MutatingUseContext::Drop) | PlaceContext::NonUse(_) => return,
377             _ => {},
378         }
379
380         if *local == self.local {
381             self.used_other_than_drop = true;
382         }
383     }
384 }
385
386 /// Determines liveness of each local purely based on `StorageLive`/`Dead`.
387 #[derive(Copy, Clone)]
388 struct MaybeStorageLive<'a, 'tcx> {
389     body: &'a mir::Body<'tcx>,
390 }
391
392 impl<'a, 'tcx> MaybeStorageLive<'a, 'tcx> {
393     fn new(body: &'a mir::Body<'tcx>) -> Self {
394         MaybeStorageLive { body }
395     }
396 }
397
398 impl<'a, 'tcx> BitDenotation<'tcx> for MaybeStorageLive<'a, 'tcx> {
399     type Idx = mir::Local;
400     fn name() -> &'static str {
401         "maybe_storage_live"
402     }
403     fn bits_per_block(&self) -> usize {
404         self.body.local_decls.len()
405     }
406
407     fn start_block_effect(&self, on_entry: &mut BitSet<mir::Local>) {
408         for arg in self.body.args_iter() {
409             on_entry.insert(arg);
410         }
411     }
412
413     fn statement_effect(&self, trans: &mut GenKillSet<mir::Local>, loc: mir::Location) {
414         let stmt = &self.body[loc.block].statements[loc.statement_index];
415
416         match stmt.kind {
417             mir::StatementKind::StorageLive(l) => trans.gen(l),
418             mir::StatementKind::StorageDead(l) => trans.kill(l),
419             _ => (),
420         }
421     }
422
423     fn terminator_effect(&self, _trans: &mut GenKillSet<mir::Local>, _loc: mir::Location) {}
424
425     fn propagate_call_return(
426         &self,
427         _in_out: &mut BitSet<mir::Local>,
428         _call_bb: mir::BasicBlock,
429         _dest_bb: mir::BasicBlock,
430         _dest_place: &mir::Place<'tcx>,
431     ) {
432         // Nothing to do when a call returns successfully
433     }
434 }
435
436 impl<'a, 'tcx> BottomValue for MaybeStorageLive<'a, 'tcx> {
437     /// bottom = dead
438     const BOTTOM_VALUE: bool = false;
439 }
440
441 /// Collects the possible borrowers of each local.
442 /// For example, `b = &a; c = &a;` will make `b` and (transitively) `c`
443 /// possible borrowers of `a`.
444 struct PossibleBorrowerVisitor<'a, 'tcx> {
445     possible_borrower: TransitiveRelation<mir::Local>,
446     body: &'a mir::Body<'tcx>,
447     cx: &'a LateContext<'a, 'tcx>,
448 }
449
450 impl<'a, 'tcx> PossibleBorrowerVisitor<'a, 'tcx> {
451     fn new(cx: &'a LateContext<'a, 'tcx>, body: &'a mir::Body<'tcx>) -> Self {
452         Self {
453             possible_borrower: TransitiveRelation::default(),
454             cx,
455             body,
456         }
457     }
458
459     fn into_map(
460         self,
461         cx: &LateContext<'a, 'tcx>,
462         maybe_live: DataflowResults<'tcx, MaybeStorageLive<'a, 'tcx>>,
463     ) -> PossibleBorrower<'a, 'tcx> {
464         let mut map = FxHashMap::default();
465         for row in (1..self.body.local_decls.len()).map(mir::Local::from_usize) {
466             if is_copy(cx, self.body.local_decls[row].ty) {
467                 continue;
468             }
469
470             let borrowers = self.possible_borrower.reachable_from(&row);
471             if !borrowers.is_empty() {
472                 let mut bs = HybridBitSet::new_empty(self.body.local_decls.len());
473                 for &c in borrowers {
474                     if c != mir::Local::from_usize(0) {
475                         bs.insert(c);
476                     }
477                 }
478
479                 if !bs.is_empty() {
480                     map.insert(row, bs);
481                 }
482             }
483         }
484
485         let bs = BitSet::new_empty(self.body.local_decls.len());
486         PossibleBorrower {
487             map,
488             maybe_live: DataflowResultsCursor::new(maybe_live, self.body),
489             bitset: (bs.clone(), bs),
490         }
491     }
492 }
493
494 impl<'a, 'tcx> mir::visit::Visitor<'tcx> for PossibleBorrowerVisitor<'a, 'tcx> {
495     fn visit_assign(&mut self, place: &mir::Place<'tcx>, rvalue: &mir::Rvalue<'_>, _location: mir::Location) {
496         if let mir::PlaceBase::Local(lhs) = place.base {
497             match rvalue {
498                 mir::Rvalue::Ref(_, _, borrowed) => {
499                     if let mir::PlaceBase::Local(borrowed_local) = borrowed.base {
500                         self.possible_borrower.add(borrowed_local, lhs);
501                     }
502                 },
503                 other => {
504                     if !ContainsRegion.visit_ty(place.ty(&self.body.local_decls, self.cx.tcx).ty) {
505                         return;
506                     }
507                     rvalue_locals(other, |rhs| {
508                         if lhs != rhs {
509                             self.possible_borrower.add(rhs, lhs);
510                         }
511                     });
512                 },
513             }
514         }
515     }
516
517     fn visit_terminator(&mut self, terminator: &mir::Terminator<'_>, _loc: mir::Location) {
518         if let mir::TerminatorKind::Call {
519             args,
520             destination:
521                 Some((
522                     mir::Place {
523                         base: mir::PlaceBase::Local(dest),
524                         ..
525                     },
526                     _,
527                 )),
528             ..
529         } = &terminator.kind
530         {
531             // If the call returns something with lifetimes,
532             // let's conservatively assume the returned value contains lifetime of all the arguments.
533             // For example, given `let y: Foo<'a> = foo(x)`, `y` is considered to be a possible borrower of `x`.
534             if !ContainsRegion.visit_ty(&self.body.local_decls[*dest].ty) {
535                 return;
536             }
537
538             for op in args {
539                 match op {
540                     mir::Operand::Copy(p) | mir::Operand::Move(p) => {
541                         if let mir::PlaceBase::Local(arg) = p.base {
542                             self.possible_borrower.add(arg, *dest);
543                         }
544                     },
545                     _ => (),
546                 }
547             }
548         }
549     }
550 }
551
552 struct ContainsRegion;
553
554 impl TypeVisitor<'_> for ContainsRegion {
555     fn visit_region(&mut self, _: ty::Region<'_>) -> bool {
556         true
557     }
558 }
559
560 fn rvalue_locals(rvalue: &mir::Rvalue<'_>, mut visit: impl FnMut(mir::Local)) {
561     use rustc::mir::Rvalue::*;
562
563     let mut visit_op = |op: &mir::Operand<'_>| match op {
564         mir::Operand::Copy(p) | mir::Operand::Move(p) => {
565             if let mir::PlaceBase::Local(l) = p.base {
566                 visit(l)
567             }
568         },
569         _ => (),
570     };
571
572     match rvalue {
573         Use(op) | Repeat(op, _) | Cast(_, op, _) | UnaryOp(_, op) => visit_op(op),
574         Aggregate(_, ops) => ops.iter().for_each(visit_op),
575         BinaryOp(_, lhs, rhs) | CheckedBinaryOp(_, lhs, rhs) => {
576             visit_op(lhs);
577             visit_op(rhs);
578         },
579         _ => (),
580     }
581 }
582
583 /// Result of `PossibleBorrowerVisitor`.
584 struct PossibleBorrower<'a, 'tcx> {
585     /// Mapping `Local -> its possible borrowers`
586     map: FxHashMap<mir::Local, HybridBitSet<mir::Local>>,
587     maybe_live: DataflowResultsCursor<'a, 'tcx, MaybeStorageLive<'a, 'tcx>>,
588     // Caches to avoid allocation of `BitSet` on every query
589     bitset: (BitSet<mir::Local>, BitSet<mir::Local>),
590 }
591
592 impl PossibleBorrower<'_, '_> {
593     /// Returns true if the set of borrowers of `borrowed` living at `at` matches with `borrowers`.
594     fn only_borrowers(&mut self, borrowers: &[mir::Local], borrowed: mir::Local, at: mir::Location) -> bool {
595         self.maybe_live.seek(at);
596
597         self.bitset.0.clear();
598         let maybe_live = &mut self.maybe_live;
599         if let Some(bitset) = self.map.get(&borrowed) {
600             for b in bitset.iter().filter(move |b| maybe_live.contains(*b)) {
601                 self.bitset.0.insert(b);
602             }
603         } else {
604             return false;
605         }
606
607         self.bitset.1.clear();
608         for b in borrowers {
609             self.bitset.1.insert(*b);
610         }
611
612         self.bitset.0 == self.bitset.1
613     }
614 }