1 use crate::consts::{constant_simple, Constant};
4 use syntax::codemap::Span;
5 use crate::utils::{in_macro, snippet, span_lint, unsext, clip};
8 /// **What it does:** Checks for identity operations, e.g. `x + 0`.
10 /// **Why is this bad?** This code can be removed without changing the
11 /// meaning. So it just obscures what's going on. Delete it mercilessly.
13 /// **Known problems:** None.
17 /// x / 1 + 0 * 1 - 0 | 0
19 declare_clippy_lint! {
22 "using identity operations, e.g. `x + 0` or `y / 1`"
25 #[derive(Copy, Clone)]
26 pub struct IdentityOp;
28 impl LintPass for IdentityOp {
29 fn get_lints(&self) -> LintArray {
30 lint_array!(IDENTITY_OP)
34 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for IdentityOp {
35 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
39 if let ExprBinary(ref cmp, ref left, ref right) = e.node {
41 BiAdd | BiBitOr | BiBitXor => {
42 check(cx, left, 0, e.span, right.span);
43 check(cx, right, 0, e.span, left.span);
45 BiShl | BiShr | BiSub => check(cx, right, 0, e.span, left.span),
47 check(cx, left, 1, e.span, right.span);
48 check(cx, right, 1, e.span, left.span);
50 BiDiv => check(cx, right, 1, e.span, left.span),
52 check(cx, left, -1, e.span, right.span);
53 check(cx, right, -1, e.span, left.span);
61 #[allow(cast_possible_wrap)]
62 fn check(cx: &LateContext, e: &Expr, m: i8, span: Span, arg: Span) {
63 if let Some(Constant::Int(v)) = constant_simple(cx, cx.tables, e) {
64 let check = match cx.tables.expr_ty(e).sty {
65 ty::TyInt(ity) => unsext(cx.tcx, -1i128, ity),
66 ty::TyUint(uty) => clip(cx.tcx, !0, uty),
80 "the operation is ineffective. Consider reducing it to `{}`",
81 snippet(cx, arg, "..")