]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/implicit_saturating_sub.rs
Merge commit '0e87918536b9833bbc6c683d1f9d51ee2bf03ef1' into clippyup
[rust.git] / clippy_lints / src / implicit_saturating_sub.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::{in_macro, match_qpath, 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, StmtKind};
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:** Checks for implicit saturating subtraction.
12     ///
13     /// **Why is this bad?** Simplicity and readability. Instead we can easily use an builtin function.
14     ///
15     /// **Known problems:** None.
16     ///
17     /// **Example:**
18     ///
19     /// ```rust
20     /// let end: u32 = 10;
21     /// let start: u32 = 5;
22     ///
23     /// let mut i: u32 = end - start;
24     ///
25     /// // Bad
26     /// if i != 0 {
27     ///     i -= 1;
28     /// }
29     ///
30     /// // Good
31     /// i = i.saturating_sub(1);
32     /// ```
33     pub IMPLICIT_SATURATING_SUB,
34     pedantic,
35     "Perform saturating subtraction instead of implicitly checking lower bound of data type"
36 }
37
38 declare_lint_pass!(ImplicitSaturatingSub => [IMPLICIT_SATURATING_SUB]);
39
40 impl<'tcx> LateLintPass<'tcx> for ImplicitSaturatingSub {
41     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
42         if in_macro(expr.span) {
43             return;
44         }
45         if_chain! {
46             if let ExprKind::If(cond, then, None) = &expr.kind;
47
48             // Check if the conditional expression is a binary operation
49             if let ExprKind::Binary(ref cond_op, ref cond_left, ref cond_right) = cond.kind;
50
51             // Ensure that the binary operator is >, != and <
52             if BinOpKind::Ne == cond_op.node || BinOpKind::Gt == cond_op.node || BinOpKind::Lt == cond_op.node;
53
54             // Check if the true condition block has only one statement
55             if let ExprKind::Block(ref block, _) = then.kind;
56             if block.stmts.len() == 1 && block.expr.is_none();
57
58             // Check if assign operation is done
59             if let StmtKind::Semi(ref e) = block.stmts[0].kind;
60             if let Some(target) = subtracts_one(cx, e);
61
62             // Extracting out the variable name
63             if let ExprKind::Path(QPath::Resolved(_, ref ares_path)) = target.kind;
64
65             then {
66                 // Handle symmetric conditions in the if statement
67                 let (cond_var, cond_num_val) = if SpanlessEq::new(cx).eq_expr(cond_left, target) {
68                     if BinOpKind::Gt == cond_op.node || BinOpKind::Ne == cond_op.node {
69                         (cond_left, cond_right)
70                     } else {
71                         return;
72                     }
73                 } else if SpanlessEq::new(cx).eq_expr(cond_right, target) {
74                     if BinOpKind::Lt == cond_op.node || BinOpKind::Ne == cond_op.node {
75                         (cond_right, cond_left)
76                     } else {
77                         return;
78                     }
79                 } else {
80                     return;
81                 };
82
83                 // Check if the variable in the condition statement is an integer
84                 if !cx.typeck_results().expr_ty(cond_var).is_integral() {
85                     return;
86                 }
87
88                 // Get the variable name
89                 let var_name = ares_path.segments[0].ident.name.as_str();
90                 const INT_TYPES: [&str; 5] = ["i8", "i16", "i32", "i64", "i128"];
91
92                 match cond_num_val.kind {
93                     ExprKind::Lit(ref cond_lit) => {
94                         // Check if the constant is zero
95                         if let LitKind::Int(0, _) = cond_lit.node {
96                             if cx.typeck_results().expr_ty(cond_left).is_signed() {
97                             } else {
98                                 print_lint_and_sugg(cx, &var_name, expr);
99                             };
100                         }
101                     },
102                     ExprKind::Path(ref cond_num_path) => {
103                         if INT_TYPES.iter().any(|int_type| match_qpath(cond_num_path, &[int_type, "MIN"])) {
104                             print_lint_and_sugg(cx, &var_name, expr);
105                         };
106                     },
107                     ExprKind::Call(ref func, _) => {
108                         if let ExprKind::Path(ref cond_num_path) = func.kind {
109                             if INT_TYPES.iter().any(|int_type| match_qpath(cond_num_path, &[int_type, "min_value"])) {
110                                 print_lint_and_sugg(cx, &var_name, expr);
111                             }
112                         };
113                     },
114                     _ => (),
115                 }
116             }
117         }
118     }
119 }
120
121 fn subtracts_one<'a>(cx: &LateContext<'_>, expr: &Expr<'a>) -> Option<&'a Expr<'a>> {
122     match expr.kind {
123         ExprKind::AssignOp(ref op1, ref target, ref value) => {
124             if_chain! {
125                 if BinOpKind::Sub == op1.node;
126                 // Check if literal being subtracted is one
127                 if let ExprKind::Lit(ref lit1) = value.kind;
128                 if let LitKind::Int(1, _) = lit1.node;
129                 then {
130                     Some(target)
131                 } else {
132                     None
133                 }
134             }
135         },
136         ExprKind::Assign(ref target, ref value, _) => {
137             if_chain! {
138                 if let ExprKind::Binary(ref op1, ref left1, ref right1) = value.kind;
139                 if BinOpKind::Sub == op1.node;
140
141                 if SpanlessEq::new(cx).eq_expr(left1, target);
142
143                 if let ExprKind::Lit(ref lit1) = right1.kind;
144                 if let LitKind::Int(1, _) = lit1.node;
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!("{} = {}.saturating_sub({});", var_name, var_name, '1'),
164         Applicability::MachineApplicable,
165     );
166 }