1 use crate::consts::{constant_simple, Constant};
2 use crate::utils::{clip, in_macro, snippet, span_lint, unsext};
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6 use rustc::{declare_tool_lint, lint_array};
7 use syntax::source_map::Span;
10 /// **What it does:** Checks for identity operations, e.g. `x + 0`.
12 /// **Why is this bad?** This code can be removed without changing the
13 /// meaning. So it just obscures what's going on. Delete it mercilessly.
15 /// **Known problems:** None.
19 /// x / 1 + 0 * 1 - 0 | 0
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)
34 fn name(&self) -> &'static str {
39 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for IdentityOp {
40 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
44 if let ExprKind::Binary(ref cmp, ref left, ref right) = e.node {
46 BinOpKind::Add | BinOpKind::BitOr | BinOpKind::BitXor => {
47 check(cx, left, 0, e.span, right.span);
48 check(cx, right, 0, e.span, left.span);
50 BinOpKind::Shl | BinOpKind::Shr | BinOpKind::Sub => check(cx, right, 0, e.span, left.span),
52 check(cx, left, 1, e.span, right.span);
53 check(cx, right, 1, e.span, left.span);
55 BinOpKind::Div => check(cx, right, 1, e.span, left.span),
56 BinOpKind::BitAnd => {
57 check(cx, left, -1, e.span, right.span);
58 check(cx, right, -1, e.span, left.span);
66 #[allow(clippy::cast_possible_wrap)]
67 fn check(cx: &LateContext<'_, '_>, e: &Expr, m: i8, span: Span, arg: Span) {
68 if let Some(Constant::Int(v)) = constant_simple(cx, cx.tables, e) {
69 let check = match cx.tables.expr_ty(e).sty {
70 ty::Int(ity) => unsext(cx.tcx, -1_i128, ity),
71 ty::Uint(uty) => clip(cx.tcx, !0, uty),
85 "the operation is ineffective. Consider reducing it to `{}`",
86 snippet(cx, arg, "..")