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