]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/redundant_clone.rs
Rustup to rust-lang/rust#67806
[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::lint::{LateContext, LateLintPass};
8 use rustc::mir::{
9     self, traversal,
10     visit::{MutatingUseContext, PlaceContext, Visitor as _},
11 };
12 use rustc::ty::{self, fold::TypeVisitor, Ty};
13 use rustc_data_structures::{fx::FxHashMap, transitive_relation::TransitiveRelation};
14 use rustc_errors::Applicability;
15 use rustc_hir::intravisit::FnKind;
16 use rustc_hir::{def_id, Body, FnDecl, HirId};
17 use rustc_index::bit_set::{BitSet, HybridBitSet};
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.base == mir::PlaceBase::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 { base: mir::PlaceBase::Local(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 (
292             mir::Place {
293                 base: mir::PlaceBase::Local(local),
294                 ..
295             },
296             v,
297         )) = &stmt.kind
298         {
299             return if *local == to_local { Some(v) } else { None };
300         }
301
302         None
303     })?;
304
305     match (by_ref, &*rvalue) {
306         (true, mir::Rvalue::Ref(_, _, place)) | (false, mir::Rvalue::Use(mir::Operand::Copy(place))) => {
307             base_local_and_movability(cx, mir, place)
308         },
309         (false, mir::Rvalue::Ref(_, _, place)) => {
310             if let [mir::ProjectionElem::Deref] = place.as_ref().projection {
311                 base_local_and_movability(cx, mir, place)
312             } else {
313                 None
314             }
315         },
316         _ => None,
317     }
318 }
319
320 /// Extracts and returns the undermost base `Local` of given `place`. Returns `place` itself
321 /// if it is already a `Local`.
322 ///
323 /// Also reports whether given `place` cannot be moved out.
324 fn base_local_and_movability<'tcx>(
325     cx: &LateContext<'_, 'tcx>,
326     mir: &mir::Body<'tcx>,
327     place: &mir::Place<'tcx>,
328 ) -> Option<(mir::Local, CannotMoveOut)> {
329     use rustc::mir::PlaceRef;
330
331     // Dereference. You cannot move things out from a borrowed value.
332     let mut deref = false;
333     // Accessing a field of an ADT that has `Drop`. Moving the field out will cause E0509.
334     let mut field = false;
335
336     let PlaceRef {
337         base: place_base,
338         mut projection,
339     } = place.as_ref();
340     if let mir::PlaceBase::Local(local) = place_base {
341         while let [base @ .., elem] = projection {
342             projection = base;
343             deref |= matches!(elem, mir::ProjectionElem::Deref);
344             field |= matches!(elem, mir::ProjectionElem::Field(..))
345                 && has_drop(
346                     cx,
347                     mir::Place::ty_from(place_base, projection, &mir.local_decls, cx.tcx).ty,
348                 );
349         }
350
351         Some((*local, deref || field))
352     } else {
353         None
354     }
355 }
356
357 struct LocalUseVisitor {
358     local: mir::Local,
359     used_other_than_drop: bool,
360 }
361
362 impl<'tcx> mir::visit::Visitor<'tcx> for LocalUseVisitor {
363     fn visit_basic_block_data(&mut self, block: mir::BasicBlock, data: &mir::BasicBlockData<'tcx>) {
364         let statements = &data.statements;
365         for (statement_index, statement) in statements.iter().enumerate() {
366             self.visit_statement(statement, mir::Location { block, statement_index });
367
368             // Once flagged, skip remaining statements
369             if self.used_other_than_drop {
370                 return;
371             }
372         }
373
374         self.visit_terminator(
375             data.terminator(),
376             mir::Location {
377                 block,
378                 statement_index: statements.len(),
379             },
380         );
381     }
382
383     fn visit_local(&mut self, local: &mir::Local, ctx: PlaceContext, _: mir::Location) {
384         match ctx {
385             PlaceContext::MutatingUse(MutatingUseContext::Drop) | PlaceContext::NonUse(_) => return,
386             _ => {},
387         }
388
389         if *local == self.local {
390             self.used_other_than_drop = true;
391         }
392     }
393 }
394
395 /// Determines liveness of each local purely based on `StorageLive`/`Dead`.
396 #[derive(Copy, Clone)]
397 struct MaybeStorageLive<'a, 'tcx> {
398     body: &'a mir::Body<'tcx>,
399 }
400
401 impl<'a, 'tcx> MaybeStorageLive<'a, 'tcx> {
402     fn new(body: &'a mir::Body<'tcx>) -> Self {
403         MaybeStorageLive { body }
404     }
405 }
406
407 impl<'a, 'tcx> BitDenotation<'tcx> for MaybeStorageLive<'a, 'tcx> {
408     type Idx = mir::Local;
409     fn name() -> &'static str {
410         "maybe_storage_live"
411     }
412     fn bits_per_block(&self) -> usize {
413         self.body.local_decls.len()
414     }
415
416     fn start_block_effect(&self, on_entry: &mut BitSet<mir::Local>) {
417         for arg in self.body.args_iter() {
418             on_entry.insert(arg);
419         }
420     }
421
422     fn statement_effect(&self, trans: &mut GenKillSet<mir::Local>, loc: mir::Location) {
423         let stmt = &self.body[loc.block].statements[loc.statement_index];
424
425         match stmt.kind {
426             mir::StatementKind::StorageLive(l) => trans.gen(l),
427             mir::StatementKind::StorageDead(l) => trans.kill(l),
428             _ => (),
429         }
430     }
431
432     fn terminator_effect(&self, _trans: &mut GenKillSet<mir::Local>, _loc: mir::Location) {}
433
434     fn propagate_call_return(
435         &self,
436         _in_out: &mut BitSet<mir::Local>,
437         _call_bb: mir::BasicBlock,
438         _dest_bb: mir::BasicBlock,
439         _dest_place: &mir::Place<'tcx>,
440     ) {
441         // Nothing to do when a call returns successfully
442     }
443 }
444
445 impl<'a, 'tcx> BottomValue for MaybeStorageLive<'a, 'tcx> {
446     /// bottom = dead
447     const BOTTOM_VALUE: bool = false;
448 }
449
450 /// Collects the possible borrowers of each local.
451 /// For example, `b = &a; c = &a;` will make `b` and (transitively) `c`
452 /// possible borrowers of `a`.
453 struct PossibleBorrowerVisitor<'a, 'tcx> {
454     possible_borrower: TransitiveRelation<mir::Local>,
455     body: &'a mir::Body<'tcx>,
456     cx: &'a LateContext<'a, 'tcx>,
457 }
458
459 impl<'a, 'tcx> PossibleBorrowerVisitor<'a, 'tcx> {
460     fn new(cx: &'a LateContext<'a, 'tcx>, body: &'a mir::Body<'tcx>) -> Self {
461         Self {
462             possible_borrower: TransitiveRelation::default(),
463             cx,
464             body,
465         }
466     }
467
468     fn into_map(
469         self,
470         cx: &LateContext<'a, 'tcx>,
471         maybe_live: DataflowResults<'tcx, MaybeStorageLive<'a, 'tcx>>,
472     ) -> PossibleBorrower<'a, 'tcx> {
473         let mut map = FxHashMap::default();
474         for row in (1..self.body.local_decls.len()).map(mir::Local::from_usize) {
475             if is_copy(cx, self.body.local_decls[row].ty) {
476                 continue;
477             }
478
479             let borrowers = self.possible_borrower.reachable_from(&row);
480             if !borrowers.is_empty() {
481                 let mut bs = HybridBitSet::new_empty(self.body.local_decls.len());
482                 for &c in borrowers {
483                     if c != mir::Local::from_usize(0) {
484                         bs.insert(c);
485                     }
486                 }
487
488                 if !bs.is_empty() {
489                     map.insert(row, bs);
490                 }
491             }
492         }
493
494         let bs = BitSet::new_empty(self.body.local_decls.len());
495         PossibleBorrower {
496             map,
497             maybe_live: DataflowResultsCursor::new(maybe_live, self.body),
498             bitset: (bs.clone(), bs),
499         }
500     }
501 }
502
503 impl<'a, 'tcx> mir::visit::Visitor<'tcx> for PossibleBorrowerVisitor<'a, 'tcx> {
504     fn visit_assign(&mut self, place: &mir::Place<'tcx>, rvalue: &mir::Rvalue<'_>, _location: mir::Location) {
505         if let mir::PlaceBase::Local(lhs) = place.base {
506             match rvalue {
507                 mir::Rvalue::Ref(_, _, borrowed) => {
508                     if let mir::PlaceBase::Local(borrowed_local) = borrowed.base {
509                         self.possible_borrower.add(borrowed_local, lhs);
510                     }
511                 },
512                 other => {
513                     if !ContainsRegion.visit_ty(place.ty(&self.body.local_decls, self.cx.tcx).ty) {
514                         return;
515                     }
516                     rvalue_locals(other, |rhs| {
517                         if lhs != rhs {
518                             self.possible_borrower.add(rhs, lhs);
519                         }
520                     });
521                 },
522             }
523         }
524     }
525
526     fn visit_terminator(&mut self, terminator: &mir::Terminator<'_>, _loc: mir::Location) {
527         if let mir::TerminatorKind::Call {
528             args,
529             destination:
530                 Some((
531                     mir::Place {
532                         base: mir::PlaceBase::Local(dest),
533                         ..
534                     },
535                     _,
536                 )),
537             ..
538         } = &terminator.kind
539         {
540             // If the call returns something with lifetimes,
541             // let's conservatively assume the returned value contains lifetime of all the arguments.
542             // For example, given `let y: Foo<'a> = foo(x)`, `y` is considered to be a possible borrower of `x`.
543             if !ContainsRegion.visit_ty(&self.body.local_decls[*dest].ty) {
544                 return;
545             }
546
547             for op in args {
548                 match op {
549                     mir::Operand::Copy(p) | mir::Operand::Move(p) => {
550                         if let mir::PlaceBase::Local(arg) = p.base {
551                             self.possible_borrower.add(arg, *dest);
552                         }
553                     },
554                     _ => (),
555                 }
556             }
557         }
558     }
559 }
560
561 struct ContainsRegion;
562
563 impl TypeVisitor<'_> for ContainsRegion {
564     fn visit_region(&mut self, _: ty::Region<'_>) -> bool {
565         true
566     }
567 }
568
569 fn rvalue_locals(rvalue: &mir::Rvalue<'_>, mut visit: impl FnMut(mir::Local)) {
570     use rustc::mir::Rvalue::*;
571
572     let mut visit_op = |op: &mir::Operand<'_>| match op {
573         mir::Operand::Copy(p) | mir::Operand::Move(p) => {
574             if let mir::PlaceBase::Local(l) = p.base {
575                 visit(l)
576             }
577         },
578         _ => (),
579     };
580
581     match rvalue {
582         Use(op) | Repeat(op, _) | Cast(_, op, _) | UnaryOp(_, op) => visit_op(op),
583         Aggregate(_, ops) => ops.iter().for_each(visit_op),
584         BinaryOp(_, lhs, rhs) | CheckedBinaryOp(_, lhs, rhs) => {
585             visit_op(lhs);
586             visit_op(rhs);
587         },
588         _ => (),
589     }
590 }
591
592 /// Result of `PossibleBorrowerVisitor`.
593 struct PossibleBorrower<'a, 'tcx> {
594     /// Mapping `Local -> its possible borrowers`
595     map: FxHashMap<mir::Local, HybridBitSet<mir::Local>>,
596     maybe_live: DataflowResultsCursor<'a, 'tcx, MaybeStorageLive<'a, 'tcx>>,
597     // Caches to avoid allocation of `BitSet` on every query
598     bitset: (BitSet<mir::Local>, BitSet<mir::Local>),
599 }
600
601 impl PossibleBorrower<'_, '_> {
602     /// Returns true if the set of borrowers of `borrowed` living at `at` matches with `borrowers`.
603     fn only_borrowers(&mut self, borrowers: &[mir::Local], borrowed: mir::Local, at: mir::Location) -> bool {
604         self.maybe_live.seek(at);
605
606         self.bitset.0.clear();
607         let maybe_live = &mut self.maybe_live;
608         if let Some(bitset) = self.map.get(&borrowed) {
609             for b in bitset.iter().filter(move |b| maybe_live.contains(*b)) {
610                 self.bitset.0.insert(b);
611             }
612         } else {
613             return false;
614         }
615
616         self.bitset.1.clear();
617         for b in borrowers {
618             self.bitset.1.insert(*b);
619         }
620
621         self.bitset.0 == self.bitset.1
622     }
623 }