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