]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/identity_op.rs
Rollup merge of #97798 - WaffleLapkin:allow_for_suggestions_that_are_quite_far_away_f...
[rust.git] / clippy_lints / src / identity_op.rs
1 use clippy_utils::consts::{constant_full_int, constant_simple, Constant, FullInt};
2 use clippy_utils::diagnostics::span_lint_and_sugg;
3 use clippy_utils::source::snippet_with_applicability;
4 use clippy_utils::{clip, unsext};
5 use rustc_errors::Applicability;
6 use rustc_hir::{BinOp, BinOpKind, Expr, ExprKind, Node};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_middle::ty;
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 use rustc_span::source_map::Span;
11
12 declare_clippy_lint! {
13     /// ### What it does
14     /// Checks for identity operations, e.g., `x + 0`.
15     ///
16     /// ### Why is this bad?
17     /// This code can be removed without changing the
18     /// meaning. So it just obscures what's going on. Delete it mercilessly.
19     ///
20     /// ### Example
21     /// ```rust
22     /// # let x = 1;
23     /// x / 1 + 0 * 1 - 0 | 0;
24     /// ```
25     #[clippy::version = "pre 1.29.0"]
26     pub IDENTITY_OP,
27     complexity,
28     "using identity operations, e.g., `x + 0` or `y / 1`"
29 }
30
31 declare_lint_pass!(IdentityOp => [IDENTITY_OP]);
32
33 impl<'tcx> LateLintPass<'tcx> for IdentityOp {
34     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
35         if expr.span.from_expansion() {
36             return;
37         }
38         if let ExprKind::Binary(cmp, left, right) = &expr.kind {
39             if !is_allowed(cx, *cmp, left, right) {
40                 match cmp.node {
41                     BinOpKind::Add | BinOpKind::BitOr | BinOpKind::BitXor => {
42                         check(cx, left, 0, expr.span, right.span, needs_parenthesis(cx, expr, right));
43                         check(cx, right, 0, expr.span, left.span, Parens::Unneeded);
44                     },
45                     BinOpKind::Shl | BinOpKind::Shr | BinOpKind::Sub => {
46                         check(cx, right, 0, expr.span, left.span, Parens::Unneeded);
47                     },
48                     BinOpKind::Mul => {
49                         check(cx, left, 1, expr.span, right.span, needs_parenthesis(cx, expr, right));
50                         check(cx, right, 1, expr.span, left.span, Parens::Unneeded);
51                     },
52                     BinOpKind::Div => check(cx, right, 1, expr.span, left.span, Parens::Unneeded),
53                     BinOpKind::BitAnd => {
54                         check(cx, left, -1, expr.span, right.span, needs_parenthesis(cx, expr, right));
55                         check(cx, right, -1, expr.span, left.span, Parens::Unneeded);
56                     },
57                     BinOpKind::Rem => check_remainder(cx, left, right, expr.span, left.span),
58                     _ => (),
59                 }
60             }
61         }
62     }
63 }
64
65 #[derive(Copy, Clone)]
66 enum Parens {
67     Needed,
68     Unneeded,
69 }
70
71 /// Checks if `left op right` needs parenthesis when reduced to `right`
72 /// e.g. `0 + if b { 1 } else { 2 } + if b { 3 } else { 4 }` cannot be reduced
73 /// to `if b { 1 } else { 2 } + if b { 3 } else { 4 }` where the `if` could be
74 /// interpreted as a statement
75 ///
76 /// See #8724
77 fn needs_parenthesis(cx: &LateContext<'_>, binary: &Expr<'_>, right: &Expr<'_>) -> Parens {
78     match right.kind {
79         ExprKind::Binary(_, lhs, _) | ExprKind::Cast(lhs, _) => {
80             // ensure we're checking against the leftmost expression of `right`
81             //
82             //     ~~~ `lhs`
83             // 0 + {4} * 2
84             //     ~~~~~~~ `right`
85             return needs_parenthesis(cx, binary, lhs);
86         },
87         ExprKind::If(..) | ExprKind::Match(..) | ExprKind::Block(..) | ExprKind::Loop(..) => {},
88         _ => return Parens::Unneeded,
89     }
90
91     let mut prev_id = binary.hir_id;
92     for (_, node) in cx.tcx.hir().parent_iter(binary.hir_id) {
93         if let Node::Expr(expr) = node
94             && let ExprKind::Binary(_, lhs, _) | ExprKind::Cast(lhs, _) = expr.kind
95             && lhs.hir_id == prev_id
96         {
97             // keep going until we find a node that encompasses left of `binary`
98             prev_id = expr.hir_id;
99             continue;
100         }
101
102         match node {
103             Node::Block(_) | Node::Stmt(_) => break,
104             _ => return Parens::Unneeded,
105         };
106     }
107
108     Parens::Needed
109 }
110
111 fn is_allowed(cx: &LateContext<'_>, cmp: BinOp, left: &Expr<'_>, right: &Expr<'_>) -> bool {
112     // This lint applies to integers
113     !cx.typeck_results().expr_ty(left).peel_refs().is_integral()
114         || !cx.typeck_results().expr_ty(right).peel_refs().is_integral()
115         // `1 << 0` is a common pattern in bit manipulation code
116         || (cmp.node == BinOpKind::Shl
117             && constant_simple(cx, cx.typeck_results(), right) == Some(Constant::Int(0))
118             && constant_simple(cx, cx.typeck_results(), left) == Some(Constant::Int(1)))
119 }
120
121 fn check_remainder(cx: &LateContext<'_>, left: &Expr<'_>, right: &Expr<'_>, span: Span, arg: Span) {
122     let lhs_const = constant_full_int(cx, cx.typeck_results(), left);
123     let rhs_const = constant_full_int(cx, cx.typeck_results(), right);
124     if match (lhs_const, rhs_const) {
125         (Some(FullInt::S(lv)), Some(FullInt::S(rv))) => lv.abs() < rv.abs(),
126         (Some(FullInt::U(lv)), Some(FullInt::U(rv))) => lv < rv,
127         _ => return,
128     } {
129         span_ineffective_operation(cx, span, arg, Parens::Unneeded);
130     }
131 }
132
133 fn check(cx: &LateContext<'_>, e: &Expr<'_>, m: i8, span: Span, arg: Span, parens: Parens) {
134     if let Some(Constant::Int(v)) = constant_simple(cx, cx.typeck_results(), e).map(Constant::peel_refs) {
135         let check = match *cx.typeck_results().expr_ty(e).peel_refs().kind() {
136             ty::Int(ity) => unsext(cx.tcx, -1_i128, ity),
137             ty::Uint(uty) => clip(cx.tcx, !0, uty),
138             _ => return,
139         };
140         if match m {
141             0 => v == 0,
142             -1 => v == check,
143             1 => v == 1,
144             _ => unreachable!(),
145         } {
146             span_ineffective_operation(cx, span, arg, parens);
147         }
148     }
149 }
150
151 fn span_ineffective_operation(cx: &LateContext<'_>, span: Span, arg: Span, parens: Parens) {
152     let mut applicability = Applicability::MachineApplicable;
153     let expr_snippet = snippet_with_applicability(cx, arg, "..", &mut applicability);
154
155     let suggestion = match parens {
156         Parens::Needed => format!("({expr_snippet})"),
157         Parens::Unneeded => expr_snippet.into_owned(),
158     };
159
160     span_lint_and_sugg(
161         cx,
162         IDENTITY_OP,
163         span,
164         "this operation has no effect",
165         "consider reducing it to",
166         suggestion,
167         applicability,
168     );
169 }