]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/int_plus_one.rs
Rollup merge of #104901 - krtab:filetype_compare, r=the8472
[rust.git] / src / tools / clippy / clippy_lints / src / int_plus_one.rs
1 //! lint on blocks unnecessarily using >= with a + 1 or - 1
2
3 use clippy_utils::diagnostics::span_lint_and_sugg;
4 use clippy_utils::source::snippet_opt;
5 use rustc_ast::ast::{BinOpKind, Expr, ExprKind, LitKind};
6 use rustc_ast::token;
7 use rustc_errors::Applicability;
8 use rustc_lint::{EarlyContext, EarlyLintPass};
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
10
11 declare_clippy_lint! {
12     /// ### What it does
13     /// Checks for usage of `x >= y + 1` or `x - 1 >= y` (and `<=`) in a block
14     ///
15     /// ### Why is this bad?
16     /// Readability -- better to use `> y` instead of `>= y + 1`.
17     ///
18     /// ### Example
19     /// ```rust
20     /// # let x = 1;
21     /// # let y = 1;
22     /// if x >= y + 1 {}
23     /// ```
24     ///
25     /// Use instead:
26     /// ```rust
27     /// # let x = 1;
28     /// # let y = 1;
29     /// if x > y {}
30     /// ```
31     #[clippy::version = "pre 1.29.0"]
32     pub INT_PLUS_ONE,
33     complexity,
34     "instead of using `x >= y + 1`, use `x > y`"
35 }
36
37 declare_lint_pass!(IntPlusOne => [INT_PLUS_ONE]);
38
39 // cases:
40 // BinOpKind::Ge
41 // x >= y + 1
42 // x - 1 >= y
43 //
44 // BinOpKind::Le
45 // x + 1 <= y
46 // x <= y - 1
47
48 #[derive(Copy, Clone)]
49 enum Side {
50     Lhs,
51     Rhs,
52 }
53
54 impl IntPlusOne {
55     #[expect(clippy::cast_sign_loss)]
56     fn check_lit(token_lit: token::Lit, target_value: i128) -> bool {
57         if let Ok(LitKind::Int(value, ..)) = LitKind::from_token_lit(token_lit) {
58             return value == (target_value as u128);
59         }
60         false
61     }
62
63     fn check_binop(cx: &EarlyContext<'_>, binop: BinOpKind, lhs: &Expr, rhs: &Expr) -> Option<String> {
64         match (binop, &lhs.kind, &rhs.kind) {
65             // case where `x - 1 >= ...` or `-1 + x >= ...`
66             (BinOpKind::Ge, ExprKind::Binary(lhskind, lhslhs, lhsrhs), _) => {
67                 match (lhskind.node, &lhslhs.kind, &lhsrhs.kind) {
68                     // `-1 + x`
69                     (BinOpKind::Add, ExprKind::Lit(lit), _) if Self::check_lit(*lit, -1) => {
70                         Self::generate_recommendation(cx, binop, lhsrhs, rhs, Side::Lhs)
71                     },
72                     // `x - 1`
73                     (BinOpKind::Sub, _, ExprKind::Lit(lit)) if Self::check_lit(*lit, 1) => {
74                         Self::generate_recommendation(cx, binop, lhslhs, rhs, Side::Lhs)
75                     },
76                     _ => None,
77                 }
78             },
79             // case where `... >= y + 1` or `... >= 1 + y`
80             (BinOpKind::Ge, _, ExprKind::Binary(rhskind, rhslhs, rhsrhs)) if rhskind.node == BinOpKind::Add => {
81                 match (&rhslhs.kind, &rhsrhs.kind) {
82                     // `y + 1` and `1 + y`
83                     (ExprKind::Lit(lit), _) if Self::check_lit(*lit, 1) => {
84                         Self::generate_recommendation(cx, binop, rhsrhs, lhs, Side::Rhs)
85                     },
86                     (_, ExprKind::Lit(lit)) if Self::check_lit(*lit, 1) => {
87                         Self::generate_recommendation(cx, binop, rhslhs, lhs, Side::Rhs)
88                     },
89                     _ => None,
90                 }
91             },
92             // case where `x + 1 <= ...` or `1 + x <= ...`
93             (BinOpKind::Le, ExprKind::Binary(lhskind, lhslhs, lhsrhs), _) if lhskind.node == BinOpKind::Add => {
94                 match (&lhslhs.kind, &lhsrhs.kind) {
95                     // `1 + x` and `x + 1`
96                     (ExprKind::Lit(lit), _) if Self::check_lit(*lit, 1) => {
97                         Self::generate_recommendation(cx, binop, lhsrhs, rhs, Side::Lhs)
98                     },
99                     (_, ExprKind::Lit(lit)) if Self::check_lit(*lit, 1) => {
100                         Self::generate_recommendation(cx, binop, lhslhs, rhs, Side::Lhs)
101                     },
102                     _ => None,
103                 }
104             },
105             // case where `... >= y - 1` or `... >= -1 + y`
106             (BinOpKind::Le, _, ExprKind::Binary(rhskind, rhslhs, rhsrhs)) => {
107                 match (rhskind.node, &rhslhs.kind, &rhsrhs.kind) {
108                     // `-1 + y`
109                     (BinOpKind::Add, ExprKind::Lit(lit), _) if Self::check_lit(*lit, -1) => {
110                         Self::generate_recommendation(cx, binop, rhsrhs, lhs, Side::Rhs)
111                     },
112                     // `y - 1`
113                     (BinOpKind::Sub, _, ExprKind::Lit(lit)) if Self::check_lit(*lit, 1) => {
114                         Self::generate_recommendation(cx, binop, rhslhs, lhs, Side::Rhs)
115                     },
116                     _ => None,
117                 }
118             },
119             _ => None,
120         }
121     }
122
123     fn generate_recommendation(
124         cx: &EarlyContext<'_>,
125         binop: BinOpKind,
126         node: &Expr,
127         other_side: &Expr,
128         side: Side,
129     ) -> Option<String> {
130         let binop_string = match binop {
131             BinOpKind::Ge => ">",
132             BinOpKind::Le => "<",
133             _ => return None,
134         };
135         if let Some(snippet) = snippet_opt(cx, node.span) {
136             if let Some(other_side_snippet) = snippet_opt(cx, other_side.span) {
137                 let rec = match side {
138                     Side::Lhs => Some(format!("{snippet} {binop_string} {other_side_snippet}")),
139                     Side::Rhs => Some(format!("{other_side_snippet} {binop_string} {snippet}")),
140                 };
141                 return rec;
142             }
143         }
144         None
145     }
146
147     fn emit_warning(cx: &EarlyContext<'_>, block: &Expr, recommendation: String) {
148         span_lint_and_sugg(
149             cx,
150             INT_PLUS_ONE,
151             block.span,
152             "unnecessary `>= y + 1` or `x - 1 >=`",
153             "change it to",
154             recommendation,
155             Applicability::MachineApplicable, // snippet
156         );
157     }
158 }
159
160 impl EarlyLintPass for IntPlusOne {
161     fn check_expr(&mut self, cx: &EarlyContext<'_>, item: &Expr) {
162         if let ExprKind::Binary(ref kind, ref lhs, ref rhs) = item.kind {
163             if let Some(rec) = Self::check_binop(cx, kind.node, lhs, rhs) {
164                 Self::emit_warning(cx, item, rec);
165             }
166         }
167     }
168 }