]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/implicit_saturating_sub.rs
Merge commit '0eff589afc83e21a03a168497bbab6b4dfbb4ef6' into clippyup
[rust.git] / clippy_lints / src / implicit_saturating_sub.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::{higher, 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::{lang_items::LangItem, 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     ///
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     #[clippy::version = "1.44.0"]
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 expr.span.from_expansion() {
43             return;
44         }
45         if_chain! {
46             if let Some(higher::If { cond, then, r#else: None }) = higher::If::hir(expr);
47
48             // Check if the conditional expression is a binary operation
49             if let ExprKind::Binary(ref cond_op, cond_left, 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 assign operation is done
55             if let Some(target) = subtracts_one(cx, then);
56
57             // Extracting out the variable name
58             if let ExprKind::Path(QPath::Resolved(_, ares_path)) = target.kind;
59
60             then {
61                 // Handle symmetric conditions in the if statement
62                 let (cond_var, cond_num_val) = if SpanlessEq::new(cx).eq_expr(cond_left, target) {
63                     if BinOpKind::Gt == cond_op.node || BinOpKind::Ne == cond_op.node {
64                         (cond_left, cond_right)
65                     } else {
66                         return;
67                     }
68                 } else if SpanlessEq::new(cx).eq_expr(cond_right, target) {
69                     if BinOpKind::Lt == cond_op.node || BinOpKind::Ne == cond_op.node {
70                         (cond_right, cond_left)
71                     } else {
72                         return;
73                     }
74                 } else {
75                     return;
76                 };
77
78                 // Check if the variable in the condition statement is an integer
79                 if !cx.typeck_results().expr_ty(cond_var).is_integral() {
80                     return;
81                 }
82
83                 // Get the variable name
84                 let var_name = ares_path.segments[0].ident.name.as_str();
85                 const INT_TYPES: [LangItem; 5] = [
86                     LangItem::I8,
87                     LangItem::I16,
88                     LangItem::I32,
89                     LangItem::I64,
90                     LangItem::Isize
91                 ];
92
93                 match cond_num_val.kind {
94                     ExprKind::Lit(ref cond_lit) => {
95                         // Check if the constant is zero
96                         if let LitKind::Int(0, _) = cond_lit.node {
97                             if cx.typeck_results().expr_ty(cond_left).is_signed() {
98                             } else {
99                                 print_lint_and_sugg(cx, var_name, expr);
100                             };
101                         }
102                     },
103                     ExprKind::Path(QPath::TypeRelative(_, name)) => {
104                         if_chain! {
105                             if name.ident.as_str() == "MIN";
106                             if let Some(const_id) = cx.typeck_results().type_dependent_def_id(cond_num_val.hir_id);
107                             if let Some(impl_id) = cx.tcx.impl_of_method(const_id);
108                             let mut int_ids = INT_TYPES.iter().filter_map(|&ty| cx.tcx.lang_items().require(ty).ok());
109                             if int_ids.any(|int_id| int_id == impl_id);
110                             then {
111                                 print_lint_and_sugg(cx, var_name, expr)
112                             }
113                         }
114                     },
115                     ExprKind::Call(func, []) => {
116                         if_chain! {
117                             if let ExprKind::Path(QPath::TypeRelative(_, name)) = func.kind;
118                             if name.ident.as_str() == "min_value";
119                             if let Some(func_id) = cx.typeck_results().type_dependent_def_id(func.hir_id);
120                             if let Some(impl_id) = cx.tcx.impl_of_method(func_id);
121                             let mut int_ids = INT_TYPES.iter().filter_map(|&ty| cx.tcx.lang_items().require(ty).ok());
122                             if int_ids.any(|int_id| int_id == impl_id);
123                             then {
124                                 print_lint_and_sugg(cx, var_name, expr)
125                             }
126                         }
127                     },
128                     _ => (),
129                 }
130             }
131         }
132     }
133 }
134
135 fn subtracts_one<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<&'a Expr<'a>> {
136     match peel_blocks_with_stmt(expr).kind {
137         ExprKind::AssignOp(ref op1, target, value) => {
138             if_chain! {
139                 if BinOpKind::Sub == op1.node;
140                 // Check if literal being subtracted is one
141                 if let ExprKind::Lit(ref lit1) = value.kind;
142                 if let LitKind::Int(1, _) = lit1.node;
143                 then {
144                     Some(target)
145                 } else {
146                     None
147                 }
148             }
149         },
150         ExprKind::Assign(target, value, _) => {
151             if_chain! {
152                 if let ExprKind::Binary(ref op1, left1, right1) = value.kind;
153                 if BinOpKind::Sub == op1.node;
154
155                 if SpanlessEq::new(cx).eq_expr(left1, target);
156
157                 if let ExprKind::Lit(ref lit1) = right1.kind;
158                 if let LitKind::Int(1, _) = lit1.node;
159                 then {
160                     Some(target)
161                 } else {
162                     None
163                 }
164             }
165         },
166         _ => None,
167     }
168 }
169
170 fn print_lint_and_sugg(cx: &LateContext<'_>, var_name: &str, expr: &Expr<'_>) {
171     span_lint_and_sugg(
172         cx,
173         IMPLICIT_SATURATING_SUB,
174         expr.span,
175         "implicitly performing saturating subtraction",
176         "try",
177         format!("{} = {}.saturating_sub({});", var_name, var_name, '1'),
178         Applicability::MachineApplicable,
179     );
180 }