2 use rustc_front::hir::*;
3 use syntax::codemap::Span;
5 use consts::{constant_simple, is_negative};
6 use consts::Constant::ConstantInt;
7 use utils::{span_lint, snippet, in_macro};
9 /// **What it does:** This lint checks for identity operations, e.g. `x + 0`. It is `Warn` by default.
11 /// **Why is this bad?** This code can be removed without changing the meaning. So it just obscures what's going on. Delete it mercilessly.
13 /// **Known problems:** None
15 /// **Example:** `x / 1 + 0 * 1 - 0 | 0`
16 declare_lint! { pub IDENTITY_OP, Warn,
17 "using identity operations, e.g. `x + 0` or `y / 1`" }
20 pub struct IdentityOp;
22 impl LintPass for IdentityOp {
23 fn get_lints(&self) -> LintArray {
24 lint_array!(IDENTITY_OP)
28 impl LateLintPass for IdentityOp {
29 fn check_expr(&mut self, cx: &LateContext, e: &Expr) {
30 if in_macro(cx, e.span) { return; }
31 if let ExprBinary(ref cmp, ref left, ref right) = e.node {
33 BiAdd | BiBitOr | BiBitXor => {
34 check(cx, left, 0, e.span, right.span);
35 check(cx, right, 0, e.span, left.span);
37 BiShl | BiShr | BiSub =>
38 check(cx, right, 0, e.span, left.span),
40 check(cx, left, 1, e.span, right.span);
41 check(cx, right, 1, e.span, left.span);
44 check(cx, right, 1, e.span, left.span),
46 check(cx, left, -1, e.span, right.span);
47 check(cx, right, -1, e.span, left.span);
56 fn check(cx: &LateContext, e: &Expr, m: i8, span: Span, arg: Span) {
57 if let Some(ConstantInt(v, ty)) = constant_simple(e) {
60 -1 => is_negative(ty) && v == 1,
61 1 => !is_negative(ty) && v == 1,
64 span_lint(cx, IDENTITY_OP, span, &format!(
65 "the operation is ineffective. Consider reducing it to `{}`",
66 snippet(cx, arg, "..")));