]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/implicit_saturating_sub.rs
Auto merge of #7957 - surechen:fix_for_7854, r=giraffate
[rust.git] / clippy_lints / src / implicit_saturating_sub.rs
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};
10
11 declare_clippy_lint! {
12     /// ### What it does
13     /// Checks for implicit saturating subtraction.
14     ///
15     /// ### Why is this bad?
16     /// Simplicity and readability. Instead we can easily use an builtin function.
17     ///
18     /// ### Example
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     #[clippy::version = "1.44.0"]
34     pub IMPLICIT_SATURATING_SUB,
35     pedantic,
36     "Perform saturating subtraction instead of implicitly checking lower bound of data type"
37 }
38
39 declare_lint_pass!(ImplicitSaturatingSub => [IMPLICIT_SATURATING_SUB]);
40
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() {
44             return;
45         }
46         if_chain! {
47             if let Some(higher::If { cond, then, r#else: None }) = higher::If::hir(expr);
48
49             // Check if the conditional expression is a binary operation
50             if let ExprKind::Binary(ref cond_op, cond_left, cond_right) = cond.kind;
51
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;
54
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();
58
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);
62
63             // Extracting out the variable name
64             if let ExprKind::Path(QPath::Resolved(_, ares_path)) = target.kind;
65
66             then {
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)
71                     } else {
72                         return;
73                     }
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)
77                     } else {
78                         return;
79                     }
80                 } else {
81                     return;
82                 };
83
84                 // Check if the variable in the condition statement is an integer
85                 if !cx.typeck_results().expr_ty(cond_var).is_integral() {
86                     return;
87                 }
88
89                 // Get the variable name
90                 let var_name = ares_path.segments[0].ident.name.as_str();
91                 const INT_TYPES: [LangItem; 5] = [
92                     LangItem::I8,
93                     LangItem::I16,
94                     LangItem::I32,
95                     LangItem::I64,
96                     LangItem::Isize
97                 ];
98
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() {
104                             } else {
105                                 print_lint_and_sugg(cx, &var_name, expr);
106                             };
107                         }
108                     },
109                     ExprKind::Path(QPath::TypeRelative(_, name)) => {
110                         if_chain! {
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);
116                             then {
117                                 print_lint_and_sugg(cx, &var_name, expr)
118                             }
119                         }
120                     },
121                     ExprKind::Call(func, []) => {
122                         if_chain! {
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);
129                             then {
130                                 print_lint_and_sugg(cx, &var_name, expr)
131                             }
132                         }
133                     },
134                     _ => (),
135                 }
136             }
137         }
138     }
139 }
140
141 fn subtracts_one<'a>(cx: &LateContext<'_>, expr: &Expr<'a>) -> Option<&'a Expr<'a>> {
142     match expr.kind {
143         ExprKind::AssignOp(ref op1, target, value) => {
144             if_chain! {
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;
149                 then {
150                     Some(target)
151                 } else {
152                     None
153                 }
154             }
155         },
156         ExprKind::Assign(target, value, _) => {
157             if_chain! {
158                 if let ExprKind::Binary(ref op1, left1, right1) = value.kind;
159                 if BinOpKind::Sub == op1.node;
160
161                 if SpanlessEq::new(cx).eq_expr(left1, target);
162
163                 if let ExprKind::Lit(ref lit1) = right1.kind;
164                 if let LitKind::Int(1, _) = lit1.node;
165                 then {
166                     Some(target)
167                 } else {
168                     None
169                 }
170             }
171         },
172         _ => None,
173     }
174 }
175
176 fn print_lint_and_sugg(cx: &LateContext<'_>, var_name: &str, expr: &Expr<'_>) {
177     span_lint_and_sugg(
178         cx,
179         IMPLICIT_SATURATING_SUB,
180         expr.span,
181         "implicitly performing saturating subtraction",
182         "try",
183         format!("{} = {}.saturating_sub({});", var_name, var_name, '1'),
184         Applicability::MachineApplicable,
185     );
186 }