]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/operators/identity_op.rs
Auto merge of #98638 - bjorn3:less_string_interning, r=tmiasko
[rust.git] / src / tools / clippy / clippy_lints / src / operators / 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::{BinOpKind, Expr, ExprKind, Node};
7 use rustc_lint::LateContext;
8 use rustc_middle::ty;
9 use rustc_span::source_map::Span;
10
11 use super::IDENTITY_OP;
12
13 pub(crate) fn check<'tcx>(
14     cx: &LateContext<'tcx>,
15     expr: &'tcx Expr<'_>,
16     op: BinOpKind,
17     left: &'tcx Expr<'_>,
18     right: &'tcx Expr<'_>,
19 ) {
20     if !is_allowed(cx, op, left, right) {
21         match op {
22             BinOpKind::Add | BinOpKind::BitOr | BinOpKind::BitXor => {
23                 check_op(cx, left, 0, expr.span, right.span, needs_parenthesis(cx, expr, right));
24                 check_op(cx, right, 0, expr.span, left.span, Parens::Unneeded);
25             },
26             BinOpKind::Shl | BinOpKind::Shr | BinOpKind::Sub => {
27                 check_op(cx, right, 0, expr.span, left.span, Parens::Unneeded);
28             },
29             BinOpKind::Mul => {
30                 check_op(cx, left, 1, expr.span, right.span, needs_parenthesis(cx, expr, right));
31                 check_op(cx, right, 1, expr.span, left.span, Parens::Unneeded);
32             },
33             BinOpKind::Div => check_op(cx, right, 1, expr.span, left.span, Parens::Unneeded),
34             BinOpKind::BitAnd => {
35                 check_op(cx, left, -1, expr.span, right.span, needs_parenthesis(cx, expr, right));
36                 check_op(cx, right, -1, expr.span, left.span, Parens::Unneeded);
37             },
38             BinOpKind::Rem => check_remainder(cx, left, right, expr.span, left.span),
39             _ => (),
40         }
41     }
42 }
43
44 #[derive(Copy, Clone)]
45 enum Parens {
46     Needed,
47     Unneeded,
48 }
49
50 /// Checks if `left op right` needs parenthesis when reduced to `right`
51 /// e.g. `0 + if b { 1 } else { 2 } + if b { 3 } else { 4 }` cannot be reduced
52 /// to `if b { 1 } else { 2 } + if b { 3 } else { 4 }` where the `if` could be
53 /// interpreted as a statement
54 ///
55 /// See #8724
56 fn needs_parenthesis(cx: &LateContext<'_>, binary: &Expr<'_>, right: &Expr<'_>) -> Parens {
57     match right.kind {
58         ExprKind::Binary(_, lhs, _) | ExprKind::Cast(lhs, _) => {
59             // ensure we're checking against the leftmost expression of `right`
60             //
61             //     ~~~ `lhs`
62             // 0 + {4} * 2
63             //     ~~~~~~~ `right`
64             return needs_parenthesis(cx, binary, lhs);
65         },
66         ExprKind::If(..) | ExprKind::Match(..) | ExprKind::Block(..) | ExprKind::Loop(..) => {},
67         _ => return Parens::Unneeded,
68     }
69
70     let mut prev_id = binary.hir_id;
71     for (_, node) in cx.tcx.hir().parent_iter(binary.hir_id) {
72         if let Node::Expr(expr) = node
73             && let ExprKind::Binary(_, lhs, _) | ExprKind::Cast(lhs, _) = expr.kind
74             && lhs.hir_id == prev_id
75         {
76             // keep going until we find a node that encompasses left of `binary`
77             prev_id = expr.hir_id;
78             continue;
79         }
80
81         match node {
82             Node::Block(_) | Node::Stmt(_) => break,
83             _ => return Parens::Unneeded,
84         };
85     }
86
87     Parens::Needed
88 }
89
90 fn is_allowed(cx: &LateContext<'_>, cmp: BinOpKind, left: &Expr<'_>, right: &Expr<'_>) -> bool {
91     // This lint applies to integers
92     !cx.typeck_results().expr_ty(left).peel_refs().is_integral()
93         || !cx.typeck_results().expr_ty(right).peel_refs().is_integral()
94         // `1 << 0` is a common pattern in bit manipulation code
95         || (cmp == BinOpKind::Shl
96             && constant_simple(cx, cx.typeck_results(), right) == Some(Constant::Int(0))
97             && constant_simple(cx, cx.typeck_results(), left) == Some(Constant::Int(1)))
98 }
99
100 fn check_remainder(cx: &LateContext<'_>, left: &Expr<'_>, right: &Expr<'_>, span: Span, arg: Span) {
101     let lhs_const = constant_full_int(cx, cx.typeck_results(), left);
102     let rhs_const = constant_full_int(cx, cx.typeck_results(), right);
103     if match (lhs_const, rhs_const) {
104         (Some(FullInt::S(lv)), Some(FullInt::S(rv))) => lv.abs() < rv.abs(),
105         (Some(FullInt::U(lv)), Some(FullInt::U(rv))) => lv < rv,
106         _ => return,
107     } {
108         span_ineffective_operation(cx, span, arg, Parens::Unneeded);
109     }
110 }
111
112 fn check_op(cx: &LateContext<'_>, e: &Expr<'_>, m: i8, span: Span, arg: Span, parens: Parens) {
113     if let Some(Constant::Int(v)) = constant_simple(cx, cx.typeck_results(), e).map(Constant::peel_refs) {
114         let check = match *cx.typeck_results().expr_ty(e).peel_refs().kind() {
115             ty::Int(ity) => unsext(cx.tcx, -1_i128, ity),
116             ty::Uint(uty) => clip(cx.tcx, !0, uty),
117             _ => return,
118         };
119         if match m {
120             0 => v == 0,
121             -1 => v == check,
122             1 => v == 1,
123             _ => unreachable!(),
124         } {
125             span_ineffective_operation(cx, span, arg, parens);
126         }
127     }
128 }
129
130 fn span_ineffective_operation(cx: &LateContext<'_>, span: Span, arg: Span, parens: Parens) {
131     let mut applicability = Applicability::MachineApplicable;
132     let expr_snippet = snippet_with_applicability(cx, arg, "..", &mut applicability);
133
134     let suggestion = match parens {
135         Parens::Needed => format!("({expr_snippet})"),
136         Parens::Unneeded => expr_snippet.into_owned(),
137     };
138
139     span_lint_and_sugg(
140         cx,
141         IDENTITY_OP,
142         span,
143         "this operation has no effect",
144         "consider reducing it to",
145         suggestion,
146         applicability,
147     );
148 }