From 301ef6bb2a3883da9b1340b243f3a934ec3c6fb8 Mon Sep 17 00:00:00 2001 From: Shotaro Yamada Date: Tue, 17 Sep 2019 00:50:15 +0900 Subject: Fix false-positive of redundant_clone and move to clippy::perf --- clippy_lints/src/lib.rs | 3 +- clippy_lints/src/redundant_clone.rs | 372 +++++++++++++++++++++++++++++------- 2 files changed, 303 insertions(+), 72 deletions(-) (limited to 'clippy_lints') diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index 10a14f3b906..3e31779426a 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -864,6 +864,7 @@ pub fn register_plugins(reg: &mut rustc_driver::plugin::Registry<'_>, conf: &Con ranges::RANGE_MINUS_ONE, ranges::RANGE_PLUS_ONE, ranges::RANGE_ZIP_WITH_LEN, + redundant_clone::REDUNDANT_CLONE, redundant_field_names::REDUNDANT_FIELD_NAMES, redundant_pattern_matching::REDUNDANT_PATTERN_MATCHING, redundant_static_lifetimes::REDUNDANT_STATIC_LIFETIMES, @@ -1169,6 +1170,7 @@ pub fn register_plugins(reg: &mut rustc_driver::plugin::Registry<'_>, conf: &Con methods::SINGLE_CHAR_PATTERN, misc::CMP_OWNED, mutex_atomic::MUTEX_ATOMIC, + redundant_clone::REDUNDANT_CLONE, slow_vector_initialization::SLOW_VECTOR_INITIALIZATION, trivially_copy_pass_by_ref::TRIVIALLY_COPY_PASS_BY_REF, types::BOX_VEC, @@ -1188,7 +1190,6 @@ pub fn register_plugins(reg: &mut rustc_driver::plugin::Registry<'_>, conf: &Con mutex_atomic::MUTEX_INTEGER, needless_borrow::NEEDLESS_BORROW, path_buf_push_overwrite::PATH_BUF_PUSH_OVERWRITE, - redundant_clone::REDUNDANT_CLONE, ]); } diff --git a/clippy_lints/src/redundant_clone.rs b/clippy_lints/src/redundant_clone.rs index 09a55d26424..ad8ed568656 100644 --- a/clippy_lints/src/redundant_clone.rs +++ b/clippy_lints/src/redundant_clone.rs @@ -9,12 +9,19 @@ use rustc::hir::{def_id, Body, FnDecl, HirId}; use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass}; use rustc::mir::{ self, traversal, - visit::{MutatingUseContext, PlaceContext, Visitor}, - TerminatorKind, + visit::{MutatingUseContext, PlaceContext, Visitor as _}, }; -use rustc::ty::{self, Ty}; +use rustc::ty::{self, fold::TypeVisitor, Ty}; use rustc::{declare_lint_pass, declare_tool_lint}; +use rustc_data_structures::{ + bit_set::{BitSet, HybridBitSet}, + fx::FxHashMap, + transitive_relation::TransitiveRelation, +}; use rustc_errors::Applicability; +use rustc_mir::dataflow::{ + do_dataflow, BitDenotation, BottomValue, DataflowResults, DataflowResultsCursor, DebugFormatted, GenKillSet, +}; use std::convert::TryFrom; use syntax::source_map::{BytePos, Span}; @@ -36,17 +43,7 @@ declare_clippy_lint! { /// /// **Known problems:** /// - /// * Suggestions made by this lint could require NLL to be enabled. - /// * False-positive if there is a borrow preventing the value from moving out. - /// - /// ```rust - /// # fn foo(x: String) {} - /// let x = String::new(); - /// - /// let y = &x; - /// - /// foo(x.clone()); // This lint suggests to remove this `clone()` - /// ``` + /// False-negatives: analysis performed by this lint is conservative and limited. /// /// **Example:** /// ```rust @@ -68,7 +65,7 @@ declare_clippy_lint! { /// Path::new("/a/b").join("c").to_path_buf(); /// ``` pub REDUNDANT_CLONE, - nursery, + perf, "`clone()` of an owned value that is going to be dropped immediately" } @@ -88,6 +85,22 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RedundantClone { let def_id = cx.tcx.hir().body_owner_def_id(body.id()); let mir = cx.tcx.optimized_mir(def_id); + let dead_unwinds = BitSet::new_empty(mir.basic_blocks().len()); + let maybe_storage_live_result = do_dataflow( + cx.tcx, + mir, + def_id, + &[], + &dead_unwinds, + MaybeStorageLive::new(mir), + |bd, p| DebugFormatted::new(&bd.body.local_decls[p]), + ); + let mut possible_borrower = { + let mut vis = PossibleBorrowerVisitor::new(cx, mir); + vis.visit_body(mir); + vis.into_map(cx, maybe_storage_live_result) + }; + for (bb, bbdata) in mir.basic_blocks().iter_enumerated() { let terminator = bbdata.terminator(); @@ -117,15 +130,16 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RedundantClone { // _1 in MIR `{ _2 = &_1; clone(move _2); }` or `{ _2 = _1; to_path_buf(_2); } (from_deref) // In case of `from_deref`, `arg` is already a reference since it is `deref`ed in the previous // block. - let (cloned, cannot_move_out) = unwrap_or_continue!(find_stmt_assigns_to( - cx, - mir, - arg, - from_borrow, - bbdata.statements.iter() - )); - - if from_borrow && cannot_move_out { + let (cloned, cannot_move_out) = unwrap_or_continue!(find_stmt_assigns_to(cx, mir, arg, from_borrow, bb)); + + let loc = mir::Location { + block: bb, + statement_index: bbdata.statements.len(), + }; + + if from_borrow + && (cannot_move_out || possible_borrower.only_borrowers(&[arg][..], cloned, loc) != Some(true)) + { continue; } @@ -151,14 +165,13 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RedundantClone { } }; - let (local, cannot_move_out) = unwrap_or_continue!(find_stmt_assigns_to( - cx, - mir, - pred_arg, - true, - mir[ps[0]].statements.iter() - )); - if cannot_move_out { + let (local, cannot_move_out) = + unwrap_or_continue!(find_stmt_assigns_to(cx, mir, pred_arg, true, ps[0])); + let loc = mir::Location { + block: bb, + statement_index: mir.basic_blocks()[bb].statements.len(), + }; + if cannot_move_out || possible_borrower.only_borrowers(&[arg, cloned][..], local, loc) != Some(true) { continue; } local @@ -224,7 +237,7 @@ fn is_call_with_ref_arg<'tcx>( kind: &'tcx mir::TerminatorKind<'tcx>, ) -> Option<(def_id::DefId, mir::Local, Ty<'tcx>, Option<&'tcx mir::Place<'tcx>>)> { if_chain! { - if let TerminatorKind::Call { func, args, destination, .. } = kind; + if let mir::TerminatorKind::Call { func, args, destination, .. } = kind; if args.len() == 1; if let mir::Operand::Move(mir::Place { base: mir::PlaceBase::Local(local), .. }) = &args[0]; if let ty::FnDef(def_id, _) = func.ty(&*mir, cx.tcx).kind; @@ -241,42 +254,35 @@ fn is_call_with_ref_arg<'tcx>( type CannotMoveOut = bool; /// Finds the first `to = (&)from`, and returns -/// ``Some((from, [`true` if `from` cannot be moved out]))``. -fn find_stmt_assigns_to<'a, 'tcx: 'a>( +/// ``Some((from, whether `from` cannot be moved out))``. +fn find_stmt_assigns_to<'tcx>( cx: &LateContext<'_, 'tcx>, mir: &mir::Body<'tcx>, - to: mir::Local, + to_local: mir::Local, by_ref: bool, - stmts: impl DoubleEndedIterator>, + bb: mir::BasicBlock, ) -> Option<(mir::Local, CannotMoveOut)> { - stmts - .rev() - .find_map(|stmt| { - if let mir::StatementKind::Assign(box ( - mir::Place { - base: mir::PlaceBase::Local(local), - .. - }, - v, - )) = &stmt.kind - { - if *local == to { - return Some(v); - } - } + let rvalue = mir.basic_blocks()[bb].statements.iter().rev().find_map(|stmt| { + if let mir::StatementKind::Assign(box ( + mir::Place { + base: mir::PlaceBase::Local(local), + .. + }, + v, + )) = &stmt.kind + { + return if *local == to_local { Some(v) } else { None }; + } - None - }) - .and_then(|v| { - if by_ref { - if let mir::Rvalue::Ref(_, _, ref place) = v { - return base_local_and_movability(cx, mir, place); - } - } else if let mir::Rvalue::Use(mir::Operand::Copy(ref place)) = v { - return base_local_and_movability(cx, mir, place); - } - None - }) + None + })?; + + match (by_ref, &*rvalue) { + (true, mir::Rvalue::Ref(_, _, place)) | (false, mir::Rvalue::Use(mir::Operand::Copy(place))) => { + base_local_and_movability(cx, mir, place) + }, + _ => None, + } } /// Extracts and returns the undermost base `Local` of given `place`. Returns `place` itself @@ -288,8 +294,6 @@ fn base_local_and_movability<'tcx>( mir: &mir::Body<'tcx>, place: &mir::Place<'tcx>, ) -> Option<(mir::Local, CannotMoveOut)> { - use rustc::mir::Place; - use rustc::mir::PlaceBase; use rustc::mir::PlaceRef; // Dereference. You cannot move things out from a borrowed value. @@ -301,13 +305,15 @@ fn base_local_and_movability<'tcx>( base: place_base, mut projection, } = place.as_ref(); - if let PlaceBase::Local(local) = place_base { + if let mir::PlaceBase::Local(local) = place_base { while let [base @ .., elem] = projection { projection = base; - deref = matches!(elem, mir::ProjectionElem::Deref); - field = !field - && matches!(elem, mir::ProjectionElem::Field(..)) - && has_drop(cx, Place::ty_from(place_base, projection, &mir.local_decls, cx.tcx).ty); + deref |= matches!(elem, mir::ProjectionElem::Deref); + field |= matches!(elem, mir::ProjectionElem::Field(..)) + && has_drop( + cx, + mir::Place::ty_from(place_base, projection, &mir.local_decls, cx.tcx).ty, + ); } Some((*local, deref || field)) @@ -353,3 +359,227 @@ impl<'tcx> mir::visit::Visitor<'tcx> for LocalUseVisitor { } } } + +#[derive(Copy, Clone)] +struct MaybeStorageLive<'a, 'tcx> { + body: &'a mir::Body<'tcx>, +} + +impl<'a, 'tcx> MaybeStorageLive<'a, 'tcx> { + fn new(body: &'a mir::Body<'tcx>) -> Self { + MaybeStorageLive { body } + } +} + +impl<'a, 'tcx> BitDenotation<'tcx> for MaybeStorageLive<'a, 'tcx> { + type Idx = mir::Local; + fn name() -> &'static str { + "maybe_storage_live" + } + fn bits_per_block(&self) -> usize { + self.body.local_decls.len() + } + + fn start_block_effect(&self, on_entry: &mut BitSet) { + for arg in self.body.args_iter() { + on_entry.insert(arg); + } + } + + fn statement_effect(&self, trans: &mut GenKillSet, loc: mir::Location) { + let stmt = &self.body[loc.block].statements[loc.statement_index]; + + match stmt.kind { + mir::StatementKind::StorageLive(l) => trans.gen(l), + mir::StatementKind::StorageDead(l) => trans.kill(l), + _ => (), + } + } + + fn terminator_effect(&self, _trans: &mut GenKillSet, _loc: mir::Location) {} + + fn propagate_call_return( + &self, + _in_out: &mut BitSet, + _call_bb: mir::BasicBlock, + _dest_bb: mir::BasicBlock, + _dest_place: &mir::Place<'tcx>, + ) { + // Nothing to do when a call returns successfully + } +} + +impl<'a, 'tcx> BottomValue for MaybeStorageLive<'a, 'tcx> { + /// bottom = dead + const BOTTOM_VALUE: bool = false; +} + +struct PossibleBorrowerVisitor<'a, 'tcx> { + possible_borrower: TransitiveRelation, + body: &'a mir::Body<'tcx>, + cx: &'a LateContext<'a, 'tcx>, +} + +impl<'a, 'tcx> PossibleBorrowerVisitor<'a, 'tcx> { + fn new(cx: &'a LateContext<'a, 'tcx>, body: &'a mir::Body<'tcx>) -> Self { + Self { + possible_borrower: TransitiveRelation::default(), + cx, + body, + } + } + + fn into_map( + self, + cx: &LateContext<'a, 'tcx>, + maybe_live: DataflowResults<'tcx, MaybeStorageLive<'a, 'tcx>>, + ) -> PossibleBorrower<'a, 'tcx> { + let mut map = FxHashMap::default(); + for row in (1..self.body.local_decls.len()).map(mir::Local::from_usize) { + if is_copy(cx, self.body.local_decls[row].ty) { + continue; + } + + let borrowers = self.possible_borrower.reachable_from(&row); + if !borrowers.is_empty() { + let mut bs = HybridBitSet::new_empty(self.body.local_decls.len()); + for &c in borrowers { + if c != mir::Local::from_usize(0) { + bs.insert(c); + } + } + + if !bs.is_empty() { + map.insert(row, bs); + } + } + } + + let bs = BitSet::new_empty(self.body.local_decls.len()); + PossibleBorrower { + map, + maybe_live: DataflowResultsCursor::new(maybe_live, self.body), + bitset: (bs.clone(), bs), + } + } +} + +impl<'a, 'tcx> mir::visit::Visitor<'tcx> for PossibleBorrowerVisitor<'a, 'tcx> { + fn visit_assign(&mut self, place: &mir::Place<'tcx>, rvalue: &mir::Rvalue<'_>, _location: mir::Location) { + if let mir::PlaceBase::Local(lhs) = place.base { + match rvalue { + mir::Rvalue::Ref(_, _, borrowed) => { + if let mir::PlaceBase::Local(borrowed_local) = borrowed.base { + self.possible_borrower.add(borrowed_local, lhs); + } + }, + other => { + if !ContainsRegion.visit_ty(place.ty(&self.body.local_decls, self.cx.tcx).ty) { + return; + } + rvalue_locals(other, |rhs| { + if lhs != rhs { + self.possible_borrower.add(rhs, lhs); + } + }); + }, + } + } + } + + fn visit_terminator(&mut self, terminator: &mir::Terminator<'_>, _loc: mir::Location) { + if let mir::TerminatorKind::Call { + args, + destination: + Some(( + mir::Place { + base: mir::PlaceBase::Local(dest), + .. + }, + _, + )), + .. + } = &terminator.kind + { + // If the call returns something with some lifetime, + // let's conservatively assume the returned value contains lifetime of all the arguments. + let mut cr = ContainsRegion; + if !cr.visit_ty(&self.body.local_decls[*dest].ty) { + return; + } + + for op in args { + match op { + mir::Operand::Copy(p) | mir::Operand::Move(p) => { + if let mir::PlaceBase::Local(arg) = p.base { + self.possible_borrower.add(arg, *dest); + } + }, + _ => (), + } + } + } + } +} + +struct ContainsRegion; + +impl TypeVisitor<'_> for ContainsRegion { + fn visit_region(&mut self, _: ty::Region<'_>) -> bool { + true + } +} + +fn rvalue_locals(rvalue: &mir::Rvalue<'_>, mut visit: impl FnMut(mir::Local)) { + use rustc::mir::Rvalue::*; + + let mut visit_op = |op: &mir::Operand<'_>| match op { + mir::Operand::Copy(p) | mir::Operand::Move(p) => { + if let mir::PlaceBase::Local(l) = p.base { + visit(l) + } + }, + _ => (), + }; + + match rvalue { + Use(op) | Repeat(op, _) | Cast(_, op, _) | UnaryOp(_, op) => visit_op(op), + Aggregate(_, ops) => ops.iter().for_each(visit_op), + BinaryOp(_, lhs, rhs) | CheckedBinaryOp(_, lhs, rhs) => { + visit_op(lhs); + visit_op(rhs); + }, + _ => (), + } +} + +struct PossibleBorrower<'a, 'tcx> { + map: FxHashMap>, + maybe_live: + DataflowResultsCursor<'a, 'tcx, MaybeStorageLive<'a, 'tcx>, DataflowResults<'tcx, MaybeStorageLive<'a, 'tcx>>>, + bitset: (BitSet, BitSet), +} + +impl PossibleBorrower<'_, '_> { + fn only_borrowers<'a>( + &mut self, + borrowers: impl IntoIterator, + borrowed: mir::Local, + at: mir::Location, + ) -> Option { + self.maybe_live.seek(at); + + self.bitset.0.clear(); + let maybe_live = &mut self.maybe_live; + for b in self.map.get(&borrowed)?.iter().filter(move |b| maybe_live.contains(*b)) { + self.bitset.0.insert(b); + } + + self.bitset.1.clear(); + for b in borrowers { + self.bitset.1.insert(*b); + } + + Some(self.bitset.0 == self.bitset.1) + } +} -- cgit 1.4.1-3-g733a5 From 667223c35d9be21e91a9ffbe626213767c066dda Mon Sep 17 00:00:00 2001 From: Shotaro Yamada Date: Tue, 10 Sep 2019 11:56:34 +0900 Subject: Add run-rustfix --- clippy_lints/src/redundant_clone.rs | 10 ++- tests/ui/redundant_clone.fixed | 132 ++++++++++++++++++++++++++++++++++ tests/ui/redundant_clone.rs | 56 ++++++++------- tests/ui/redundant_clone.stderr | 140 ++++++++++++++++++------------------ 4 files changed, 241 insertions(+), 97 deletions(-) create mode 100644 tests/ui/redundant_clone.fixed (limited to 'clippy_lints') diff --git a/clippy_lints/src/redundant_clone.rs b/clippy_lints/src/redundant_clone.rs index ad8ed568656..965f6bac62a 100644 --- a/clippy_lints/src/redundant_clone.rs +++ b/clippy_lints/src/redundant_clone.rs @@ -208,13 +208,21 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RedundantClone { let sugg_span = span.with_lo( span.lo() + BytePos(u32::try_from(dot).unwrap()) ); + let mut app = Applicability::MaybeIncorrect; + let mut call_snip = &snip[dot + 1..]; + if call_snip.ends_with("()") { + call_snip = call_snip[..call_snip.len()-2].trim(); + if call_snip.as_bytes().iter().all(|b| b.is_ascii_alphabetic() || *b == b'_') { + app = Applicability::MachineApplicable; + } + } span_lint_hir_and_then(cx, REDUNDANT_CLONE, node, sugg_span, "redundant clone", |db| { db.span_suggestion( sugg_span, "remove this", String::new(), - Applicability::MaybeIncorrect, + app, ); db.span_note( span.with_hi(span.lo() + BytePos(u32::try_from(dot).unwrap())), diff --git a/tests/ui/redundant_clone.fixed b/tests/ui/redundant_clone.fixed new file mode 100644 index 00000000000..614a9bf4d90 --- /dev/null +++ b/tests/ui/redundant_clone.fixed @@ -0,0 +1,132 @@ +// run-rustfix +// rustfix-only-machine-applicable +use std::ffi::OsString; +use std::path::Path; + +fn main() { + let _s = ["lorem", "ipsum"].join(" "); + + let s = String::from("foo"); + let _s = s; + + let s = String::from("foo"); + let _s = s; + + let s = String::from("foo"); + let _s = s; + + let _s = Path::new("/a/b/").join("c"); + + let _s = Path::new("/a/b/").join("c"); + + let _s = OsString::new(); + + let _s = OsString::new(); + + // Check that lint level works + #[allow(clippy::redundant_clone)] + let _s = String::new().to_string(); + + let tup = (String::from("foo"),); + let _t = tup.0; + + let tup_ref = &(String::from("foo"),); + let _s = tup_ref.0.clone(); // this `.clone()` cannot be removed + + { + let x = String::new(); + let y = &x; + + let _x = x.clone(); // ok; `x` is borrowed by `y` + + let _ = y.len(); + } + + let x = (String::new(),); + let _ = Some(String::new()).unwrap_or_else(|| x.0.clone()); // ok; closure borrows `x` + + with_branch(Alpha, true); + cannot_move_from_type_with_drop(); + borrower_propagation(); +} + +#[derive(Clone)] +struct Alpha; +fn with_branch(a: Alpha, b: bool) -> (Alpha, Alpha) { + if b { + (a.clone(), a) + } else { + (Alpha, a) + } +} + +struct TypeWithDrop { + x: String, +} + +impl Drop for TypeWithDrop { + fn drop(&mut self) {} +} + +fn cannot_move_from_type_with_drop() -> String { + let s = TypeWithDrop { x: String::new() }; + s.x.clone() // removing this `clone()` summons E0509 +} + +fn borrower_propagation() { + let s = String::new(); + let t = String::new(); + + { + fn b() -> bool { + unimplemented!() + } + let _u = if b() { &s } else { &t }; + + // ok; `s` and `t` are possibly borrowed + let _s = s.clone(); + let _t = t.clone(); + } + + { + let _u = || s.len(); + let _v = [&t; 32]; + let _s = s.clone(); // ok + let _t = t.clone(); // ok + } + + { + let _u = { + let u = Some(&s); + let _ = s.clone(); // ok + u + }; + let _s = s.clone(); // ok + } + + { + use std::convert::identity as id; + let _u = id(id(&s)); + let _s = s.clone(); // ok, `u` borrows `s` + } + + let _s = s; + let _t = t; + + #[derive(Clone)] + struct Foo { + x: usize, + } + + { + let f = Foo { x: 123 }; + let _x = Some(f.x); + let _f = f; + } + + { + let f = Foo { x: 123 }; + let _x = &f.x; + let _f = f.clone(); // ok + } +} diff --git a/tests/ui/redundant_clone.rs b/tests/ui/redundant_clone.rs index 4e38a5c924c..48687c82c2f 100644 --- a/tests/ui/redundant_clone.rs +++ b/tests/ui/redundant_clone.rs @@ -1,34 +1,34 @@ -#![warn(clippy::redundant_clone)] - +// run-rustfix +// rustfix-only-machine-applicable use std::ffi::OsString; use std::path::Path; fn main() { - let _ = ["lorem", "ipsum"].join(" ").to_string(); + let _s = ["lorem", "ipsum"].join(" ").to_string(); let s = String::from("foo"); - let _ = s.clone(); + let _s = s.clone(); let s = String::from("foo"); - let _ = s.to_string(); + let _s = s.to_string(); let s = String::from("foo"); - let _ = s.to_owned(); + let _s = s.to_owned(); - let _ = Path::new("/a/b/").join("c").to_owned(); + let _s = Path::new("/a/b/").join("c").to_owned(); - let _ = Path::new("/a/b/").join("c").to_path_buf(); + let _s = Path::new("/a/b/").join("c").to_path_buf(); - let _ = OsString::new().to_owned(); + let _s = OsString::new().to_owned(); - let _ = OsString::new().to_os_string(); + let _s = OsString::new().to_os_string(); // Check that lint level works #[allow(clippy::redundant_clone)] - let _ = String::new().to_string(); + let _s = String::new().to_string(); let tup = (String::from("foo"),); - let _ = tup.0.clone(); + let _t = tup.0.clone(); let tup_ref = &(String::from("foo"),); let _s = tup_ref.0.clone(); // this `.clone()` cannot be removed @@ -37,13 +37,17 @@ fn main() { let x = String::new(); let y = &x; - let _ = x.clone(); // ok; `x` is borrowed by `y` + let _x = x.clone(); // ok; `x` is borrowed by `y` let _ = y.len(); } let x = (String::new(),); let _ = Some(String::new()).unwrap_or_else(|| x.0.clone()); // ok; closure borrows `x` + + with_branch(Alpha, true); + cannot_move_from_type_with_drop(); + borrower_propagation(); } #[derive(Clone)] @@ -77,37 +81,37 @@ fn borrower_propagation() { fn b() -> bool { unimplemented!() } - let u = if b() { &s } else { &t }; + let _u = if b() { &s } else { &t }; // ok; `s` and `t` are possibly borrowed - let _ = s.clone(); - let _ = t.clone(); + let _s = s.clone(); + let _t = t.clone(); } { - let u = || s.len(); - let v = [&t; 32]; - let _ = s.clone(); // ok - let _ = t.clone(); // ok + let _u = || s.len(); + let _v = [&t; 32]; + let _s = s.clone(); // ok + let _t = t.clone(); // ok } { - let u = { + let _u = { let u = Some(&s); let _ = s.clone(); // ok u }; - let _ = s.clone(); // ok + let _s = s.clone(); // ok } { use std::convert::identity as id; - let u = id(id(&s)); - let _ = s.clone(); // ok, `u` borrows `s` + let _u = id(id(&s)); + let _s = s.clone(); // ok, `u` borrows `s` } - let _ = s.clone(); - let _ = t.clone(); + let _s = s.clone(); + let _t = t.clone(); #[derive(Clone)] struct Foo { diff --git a/tests/ui/redundant_clone.stderr b/tests/ui/redundant_clone.stderr index d1bc7e44fda..feafbd78b4e 100644 --- a/tests/ui/redundant_clone.stderr +++ b/tests/ui/redundant_clone.stderr @@ -1,156 +1,156 @@ error: redundant clone - --> $DIR/redundant_clone.rs:7:41 + --> $DIR/redundant_clone.rs:7:42 | -LL | let _ = ["lorem", "ipsum"].join(" ").to_string(); - | ^^^^^^^^^^^^ help: remove this +LL | let _s = ["lorem", "ipsum"].join(" ").to_string(); + | ^^^^^^^^^^^^ help: remove this | = note: `-D clippy::redundant-clone` implied by `-D warnings` note: this value is dropped without further use - --> $DIR/redundant_clone.rs:7:13 + --> $DIR/redundant_clone.rs:7:14 | -LL | let _ = ["lorem", "ipsum"].join(" ").to_string(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | let _s = ["lorem", "ipsum"].join(" ").to_string(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: redundant clone - --> $DIR/redundant_clone.rs:10:14 + --> $DIR/redundant_clone.rs:10:15 | -LL | let _ = s.clone(); - | ^^^^^^^^ help: remove this +LL | let _s = s.clone(); + | ^^^^^^^^ help: remove this | note: this value is dropped without further use - --> $DIR/redundant_clone.rs:10:13 + --> $DIR/redundant_clone.rs:10:14 | -LL | let _ = s.clone(); - | ^ +LL | let _s = s.clone(); + | ^ error: redundant clone - --> $DIR/redundant_clone.rs:13:14 + --> $DIR/redundant_clone.rs:13:15 | -LL | let _ = s.to_string(); - | ^^^^^^^^^^^^ help: remove this +LL | let _s = s.to_string(); + | ^^^^^^^^^^^^ help: remove this | note: this value is dropped without further use - --> $DIR/redundant_clone.rs:13:13 + --> $DIR/redundant_clone.rs:13:14 | -LL | let _ = s.to_string(); - | ^ +LL | let _s = s.to_string(); + | ^ error: redundant clone - --> $DIR/redundant_clone.rs:16:14 + --> $DIR/redundant_clone.rs:16:15 | -LL | let _ = s.to_owned(); - | ^^^^^^^^^^^ help: remove this +LL | let _s = s.to_owned(); + | ^^^^^^^^^^^ help: remove this | note: this value is dropped without further use - --> $DIR/redundant_clone.rs:16:13 + --> $DIR/redundant_clone.rs:16:14 | -LL | let _ = s.to_owned(); - | ^ +LL | let _s = s.to_owned(); + | ^ error: redundant clone - --> $DIR/redundant_clone.rs:18:41 + --> $DIR/redundant_clone.rs:18:42 | -LL | let _ = Path::new("/a/b/").join("c").to_owned(); - | ^^^^^^^^^^^ help: remove this +LL | let _s = Path::new("/a/b/").join("c").to_owned(); + | ^^^^^^^^^^^ help: remove this | note: this value is dropped without further use - --> $DIR/redundant_clone.rs:18:13 + --> $DIR/redundant_clone.rs:18:14 | -LL | let _ = Path::new("/a/b/").join("c").to_owned(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | let _s = Path::new("/a/b/").join("c").to_owned(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: redundant clone - --> $DIR/redundant_clone.rs:20:41 + --> $DIR/redundant_clone.rs:20:42 | -LL | let _ = Path::new("/a/b/").join("c").to_path_buf(); - | ^^^^^^^^^^^^^^ help: remove this +LL | let _s = Path::new("/a/b/").join("c").to_path_buf(); + | ^^^^^^^^^^^^^^ help: remove this | note: this value is dropped without further use - --> $DIR/redundant_clone.rs:20:13 + --> $DIR/redundant_clone.rs:20:14 | -LL | let _ = Path::new("/a/b/").join("c").to_path_buf(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | let _s = Path::new("/a/b/").join("c").to_path_buf(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: redundant clone - --> $DIR/redundant_clone.rs:22:28 + --> $DIR/redundant_clone.rs:22:29 | -LL | let _ = OsString::new().to_owned(); - | ^^^^^^^^^^^ help: remove this +LL | let _s = OsString::new().to_owned(); + | ^^^^^^^^^^^ help: remove this | note: this value is dropped without further use - --> $DIR/redundant_clone.rs:22:13 + --> $DIR/redundant_clone.rs:22:14 | -LL | let _ = OsString::new().to_owned(); - | ^^^^^^^^^^^^^^^ +LL | let _s = OsString::new().to_owned(); + | ^^^^^^^^^^^^^^^ error: redundant clone - --> $DIR/redundant_clone.rs:24:28 + --> $DIR/redundant_clone.rs:24:29 | -LL | let _ = OsString::new().to_os_string(); - | ^^^^^^^^^^^^^^^ help: remove this +LL | let _s = OsString::new().to_os_string(); + | ^^^^^^^^^^^^^^^ help: remove this | note: this value is dropped without further use - --> $DIR/redundant_clone.rs:24:13 + --> $DIR/redundant_clone.rs:24:14 | -LL | let _ = OsString::new().to_os_string(); - | ^^^^^^^^^^^^^^^ +LL | let _s = OsString::new().to_os_string(); + | ^^^^^^^^^^^^^^^ error: redundant clone - --> $DIR/redundant_clone.rs:31:18 + --> $DIR/redundant_clone.rs:31:19 | -LL | let _ = tup.0.clone(); - | ^^^^^^^^ help: remove this +LL | let _t = tup.0.clone(); + | ^^^^^^^^ help: remove this | note: this value is dropped without further use - --> $DIR/redundant_clone.rs:31:13 + --> $DIR/redundant_clone.rs:31:14 | -LL | let _ = tup.0.clone(); - | ^^^^^ +LL | let _t = tup.0.clone(); + | ^^^^^ error: redundant clone - --> $DIR/redundant_clone.rs:53:22 + --> $DIR/redundant_clone.rs:57:22 | LL | (a.clone(), a.clone()) | ^^^^^^^^ help: remove this | note: this value is dropped without further use - --> $DIR/redundant_clone.rs:53:21 + --> $DIR/redundant_clone.rs:57:21 | LL | (a.clone(), a.clone()) | ^ error: redundant clone - --> $DIR/redundant_clone.rs:109:14 + --> $DIR/redundant_clone.rs:113:15 | -LL | let _ = s.clone(); - | ^^^^^^^^ help: remove this +LL | let _s = s.clone(); + | ^^^^^^^^ help: remove this | note: this value is dropped without further use - --> $DIR/redundant_clone.rs:109:13 + --> $DIR/redundant_clone.rs:113:14 | -LL | let _ = s.clone(); - | ^ +LL | let _s = s.clone(); + | ^ error: redundant clone - --> $DIR/redundant_clone.rs:110:14 + --> $DIR/redundant_clone.rs:114:15 | -LL | let _ = t.clone(); - | ^^^^^^^^ help: remove this +LL | let _t = t.clone(); + | ^^^^^^^^ help: remove this | note: this value is dropped without further use - --> $DIR/redundant_clone.rs:110:13 + --> $DIR/redundant_clone.rs:114:14 | -LL | let _ = t.clone(); - | ^ +LL | let _t = t.clone(); + | ^ error: redundant clone - --> $DIR/redundant_clone.rs:120:19 + --> $DIR/redundant_clone.rs:124:19 | LL | let _f = f.clone(); | ^^^^^^^^ help: remove this | note: this value is dropped without further use - --> $DIR/redundant_clone.rs:120:18 + --> $DIR/redundant_clone.rs:124:18 | LL | let _f = f.clone(); | ^ -- cgit 1.4.1-3-g733a5 From a3f403aa5020e8890e23e054ad08624955180720 Mon Sep 17 00:00:00 2001 From: Shotaro Yamada Date: Wed, 18 Sep 2019 14:56:30 +0900 Subject: Apply suggestion Co-Authored-By: ecstatic-morse --- clippy_lints/src/redundant_clone.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'clippy_lints') diff --git a/clippy_lints/src/redundant_clone.rs b/clippy_lints/src/redundant_clone.rs index 965f6bac62a..a8589e6658a 100644 --- a/clippy_lints/src/redundant_clone.rs +++ b/clippy_lints/src/redundant_clone.rs @@ -563,8 +563,7 @@ fn rvalue_locals(rvalue: &mir::Rvalue<'_>, mut visit: impl FnMut(mir::Local)) { struct PossibleBorrower<'a, 'tcx> { map: FxHashMap>, - maybe_live: - DataflowResultsCursor<'a, 'tcx, MaybeStorageLive<'a, 'tcx>, DataflowResults<'tcx, MaybeStorageLive<'a, 'tcx>>>, + maybe_live: DataflowResultsCursor<'a, 'tcx, MaybeStorageLive<'a, 'tcx>>, bitset: (BitSet, BitSet), } -- cgit 1.4.1-3-g733a5 From 1cee3fe00e08ee1f34583df9a20e1e8c0068a139 Mon Sep 17 00:00:00 2001 From: Shotaro Yamada Date: Sat, 28 Sep 2019 20:29:35 +0900 Subject: Resolve reviews --- clippy_lints/src/booleans.rs | 2 +- clippy_lints/src/redundant_clone.rs | 24 +++++++++++------------- 2 files changed, 12 insertions(+), 14 deletions(-) (limited to 'clippy_lints') diff --git a/clippy_lints/src/booleans.rs b/clippy_lints/src/booleans.rs index 4309eaa7879..c5da0af6f4d 100644 --- a/clippy_lints/src/booleans.rs +++ b/clippy_lints/src/booleans.rs @@ -343,7 +343,7 @@ impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> { let stats = terminal_stats(&expr); let mut simplified = expr.simplify(); - for simple in Bool::Not(Box::new(expr.clone())).simplify() { + for simple in Bool::Not(Box::new(expr)).simplify() { match simple { Bool::Not(_) | Bool::True | Bool::False => {}, _ => simplified.push(Bool::Not(Box::new(simple.clone()))), diff --git a/clippy_lints/src/redundant_clone.rs b/clippy_lints/src/redundant_clone.rs index a8589e6658a..5a2baf2e8ba 100644 --- a/clippy_lints/src/redundant_clone.rs +++ b/clippy_lints/src/redundant_clone.rs @@ -137,9 +137,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RedundantClone { statement_index: bbdata.statements.len(), }; - if from_borrow - && (cannot_move_out || possible_borrower.only_borrowers(&[arg][..], cloned, loc) != Some(true)) - { + if from_borrow && (cannot_move_out || !possible_borrower.only_borrowers(&[arg], cloned, loc)) { continue; } @@ -171,7 +169,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RedundantClone { block: bb, statement_index: mir.basic_blocks()[bb].statements.len(), }; - if cannot_move_out || possible_borrower.only_borrowers(&[arg, cloned][..], local, loc) != Some(true) { + if cannot_move_out || !possible_borrower.only_borrowers(&[arg, cloned], local, loc) { continue; } local @@ -564,22 +562,22 @@ fn rvalue_locals(rvalue: &mir::Rvalue<'_>, mut visit: impl FnMut(mir::Local)) { struct PossibleBorrower<'a, 'tcx> { map: FxHashMap>, maybe_live: DataflowResultsCursor<'a, 'tcx, MaybeStorageLive<'a, 'tcx>>, + // Caches to avoid allocation of `BitSet` on every query bitset: (BitSet, BitSet), } impl PossibleBorrower<'_, '_> { - fn only_borrowers<'a>( - &mut self, - borrowers: impl IntoIterator, - borrowed: mir::Local, - at: mir::Location, - ) -> Option { + fn only_borrowers(&mut self, borrowers: &[mir::Local], borrowed: mir::Local, at: mir::Location) -> bool { self.maybe_live.seek(at); self.bitset.0.clear(); let maybe_live = &mut self.maybe_live; - for b in self.map.get(&borrowed)?.iter().filter(move |b| maybe_live.contains(*b)) { - self.bitset.0.insert(b); + if let Some(bitset) = self.map.get(&borrowed) { + for b in bitset.iter().filter(move |b| maybe_live.contains(*b)) { + self.bitset.0.insert(b); + } + } else { + return false; } self.bitset.1.clear(); @@ -587,6 +585,6 @@ impl PossibleBorrower<'_, '_> { self.bitset.1.insert(*b); } - Some(self.bitset.0 == self.bitset.1) + self.bitset.0 == self.bitset.1 } } -- cgit 1.4.1-3-g733a5 From 866729f5dbba7f5982cba0eb2e9f6208d187f9b6 Mon Sep 17 00:00:00 2001 From: Shotaro Yamada Date: Mon, 30 Sep 2019 16:16:09 +0900 Subject: Add comments --- clippy_lints/src/redundant_clone.rs | 55 +++++++++++++++++++++++++++---------- 1 file changed, 41 insertions(+), 14 deletions(-) (limited to 'clippy_lints') diff --git a/clippy_lints/src/redundant_clone.rs b/clippy_lints/src/redundant_clone.rs index 5a2baf2e8ba..c0f6f3ae76d 100644 --- a/clippy_lints/src/redundant_clone.rs +++ b/clippy_lints/src/redundant_clone.rs @@ -127,9 +127,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RedundantClone { continue; } - // _1 in MIR `{ _2 = &_1; clone(move _2); }` or `{ _2 = _1; to_path_buf(_2); } (from_deref) - // In case of `from_deref`, `arg` is already a reference since it is `deref`ed in the previous - // block. + // `{ cloned = &arg; clone(move cloned); }` or `{ cloned = &arg; to_path_buf(cloned); }` let (cloned, cannot_move_out) = unwrap_or_continue!(find_stmt_assigns_to(cx, mir, arg, from_borrow, bb)); let loc = mir::Location { @@ -137,18 +135,27 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RedundantClone { statement_index: bbdata.statements.len(), }; - if from_borrow && (cannot_move_out || !possible_borrower.only_borrowers(&[arg], cloned, loc)) { - continue; - } + // Cloned local + let local = if from_borrow { + // `res = clone(arg)` can be turned into `res = move arg;` + // if `arg` is the only borrow of `cloned` at this point. + + if cannot_move_out || !possible_borrower.only_borrowers(&[arg], cloned, loc) { + continue; + } + + cloned + } else { + // `arg` is a reference as it is `.deref()`ed in the previous block. + // Look into the predecessor block and find out the source of deref. - // _1 in MIR `{ _2 = &_1; _3 = deref(move _2); } -> { _4 = _3; to_path_buf(move _4); }` - let referent = if from_deref { let ps = mir.predecessors_for(bb); if ps.len() != 1 { continue; } let pred_terminator = mir[ps[0]].terminator(); + // receiver of the `deref()` call let pred_arg = if_chain! { if let Some((pred_fn_def_id, pred_arg, pred_arg_ty, Some(res))) = is_call_with_ref_arg(cx, mir, &pred_terminator.kind); @@ -169,14 +176,25 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RedundantClone { block: bb, statement_index: mir.basic_blocks()[bb].statements.len(), }; + + // This can be turned into `res = move local` if `arg` and `cloned` are not borrowed + // at the last statement: + // + // ``` + // pred_arg = &local; + // cloned = deref(pred_arg); + // arg = &cloned; + // StorageDead(pred_arg); + // res = to_path_buf(cloned); + // ``` if cannot_move_out || !possible_borrower.only_borrowers(&[arg, cloned], local, loc) { continue; } + local - } else { - cloned }; + // `local` cannot be moved out if it is used later let used_later = traversal::ReversePostorder::new(&mir, bb).skip(1).any(|(tbb, tdata)| { // Give up on loops if tdata.terminator().successors().any(|s| *s == bb) { @@ -184,7 +202,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RedundantClone { } let mut vis = LocalUseVisitor { - local: referent, + local, used_other_than_drop: false, }; vis.visit_basic_block_data(tbb, tdata); @@ -207,7 +225,9 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RedundantClone { span.lo() + BytePos(u32::try_from(dot).unwrap()) ); let mut app = Applicability::MaybeIncorrect; + let mut call_snip = &snip[dot + 1..]; + // Machine applicable when `call_snip` looks like `foobar()` if call_snip.ends_with("()") { call_snip = call_snip[..call_snip.len()-2].trim(); if call_snip.as_bytes().iter().all(|b| b.is_ascii_alphabetic() || *b == b'_') { @@ -366,6 +386,7 @@ impl<'tcx> mir::visit::Visitor<'tcx> for LocalUseVisitor { } } +/// Determines liveness of each local purely based on `StorageLive`/`Dead`. #[derive(Copy, Clone)] struct MaybeStorageLive<'a, 'tcx> { body: &'a mir::Body<'tcx>, @@ -420,6 +441,9 @@ impl<'a, 'tcx> BottomValue for MaybeStorageLive<'a, 'tcx> { const BOTTOM_VALUE: bool = false; } +/// Collects the possible borrowers of each local. +/// For example, `b = &a; c = &a;` will make `b` and (transitively) `c` +/// possible borrowers of `a`. struct PossibleBorrowerVisitor<'a, 'tcx> { possible_borrower: TransitiveRelation, body: &'a mir::Body<'tcx>, @@ -507,10 +531,10 @@ impl<'a, 'tcx> mir::visit::Visitor<'tcx> for PossibleBorrowerVisitor<'a, 'tcx> { .. } = &terminator.kind { - // If the call returns something with some lifetime, + // If the call returns something with lifetimes, // let's conservatively assume the returned value contains lifetime of all the arguments. - let mut cr = ContainsRegion; - if !cr.visit_ty(&self.body.local_decls[*dest].ty) { + // For example, given `let y: Foo<'a> = foo(x)`, `y` is considered to be a possible borrower of `x`. + if !ContainsRegion.visit_ty(&self.body.local_decls[*dest].ty) { return; } @@ -559,7 +583,9 @@ fn rvalue_locals(rvalue: &mir::Rvalue<'_>, mut visit: impl FnMut(mir::Local)) { } } +/// Result of `PossibleBorrowerVisitor`. struct PossibleBorrower<'a, 'tcx> { + /// Mapping `Local -> its possible borrowers` map: FxHashMap>, maybe_live: DataflowResultsCursor<'a, 'tcx, MaybeStorageLive<'a, 'tcx>>, // Caches to avoid allocation of `BitSet` on every query @@ -567,6 +593,7 @@ struct PossibleBorrower<'a, 'tcx> { } impl PossibleBorrower<'_, '_> { + /// Returns true if the set of borrowers of `borrowed` living at `at` matches with `borrowers`. fn only_borrowers(&mut self, borrowers: &[mir::Local], borrowed: mir::Local, at: mir::Location) -> bool { self.maybe_live.seek(at); -- cgit 1.4.1-3-g733a5 From 4cded6d9012bbfc77d13c7ef2a413402199a2a03 Mon Sep 17 00:00:00 2001 From: Shotaro Yamada Date: Wed, 2 Oct 2019 08:02:18 +0900 Subject: extern rustc_index --- clippy_lints/src/lib.rs | 2 ++ clippy_lints/src/redundant_clone.rs | 7 ++----- 2 files changed, 4 insertions(+), 5 deletions(-) (limited to 'clippy_lints') diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index 3e31779426a..490f47424b1 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -27,6 +27,8 @@ extern crate rustc_driver; #[allow(unused_extern_crates)] extern crate rustc_errors; #[allow(unused_extern_crates)] +extern crate rustc_index; +#[allow(unused_extern_crates)] extern crate rustc_mir; #[allow(unused_extern_crates)] extern crate rustc_target; diff --git a/clippy_lints/src/redundant_clone.rs b/clippy_lints/src/redundant_clone.rs index c0f6f3ae76d..478ca2e04ff 100644 --- a/clippy_lints/src/redundant_clone.rs +++ b/clippy_lints/src/redundant_clone.rs @@ -13,12 +13,9 @@ use rustc::mir::{ }; use rustc::ty::{self, fold::TypeVisitor, Ty}; use rustc::{declare_lint_pass, declare_tool_lint}; -use rustc_data_structures::{ - bit_set::{BitSet, HybridBitSet}, - fx::FxHashMap, - transitive_relation::TransitiveRelation, -}; +use rustc_data_structures::{fx::FxHashMap, transitive_relation::TransitiveRelation}; use rustc_errors::Applicability; +use rustc_index::bit_set::{BitSet, HybridBitSet}; use rustc_mir::dataflow::{ do_dataflow, BitDenotation, BottomValue, DataflowResults, DataflowResultsCursor, DebugFormatted, GenKillSet, }; -- cgit 1.4.1-3-g733a5