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