1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::higher;
3 use clippy_utils::SpanlessEq;
4 use if_chain::if_chain;
5 use rustc_ast::ast::LitKind;
6 use rustc_errors::Applicability;
7 use rustc_hir::{lang_items::LangItem, BinOpKind, Expr, ExprKind, QPath, StmtKind};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 declare_clippy_lint! {
13 /// Checks for implicit saturating subtraction.
15 /// ### Why is this bad?
16 /// Simplicity and readability. Instead we can easily use an builtin function.
20 /// let end: u32 = 10;
21 /// let start: u32 = 5;
23 /// let mut i: u32 = end - start;
31 /// i = i.saturating_sub(1);
33 #[clippy::version = "1.44.0"]
34 pub IMPLICIT_SATURATING_SUB,
36 "Perform saturating subtraction instead of implicitly checking lower bound of data type"
39 declare_lint_pass!(ImplicitSaturatingSub => [IMPLICIT_SATURATING_SUB]);
41 impl<'tcx> LateLintPass<'tcx> for ImplicitSaturatingSub {
42 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
43 if expr.span.from_expansion() {
47 if let Some(higher::If { cond, then, r#else: None }) = higher::If::hir(expr);
49 // Check if the conditional expression is a binary operation
50 if let ExprKind::Binary(ref cond_op, cond_left, cond_right) = cond.kind;
52 // Ensure that the binary operator is >, != and <
53 if BinOpKind::Ne == cond_op.node || BinOpKind::Gt == cond_op.node || BinOpKind::Lt == cond_op.node;
55 // Check if the true condition block has only one statement
56 if let ExprKind::Block(block, _) = then.kind;
57 if block.stmts.len() == 1 && block.expr.is_none();
59 // Check if assign operation is done
60 if let StmtKind::Semi(e) = block.stmts[0].kind;
61 if let Some(target) = subtracts_one(cx, e);
63 // Extracting out the variable name
64 if let ExprKind::Path(QPath::Resolved(_, ares_path)) = target.kind;
67 // Handle symmetric conditions in the if statement
68 let (cond_var, cond_num_val) = if SpanlessEq::new(cx).eq_expr(cond_left, target) {
69 if BinOpKind::Gt == cond_op.node || BinOpKind::Ne == cond_op.node {
70 (cond_left, cond_right)
74 } else if SpanlessEq::new(cx).eq_expr(cond_right, target) {
75 if BinOpKind::Lt == cond_op.node || BinOpKind::Ne == cond_op.node {
76 (cond_right, cond_left)
84 // Check if the variable in the condition statement is an integer
85 if !cx.typeck_results().expr_ty(cond_var).is_integral() {
89 // Get the variable name
90 let var_name = ares_path.segments[0].ident.name.as_str();
91 const INT_TYPES: [LangItem; 5] = [
99 match cond_num_val.kind {
100 ExprKind::Lit(ref cond_lit) => {
101 // Check if the constant is zero
102 if let LitKind::Int(0, _) = cond_lit.node {
103 if cx.typeck_results().expr_ty(cond_left).is_signed() {
105 print_lint_and_sugg(cx, &var_name, expr);
109 ExprKind::Path(QPath::TypeRelative(_, name)) => {
111 if name.ident.as_str() == "MIN";
112 if let Some(const_id) = cx.typeck_results().type_dependent_def_id(cond_num_val.hir_id);
113 if let Some(impl_id) = cx.tcx.impl_of_method(const_id);
114 let mut int_ids = INT_TYPES.iter().filter_map(|&ty| cx.tcx.lang_items().require(ty).ok());
115 if int_ids.any(|int_id| int_id == impl_id);
117 print_lint_and_sugg(cx, &var_name, expr)
121 ExprKind::Call(func, []) => {
123 if let ExprKind::Path(QPath::TypeRelative(_, name)) = func.kind;
124 if name.ident.as_str() == "min_value";
125 if let Some(func_id) = cx.typeck_results().type_dependent_def_id(func.hir_id);
126 if let Some(impl_id) = cx.tcx.impl_of_method(func_id);
127 let mut int_ids = INT_TYPES.iter().filter_map(|&ty| cx.tcx.lang_items().require(ty).ok());
128 if int_ids.any(|int_id| int_id == impl_id);
130 print_lint_and_sugg(cx, &var_name, expr)
141 fn subtracts_one<'a>(cx: &LateContext<'_>, expr: &Expr<'a>) -> Option<&'a Expr<'a>> {
143 ExprKind::AssignOp(ref op1, target, value) => {
145 if BinOpKind::Sub == op1.node;
146 // Check if literal being subtracted is one
147 if let ExprKind::Lit(ref lit1) = value.kind;
148 if let LitKind::Int(1, _) = lit1.node;
156 ExprKind::Assign(target, value, _) => {
158 if let ExprKind::Binary(ref op1, left1, right1) = value.kind;
159 if BinOpKind::Sub == op1.node;
161 if SpanlessEq::new(cx).eq_expr(left1, target);
163 if let ExprKind::Lit(ref lit1) = right1.kind;
164 if let LitKind::Int(1, _) = lit1.node;
176 fn print_lint_and_sugg(cx: &LateContext<'_>, var_name: &str, expr: &Expr<'_>) {
179 IMPLICIT_SATURATING_SUB,
181 "implicitly performing saturating subtraction",
183 format!("{} = {}.saturating_sub({});", var_name, var_name, '1'),
184 Applicability::MachineApplicable,