From 90e8edb19a9cc5f0648886afc0a39e65eb84ee3c Mon Sep 17 00:00:00 2001 From: pmk21 Date: Sat, 18 Apr 2020 00:30:33 +0530 Subject: [PATCH] Move expression logic to subtracts_one --- clippy_lints/src/implicit_saturating_sub.rs | 47 +++++++++++++++------ 1 file changed, 33 insertions(+), 14 deletions(-) diff --git a/clippy_lints/src/implicit_saturating_sub.rs b/clippy_lints/src/implicit_saturating_sub.rs index b23658e9347a..bf1de1de6413 100644 --- a/clippy_lints/src/implicit_saturating_sub.rs +++ b/clippy_lints/src/implicit_saturating_sub.rs @@ -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 { @@ -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<'_>) {