Skip to content

Commit

Permalink
Fixed branches_sharing_code FP with block expressions in else
Browse files Browse the repository at this point in the history
And added `branches_sharing_code` PF note to lint doc for `rust-clippy#7452`
  • Loading branch information
xFrednet committed Jul 14, 2021
1 parent 8131445 commit bd2e7ef
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
10 changes: 6 additions & 4 deletions clippy_lints/src/copies.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,10 @@ declare_clippy_lint! {
///
/// **Why is this bad?** Duplicate code is less maintainable.
///
/// **Known problems:** Hopefully none.
/// **Known problems:**
/// * The lint doesn't check if the moved expressions modify values that are beeing used in
/// the if condition. The suggestion can in that case modify the behavior of the program.
/// See [rust-clippy#7452](https://github.com/rust-lang/rust-clippy/issues/7452)
///
/// **Example:**
/// ```ignore
Expand Down Expand Up @@ -225,7 +228,7 @@ fn lint_same_then_else<'tcx>(
blocks,
expr,
);
} else if end_eq != 0 || (has_expr && expr_eq) {
} else if (end_eq != 0 && !has_expr) || (has_expr && expr_eq) {
let block = blocks[blocks.len() - 1];
let (start_stmts, block_stmts) = block.stmts.split_at(start_eq);
let (block_stmts, end_stmts) = block_stmts.split_at(block_stmts.len() - end_eq);
Expand Down Expand Up @@ -358,8 +361,7 @@ fn scan_block_for_eq(cx: &LateContext<'tcx>, blocks: &[&Block<'tcx>]) -> Option<
expr_eq &= block_expr_eq;
}

let has_expr = blocks[0].expr.is_some();
if has_expr && !expr_eq {
if !expr_eq {
end_eq = 0;
}

Expand Down
28 changes: 28 additions & 0 deletions tests/ui/branches_sharing_code/false_positives.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#![allow(dead_code)]
#![deny(clippy::if_same_then_else, clippy::branches_sharing_code)]

// ##################################
// # Issue clippy#7369
// ##################################
#[derive(Debug)]
pub struct FooBar {
foo: Vec<u32>,
}

impl FooBar {
pub fn bar(&mut self) {
if true {
self.foo.pop();
} else {
self.baz();

self.foo.pop();

self.baz()
}
}

fn baz(&mut self) {}
}

fn main() {}

0 comments on commit bd2e7ef

Please sign in to comment.