1 use clippy_utils::source::snippet;
2 use rustc_hir::{BinOp, BinOpKind, Expr, ExprKind};
3 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
6 use rustc_span::source_map::Span;
8 use clippy_utils::consts::{constant_simple, Constant};
9 use clippy_utils::diagnostics::span_lint;
10 use clippy_utils::{clip, unsext};
12 declare_clippy_lint! {
14 /// Checks for identity operations, e.g., `x + 0`.
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.
23 /// x / 1 + 0 * 1 - 0 | 0;
25 #[clippy::version = "pre 1.29.0"]
28 "using identity operations, e.g., `x + 0` or `y / 1`"
31 declare_lint_pass!(IdentityOp => [IDENTITY_OP]);
33 impl<'tcx> LateLintPass<'tcx> for IdentityOp {
34 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
35 if e.span.from_expansion() {
38 if let ExprKind::Binary(cmp, left, right) = e.kind {
39 if is_allowed(cx, cmp, left, right) {
43 BinOpKind::Add | BinOpKind::BitOr | BinOpKind::BitXor => {
44 check(cx, left, 0, e.span, right.span);
45 check(cx, right, 0, e.span, left.span);
47 BinOpKind::Shl | BinOpKind::Shr | BinOpKind::Sub => check(cx, right, 0, e.span, left.span),
49 check(cx, left, 1, e.span, right.span);
50 check(cx, right, 1, e.span, left.span);
52 BinOpKind::Div => check(cx, right, 1, e.span, left.span),
53 BinOpKind::BitAnd => {
54 check(cx, left, -1, e.span, right.span);
55 check(cx, right, -1, e.span, left.span);
63 fn is_allowed(cx: &LateContext<'_>, cmp: BinOp, left: &Expr<'_>, right: &Expr<'_>) -> bool {
64 // `1 << 0` is a common pattern in bit manipulation code
65 cmp.node == BinOpKind::Shl
66 && constant_simple(cx, cx.typeck_results(), right) == Some(Constant::Int(0))
67 && constant_simple(cx, cx.typeck_results(), left) == Some(Constant::Int(1))
70 fn check(cx: &LateContext<'_>, e: &Expr<'_>, m: i8, span: Span, arg: Span) {
71 if let Some(Constant::Int(v)) = constant_simple(cx, cx.typeck_results(), e) {
72 let check = match *cx.typeck_results().expr_ty(e).kind() {
73 ty::Int(ity) => unsext(cx.tcx, -1_i128, ity),
74 ty::Uint(uty) => clip(cx.tcx, !0, uty),
88 "the operation is ineffective. Consider reducing it to `{}`",
89 snippet(cx, arg, "..")