Skip to content

Commit

Permalink
Move expression logic to subtracts_one
Browse files Browse the repository at this point in the history
  • Loading branch information
pmk21 committed Apr 17, 2020
1 parent 1b5002f commit 90e8edb
Showing 1 changed file with 33 additions and 14 deletions.
47 changes: 33 additions & 14 deletions clippy_lints/src/implicit_saturating_sub.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitSaturatingSub {

// Check if assign operation is done
if let StmtKind::Semi(ref e) = block.stmts[0].kind;
if subtracts_one(e);
if let ExprKind::AssignOp(_, ref target, _) = e.kind;
if let ExprKind::Path(ref assign_path) = target.kind;
if let (true, Some(target)) = subtracts_one(cx, e);

// Extracting out the variable name
if let ExprKind::Path(ref assign_path) = target.kind;
if let QPath::Resolved(_, ref ares_path) = assign_path;

then {
Expand Down Expand Up @@ -126,19 +125,39 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitSaturatingSub {
}
}

fn subtracts_one(expr: &Expr<'_>) -> bool {
if_chain! {
if let ExprKind::AssignOp(ref op1, _, ref value) = expr.kind;
if BinOpKind::Sub == op1.node;
fn subtracts_one<'a>(cx: &LateContext<'_, '_>, expr: &Expr<'a>) -> (bool, Option<&'a Expr<'a>>) {
match expr.kind {
ExprKind::AssignOp(ref op1, ref target, ref value) => {
if_chain! {
if BinOpKind::Sub == op1.node;
// Check if literal being subtracted is one
if let ExprKind::Lit(ref lit1) = value.kind;
if let LitKind::Int(1, _) = lit1.node;
then {
(true, Option::Some(target))
} else {
(false, None)
}
}
},
ExprKind::Assign(ref target, ref value, _) => {
if_chain! {
if let ExprKind::Binary(ref op1, ref left1, ref right1) = value.kind;
if BinOpKind::Sub == op1.node;

if SpanlessEq::new(cx).eq_expr(left1, target);

// Check if literal being subtracted is one
if let ExprKind::Lit(ref lit1) = value.kind;
if let LitKind::Int(1, _) = lit1.node;
then {
return true;
}
if let ExprKind::Lit(ref lit1) = right1.kind;
if let LitKind::Int(1, _) = lit1.node;
then {
(true, Some(target))
} else {
(false, None)
}
}
},
_ => (false, None),
}
false
}

fn print_lint_and_sugg(cx: &LateContext<'_, '_>, var_name: &str, expr: &Expr<'_>) {
Expand Down

0 comments on commit 90e8edb

Please sign in to comment.