]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/implicit_saturating_sub.rs
Auto merge of #9870 - koka831:unformat-unused-rounding, r=Jarcho
[rust.git] / clippy_lints / src / implicit_saturating_sub.rs
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};
9
10 declare_clippy_lint! {
11     /// ### What it does
12     /// Checks for implicit saturating subtraction.
13     ///
14     /// ### Why is this bad?
15     /// Simplicity and readability. Instead we can easily use an builtin function.
16     ///
17     /// ### Example
18     /// ```rust
19     /// # let end: u32 = 10;
20     /// # let start: u32 = 5;
21     /// let mut i: u32 = end - start;
22     ///
23     /// if i != 0 {
24     ///     i -= 1;
25     /// }
26     /// ```
27     ///
28     /// Use instead:
29     /// ```rust
30     /// # let end: u32 = 10;
31     /// # let start: u32 = 5;
32     /// let mut i: u32 = end - start;
33     ///
34     /// i = i.saturating_sub(1);
35     /// ```
36     #[clippy::version = "1.44.0"]
37     pub IMPLICIT_SATURATING_SUB,
38     style,
39     "Perform saturating subtraction instead of implicitly checking lower bound of data type"
40 }
41
42 declare_lint_pass!(ImplicitSaturatingSub => [IMPLICIT_SATURATING_SUB]);
43
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() {
47             return;
48         }
49         if_chain! {
50             if let Some(higher::If { cond, then, r#else: None }) = higher::If::hir(expr);
51
52             // Check if the conditional expression is a binary operation
53             if let ExprKind::Binary(ref cond_op, cond_left, cond_right) = cond.kind;
54
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;
57
58             // Check if assign operation is done
59             if let Some(target) = subtracts_one(cx, then);
60
61             // Extracting out the variable name
62             if let ExprKind::Path(QPath::Resolved(_, ares_path)) = target.kind;
63
64             then {
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)
69                     } else {
70                         return;
71                     }
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)
75                     } else {
76                         return;
77                     }
78                 } else {
79                     return;
80                 };
81
82                 // Check if the variable in the condition statement is an integer
83                 if !cx.typeck_results().expr_ty(cond_var).is_integral() {
84                     return;
85                 }
86
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() {
94                             } else {
95                                 print_lint_and_sugg(cx, var_name, expr);
96                             };
97                         }
98                     },
99                     ExprKind::Path(QPath::TypeRelative(_, name)) => {
100                         if_chain! {
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();
106                             then {
107                                 print_lint_and_sugg(cx, var_name, expr)
108                             }
109                         }
110                     },
111                     ExprKind::Call(func, []) => {
112                         if_chain! {
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();
119                             then {
120                                 print_lint_and_sugg(cx, var_name, expr)
121                             }
122                         }
123                     },
124                     _ => (),
125                 }
126             }
127         }
128     }
129 }
130
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)
136         },
137         ExprKind::Assign(target, value, _) => {
138             if_chain! {
139                 if let ExprKind::Binary(ref op1, left1, right1) = value.kind;
140                 if BinOpKind::Sub == op1.node;
141
142                 if SpanlessEq::new(cx).eq_expr(left1, target);
143
144                 if is_integer_literal(right1, 1);
145                 then {
146                     Some(target)
147                 } else {
148                     None
149                 }
150             }
151         },
152         _ => None,
153     }
154 }
155
156 fn print_lint_and_sugg(cx: &LateContext<'_>, var_name: &str, expr: &Expr<'_>) {
157     span_lint_and_sugg(
158         cx,
159         IMPLICIT_SATURATING_SUB,
160         expr.span,
161         "implicitly performing saturating subtraction",
162         "try",
163         format!("{var_name} = {var_name}.saturating_sub({});", '1'),
164         Applicability::MachineApplicable,
165     );
166 }