]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/implicit_saturating_sub.rs
Merge commit '0cce3f643bfcbb92d5a1bb71858c9cbaff749d6b' 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, 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, 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
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     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, cond_left, 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(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(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(_, 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: [LangItem; 5] = [
90                     LangItem::I8,
91                     LangItem::I16,
92                     LangItem::I32,
93                     LangItem::I64,
94                     LangItem::Isize
95                 ];
96
97                 match cond_num_val.kind {
98                     ExprKind::Lit(ref cond_lit) => {
99                         // Check if the constant is zero
100                         if let LitKind::Int(0, _) = cond_lit.node {
101                             if cx.typeck_results().expr_ty(cond_left).is_signed() {
102                             } else {
103                                 print_lint_and_sugg(cx, &var_name, expr);
104                             };
105                         }
106                     },
107                     ExprKind::Path(QPath::TypeRelative(_, name)) => {
108                         if_chain! {
109                             if name.ident.as_str() == "MIN";
110                             if let Some(const_id) = cx.typeck_results().type_dependent_def_id(cond_num_val.hir_id);
111                             if let Some(impl_id) = cx.tcx.impl_of_method(const_id);
112                             let mut int_ids = INT_TYPES.iter().filter_map(|&ty| cx.tcx.lang_items().require(ty).ok());
113                             if int_ids.any(|int_id| int_id == impl_id);
114                             then {
115                                 print_lint_and_sugg(cx, &var_name, expr)
116                             }
117                         }
118                     },
119                     ExprKind::Call(func, []) => {
120                         if_chain! {
121                             if let ExprKind::Path(QPath::TypeRelative(_, name)) = func.kind;
122                             if name.ident.as_str() == "min_value";
123                             if let Some(func_id) = cx.typeck_results().type_dependent_def_id(func.hir_id);
124                             if let Some(impl_id) = cx.tcx.impl_of_method(func_id);
125                             let mut int_ids = INT_TYPES.iter().filter_map(|&ty| cx.tcx.lang_items().require(ty).ok());
126                             if int_ids.any(|int_id| int_id == impl_id);
127                             then {
128                                 print_lint_and_sugg(cx, &var_name, expr)
129                             }
130                         }
131                     },
132                     _ => (),
133                 }
134             }
135         }
136     }
137 }
138
139 fn subtracts_one<'a>(cx: &LateContext<'_>, expr: &Expr<'a>) -> Option<&'a Expr<'a>> {
140     match expr.kind {
141         ExprKind::AssignOp(ref op1, target, value) => {
142             if_chain! {
143                 if BinOpKind::Sub == op1.node;
144                 // Check if literal being subtracted is one
145                 if let ExprKind::Lit(ref lit1) = value.kind;
146                 if let LitKind::Int(1, _) = lit1.node;
147                 then {
148                     Some(target)
149                 } else {
150                     None
151                 }
152             }
153         },
154         ExprKind::Assign(target, value, _) => {
155             if_chain! {
156                 if let ExprKind::Binary(ref op1, left1, right1) = value.kind;
157                 if BinOpKind::Sub == op1.node;
158
159                 if SpanlessEq::new(cx).eq_expr(left1, target);
160
161                 if let ExprKind::Lit(ref lit1) = right1.kind;
162                 if let LitKind::Int(1, _) = lit1.node;
163                 then {
164                     Some(target)
165                 } else {
166                     None
167                 }
168             }
169         },
170         _ => None,
171     }
172 }
173
174 fn print_lint_and_sugg(cx: &LateContext<'_>, var_name: &str, expr: &Expr<'_>) {
175     span_lint_and_sugg(
176         cx,
177         IMPLICIT_SATURATING_SUB,
178         expr.span,
179         "implicitly performing saturating subtraction",
180         "try",
181         format!("{} = {}.saturating_sub({});", var_name, var_name, '1'),
182         Applicability::MachineApplicable,
183     );
184 }