1 use crate::consts::{constant_simple, Constant};
3 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
4 use rustc::{declare_lint, lint_array};
5 use syntax::source_map::Span;
6 use crate::utils::{in_macro, snippet, span_lint, unsext, clip};
9 /// **What it does:** Checks for identity operations, e.g. `x + 0`.
11 /// **Why is this bad?** This code can be removed without changing the
12 /// meaning. So it just obscures what's going on. Delete it mercilessly.
14 /// **Known problems:** None.
18 /// x / 1 + 0 * 1 - 0 | 0
20 declare_clippy_lint! {
23 "using identity operations, e.g. `x + 0` or `y / 1`"
26 #[derive(Copy, Clone)]
27 pub struct IdentityOp;
29 impl LintPass for IdentityOp {
30 fn get_lints(&self) -> LintArray {
31 lint_array!(IDENTITY_OP)
35 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for IdentityOp {
36 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
40 if let ExprKind::Binary(ref cmp, ref left, ref right) = e.node {
42 BinOpKind::Add | BinOpKind::BitOr | BinOpKind::BitXor => {
43 check(cx, left, 0, e.span, right.span);
44 check(cx, right, 0, e.span, left.span);
46 BinOpKind::Shl | BinOpKind::Shr | BinOpKind::Sub => check(cx, right, 0, e.span, left.span),
48 check(cx, left, 1, e.span, right.span);
49 check(cx, right, 1, e.span, left.span);
51 BinOpKind::Div => check(cx, right, 1, e.span, left.span),
52 BinOpKind::BitAnd => {
53 check(cx, left, -1, e.span, right.span);
54 check(cx, right, -1, e.span, left.span);
62 #[allow(cast_possible_wrap)]
63 fn check(cx: &LateContext<'_, '_>, e: &Expr, m: i8, span: Span, arg: Span) {
64 if let Some(Constant::Int(v)) = constant_simple(cx, cx.tables, e) {
65 let check = match cx.tables.expr_ty(e).sty {
66 ty::Int(ity) => unsext(cx.tcx, -1_i128, ity),
67 ty::Uint(uty) => clip(cx.tcx, !0, uty),
81 "the operation is ineffective. Consider reducing it to `{}`",
82 snippet(cx, arg, "..")