1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::{higher, is_integer_literal, peel_blocks_with_stmt, SpanlessEq};
3 use if_chain::if_chain;
4 use rustc_ast::ast::LitKind;
5 use rustc_errors::Applicability;
6 use rustc_hir::{BinOpKind, Expr, ExprKind, QPath};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 declare_clippy_lint! {
12 /// Checks for implicit saturating subtraction.
14 /// ### Why is this bad?
15 /// Simplicity and readability. Instead we can easily use an builtin function.
19 /// # let end: u32 = 10;
20 /// # let start: u32 = 5;
21 /// let mut i: u32 = end - start;
30 /// # let end: u32 = 10;
31 /// # let start: u32 = 5;
32 /// let mut i: u32 = end - start;
34 /// i = i.saturating_sub(1);
36 #[clippy::version = "1.44.0"]
37 pub IMPLICIT_SATURATING_SUB,
39 "Perform saturating subtraction instead of implicitly checking lower bound of data type"
42 declare_lint_pass!(ImplicitSaturatingSub => [IMPLICIT_SATURATING_SUB]);
44 impl<'tcx> LateLintPass<'tcx> for ImplicitSaturatingSub {
45 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
46 if expr.span.from_expansion() {
50 if let Some(higher::If { cond, then, r#else: None }) = higher::If::hir(expr);
52 // Check if the conditional expression is a binary operation
53 if let ExprKind::Binary(ref cond_op, cond_left, cond_right) = cond.kind;
55 // Ensure that the binary operator is >, !=, or <
56 if BinOpKind::Ne == cond_op.node || BinOpKind::Gt == cond_op.node || BinOpKind::Lt == cond_op.node;
58 // Check if assign operation is done
59 if let Some(target) = subtracts_one(cx, then);
61 // Extracting out the variable name
62 if let ExprKind::Path(QPath::Resolved(_, ares_path)) = target.kind;
65 // Handle symmetric conditions in the if statement
66 let (cond_var, cond_num_val) = if SpanlessEq::new(cx).eq_expr(cond_left, target) {
67 if BinOpKind::Gt == cond_op.node || BinOpKind::Ne == cond_op.node {
68 (cond_left, cond_right)
72 } else if SpanlessEq::new(cx).eq_expr(cond_right, target) {
73 if BinOpKind::Lt == cond_op.node || BinOpKind::Ne == cond_op.node {
74 (cond_right, cond_left)
82 // Check if the variable in the condition statement is an integer
83 if !cx.typeck_results().expr_ty(cond_var).is_integral() {
87 // Get the variable name
88 let var_name = ares_path.segments[0].ident.name.as_str();
89 match cond_num_val.kind {
90 ExprKind::Lit(ref cond_lit) => {
91 // Check if the constant is zero
92 if let LitKind::Int(0, _) = cond_lit.node {
93 if cx.typeck_results().expr_ty(cond_left).is_signed() {
95 print_lint_and_sugg(cx, var_name, expr);
99 ExprKind::Path(QPath::TypeRelative(_, name)) => {
101 if name.ident.as_str() == "MIN";
102 if let Some(const_id) = cx.typeck_results().type_dependent_def_id(cond_num_val.hir_id);
103 if let Some(impl_id) = cx.tcx.impl_of_method(const_id);
104 if let None = cx.tcx.impl_trait_ref(impl_id); // An inherent impl
105 if cx.tcx.type_of(impl_id).is_integral();
107 print_lint_and_sugg(cx, var_name, expr)
111 ExprKind::Call(func, []) => {
113 if let ExprKind::Path(QPath::TypeRelative(_, name)) = func.kind;
114 if name.ident.as_str() == "min_value";
115 if let Some(func_id) = cx.typeck_results().type_dependent_def_id(func.hir_id);
116 if let Some(impl_id) = cx.tcx.impl_of_method(func_id);
117 if let None = cx.tcx.impl_trait_ref(impl_id); // An inherent impl
118 if cx.tcx.type_of(impl_id).is_integral();
120 print_lint_and_sugg(cx, var_name, expr)
131 fn subtracts_one<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<&'a Expr<'a>> {
132 match peel_blocks_with_stmt(expr).kind {
133 ExprKind::AssignOp(ref op1, target, value) => {
134 // Check if literal being subtracted is one
135 (BinOpKind::Sub == op1.node && is_integer_literal(value, 1)).then_some(target)
137 ExprKind::Assign(target, value, _) => {
139 if let ExprKind::Binary(ref op1, left1, right1) = value.kind;
140 if BinOpKind::Sub == op1.node;
142 if SpanlessEq::new(cx).eq_expr(left1, target);
144 if is_integer_literal(right1, 1);
156 fn print_lint_and_sugg(cx: &LateContext<'_>, var_name: &str, expr: &Expr<'_>) {
159 IMPLICIT_SATURATING_SUB,
161 "implicitly performing saturating subtraction",
163 format!("{var_name} = {var_name}.saturating_sub({});", '1'),
164 Applicability::MachineApplicable,