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