]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/implicit_saturating_sub.rs
Rollup merge of #80933 - rcvalle:fix-sysroot-option, r=nagisa
[rust.git] / src / tools / clippy / clippy_lints / src / implicit_saturating_sub.rs
1 use crate::utils::{in_macro, match_qpath, span_lint_and_sugg, SpanlessEq};
2 use if_chain::if_chain;
3 use rustc_ast::ast::LitKind;
4 use rustc_errors::Applicability;
5 use rustc_hir::{BinOpKind, Expr, ExprKind, QPath, StmtKind};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
8
9 declare_clippy_lint! {
10     /// **What it does:** Checks for implicit saturating subtraction.
11     ///
12     /// **Why is this bad?** Simplicity and readability. Instead we can easily use an builtin function.
13     ///
14     /// **Known problems:** None.
15     ///
16     /// **Example:**
17     ///
18     /// ```rust
19     /// let end: u32 = 10;
20     /// let start: u32 = 5;
21     ///
22     /// let mut i: u32 = end - start;
23     ///
24     /// // Bad
25     /// if i != 0 {
26     ///     i -= 1;
27     /// }
28     ///
29     /// // Good
30     /// i = i.saturating_sub(1);
31     /// ```
32     pub IMPLICIT_SATURATING_SUB,
33     pedantic,
34     "Perform saturating subtraction instead of implicitly checking lower bound of data type"
35 }
36
37 declare_lint_pass!(ImplicitSaturatingSub => [IMPLICIT_SATURATING_SUB]);
38
39 impl<'tcx> LateLintPass<'tcx> for ImplicitSaturatingSub {
40     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
41         if in_macro(expr.span) {
42             return;
43         }
44         if_chain! {
45             if let ExprKind::If(cond, then, None) = &expr.kind;
46
47             // Check if the conditional expression is a binary operation
48             if let ExprKind::Binary(ref cond_op, ref cond_left, ref cond_right) = cond.kind;
49
50             // Ensure that the binary operator is >, != and <
51             if BinOpKind::Ne == cond_op.node || BinOpKind::Gt == cond_op.node || BinOpKind::Lt == cond_op.node;
52
53             // Check if the true condition block has only one statement
54             if let ExprKind::Block(ref block, _) = then.kind;
55             if block.stmts.len() == 1 && block.expr.is_none();
56
57             // Check if assign operation is done
58             if let StmtKind::Semi(ref e) = block.stmts[0].kind;
59             if let Some(target) = subtracts_one(cx, e);
60
61             // Extracting out the variable name
62             if let ExprKind::Path(QPath::Resolved(_, ref 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                 const INT_TYPES: [&str; 5] = ["i8", "i16", "i32", "i64", "i128"];
90
91                 match cond_num_val.kind {
92                     ExprKind::Lit(ref cond_lit) => {
93                         // Check if the constant is zero
94                         if let LitKind::Int(0, _) = cond_lit.node {
95                             if cx.typeck_results().expr_ty(cond_left).is_signed() {
96                             } else {
97                                 print_lint_and_sugg(cx, &var_name, expr);
98                             };
99                         }
100                     },
101                     ExprKind::Path(ref cond_num_path) => {
102                         if INT_TYPES.iter().any(|int_type| match_qpath(cond_num_path, &[int_type, "MIN"])) {
103                             print_lint_and_sugg(cx, &var_name, expr);
104                         };
105                     },
106                     ExprKind::Call(ref func, _) => {
107                         if let ExprKind::Path(ref cond_num_path) = func.kind {
108                             if INT_TYPES.iter().any(|int_type| match_qpath(cond_num_path, &[int_type, "min_value"])) {
109                                 print_lint_and_sugg(cx, &var_name, expr);
110                             }
111                         };
112                     },
113                     _ => (),
114                 }
115             }
116         }
117     }
118 }
119
120 fn subtracts_one<'a>(cx: &LateContext<'_>, expr: &Expr<'a>) -> Option<&'a Expr<'a>> {
121     match expr.kind {
122         ExprKind::AssignOp(ref op1, ref target, ref value) => {
123             if_chain! {
124                 if BinOpKind::Sub == op1.node;
125                 // Check if literal being subtracted is one
126                 if let ExprKind::Lit(ref lit1) = value.kind;
127                 if let LitKind::Int(1, _) = lit1.node;
128                 then {
129                     Some(target)
130                 } else {
131                     None
132                 }
133             }
134         },
135         ExprKind::Assign(ref target, ref value, _) => {
136             if_chain! {
137                 if let ExprKind::Binary(ref op1, ref left1, ref right1) = value.kind;
138                 if BinOpKind::Sub == op1.node;
139
140                 if SpanlessEq::new(cx).eq_expr(left1, target);
141
142                 if let ExprKind::Lit(ref lit1) = right1.kind;
143                 if let LitKind::Int(1, _) = lit1.node;
144                 then {
145                     Some(target)
146                 } else {
147                     None
148                 }
149             }
150         },
151         _ => None,
152     }
153 }
154
155 fn print_lint_and_sugg(cx: &LateContext<'_>, var_name: &str, expr: &Expr<'_>) {
156     span_lint_and_sugg(
157         cx,
158         IMPLICIT_SATURATING_SUB,
159         expr.span,
160         "implicitly performing saturating subtraction",
161         "try",
162         format!("{} = {}.saturating_sub({});", var_name, var_name, '1'),
163         Applicability::MachineApplicable,
164     );
165 }