]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/identity_op.rs
Rollup merge of #97415 - cjgillot:is-late-bound-solo, r=estebank
[rust.git] / clippy_lints / src / identity_op.rs
1 use clippy_utils::get_parent_expr;
2 use clippy_utils::source::snippet;
3 use rustc_hir::{BinOp, BinOpKind, Expr, ExprKind};
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_middle::ty;
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
7 use rustc_span::source_map::Span;
8
9 use clippy_utils::consts::{constant_full_int, constant_simple, Constant, FullInt};
10 use clippy_utils::diagnostics::span_lint;
11 use clippy_utils::{clip, unsext};
12
13 declare_clippy_lint! {
14     /// ### What it does
15     /// Checks for identity operations, e.g., `x + 0`.
16     ///
17     /// ### Why is this bad?
18     /// This code can be removed without changing the
19     /// meaning. So it just obscures what's going on. Delete it mercilessly.
20     ///
21     /// ### Example
22     /// ```rust
23     /// # let x = 1;
24     /// x / 1 + 0 * 1 - 0 | 0;
25     /// ```
26     ///
27     /// ### Known problems
28     /// False negatives: `f(0 + if b { 1 } else { 2 } + 3);` is reducible to
29     /// `f(if b { 1 } else { 2 } + 3);`. But the lint doesn't trigger for the code.
30     /// See [#8724](https://github.com/rust-lang/rust-clippy/issues/8724)
31     #[clippy::version = "pre 1.29.0"]
32     pub IDENTITY_OP,
33     complexity,
34     "using identity operations, e.g., `x + 0` or `y / 1`"
35 }
36
37 declare_lint_pass!(IdentityOp => [IDENTITY_OP]);
38
39 impl<'tcx> LateLintPass<'tcx> for IdentityOp {
40     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
41         if expr.span.from_expansion() {
42             return;
43         }
44         if let ExprKind::Binary(cmp, left, right) = &expr.kind {
45             if !is_allowed(cx, *cmp, left, right) {
46                 match cmp.node {
47                     BinOpKind::Add | BinOpKind::BitOr | BinOpKind::BitXor => {
48                         if reducible_to_right(cx, expr, right) {
49                             check(cx, left, 0, expr.span, right.span);
50                         }
51                         check(cx, right, 0, expr.span, left.span);
52                     },
53                     BinOpKind::Shl | BinOpKind::Shr | BinOpKind::Sub => {
54                         check(cx, right, 0, expr.span, left.span);
55                     },
56                     BinOpKind::Mul => {
57                         if reducible_to_right(cx, expr, right) {
58                             check(cx, left, 1, expr.span, right.span);
59                         }
60                         check(cx, right, 1, expr.span, left.span);
61                     },
62                     BinOpKind::Div => check(cx, right, 1, expr.span, left.span),
63                     BinOpKind::BitAnd => {
64                         if reducible_to_right(cx, expr, right) {
65                             check(cx, left, -1, expr.span, right.span);
66                         }
67                         check(cx, right, -1, expr.span, left.span);
68                     },
69                     BinOpKind::Rem => {
70                         // Don't call reducible_to_right because N % N is always reducible to 1
71                         check_remainder(cx, left, right, expr.span, left.span);
72                     },
73                     _ => (),
74                 }
75             }
76         }
77     }
78 }
79
80 /// Checks if `left op ..right` can be actually reduced to `right`
81 /// e.g. `0 + if b { 1 } else { 2 } + if b { 3 } else { 4 }`
82 /// cannot be reduced to `if b { 1 } else { 2 } +  if b { 3 } else { 4 }`
83 /// See #8724
84 fn reducible_to_right(cx: &LateContext<'_>, binary: &Expr<'_>, right: &Expr<'_>) -> bool {
85     if let ExprKind::If(..) | ExprKind::Match(..) | ExprKind::Block(..) | ExprKind::Loop(..) = right.kind {
86         is_toplevel_binary(cx, binary)
87     } else {
88         true
89     }
90 }
91
92 fn is_toplevel_binary(cx: &LateContext<'_>, must_be_binary: &Expr<'_>) -> bool {
93     if let Some(parent) = get_parent_expr(cx, must_be_binary) && let ExprKind::Binary(..) = &parent.kind {
94         false
95     } else {
96         true
97     }
98 }
99
100 fn is_allowed(cx: &LateContext<'_>, cmp: BinOp, left: &Expr<'_>, right: &Expr<'_>) -> bool {
101     // This lint applies to integers
102     !cx.typeck_results().expr_ty(left).peel_refs().is_integral()
103         || !cx.typeck_results().expr_ty(right).peel_refs().is_integral()
104         // `1 << 0` is a common pattern in bit manipulation code
105         || (cmp.node == BinOpKind::Shl
106             && constant_simple(cx, cx.typeck_results(), right) == Some(Constant::Int(0))
107             && constant_simple(cx, cx.typeck_results(), left) == Some(Constant::Int(1)))
108 }
109
110 fn check_remainder(cx: &LateContext<'_>, left: &Expr<'_>, right: &Expr<'_>, span: Span, arg: Span) {
111     let lhs_const = constant_full_int(cx, cx.typeck_results(), left);
112     let rhs_const = constant_full_int(cx, cx.typeck_results(), right);
113     if match (lhs_const, rhs_const) {
114         (Some(FullInt::S(lv)), Some(FullInt::S(rv))) => lv.abs() < rv.abs(),
115         (Some(FullInt::U(lv)), Some(FullInt::U(rv))) => lv < rv,
116         _ => return,
117     } {
118         span_ineffective_operation(cx, span, arg);
119     }
120 }
121
122 fn check(cx: &LateContext<'_>, e: &Expr<'_>, m: i8, span: Span, arg: Span) {
123     if let Some(Constant::Int(v)) = constant_simple(cx, cx.typeck_results(), e).map(Constant::peel_refs) {
124         let check = match *cx.typeck_results().expr_ty(e).peel_refs().kind() {
125             ty::Int(ity) => unsext(cx.tcx, -1_i128, ity),
126             ty::Uint(uty) => clip(cx.tcx, !0, uty),
127             _ => return,
128         };
129         if match m {
130             0 => v == 0,
131             -1 => v == check,
132             1 => v == 1,
133             _ => unreachable!(),
134         } {
135             span_ineffective_operation(cx, span, arg);
136         }
137     }
138 }
139
140 fn span_ineffective_operation(cx: &LateContext<'_>, span: Span, arg: Span) {
141     span_lint(
142         cx,
143         IDENTITY_OP,
144         span,
145         &format!(
146             "the operation is ineffective. Consider reducing it to `{}`",
147             snippet(cx, arg, "..")
148         ),
149     );
150 }