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