]> git.lizzy.rs Git - rust.git/blob - src/identity_op.rs
Remove * dep
[rust.git] / src / identity_op.rs
1 use rustc::lint::*;
2 use rustc_front::hir::*;
3 use syntax::codemap::Span;
4
5 use consts::{constant_simple, is_negative};
6 use consts::Constant::ConstantInt;
7 use utils::{span_lint, snippet, in_macro};
8
9 /// **What it does:** This lint checks for identity operations, e.g. `x + 0`. It is `Warn` by default.
10 ///
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.
12 ///
13 /// **Known problems:** None
14 ///
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`" }
18
19 #[derive(Copy,Clone)]
20 pub struct IdentityOp;
21
22 impl LintPass for IdentityOp {
23     fn get_lints(&self) -> LintArray {
24         lint_array!(IDENTITY_OP)
25     }
26 }
27
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 {
32             match cmp.node {
33                 BiAdd | BiBitOr | BiBitXor => {
34                     check(cx, left, 0, e.span, right.span);
35                     check(cx, right, 0, e.span, left.span);
36                 }
37                 BiShl | BiShr | BiSub =>
38                     check(cx, right, 0, e.span, left.span),
39                 BiMul => {
40                     check(cx, left, 1, e.span, right.span);
41                     check(cx, right, 1, e.span, left.span);
42                 }
43                 BiDiv =>
44                     check(cx, right, 1, e.span, left.span),
45                 BiBitAnd => {
46                     check(cx, left, -1, e.span, right.span);
47                     check(cx, right, -1, e.span, left.span);
48                 }
49                 _ => ()
50             }
51         }
52     }
53 }
54
55
56 fn check(cx: &LateContext, e: &Expr, m: i8, span: Span, arg: Span) {
57     if let Some(ConstantInt(v, ty)) = constant_simple(e) {
58         if match m {
59             0 => v == 0,
60             -1 => is_negative(ty) && v == 1,
61             1 => !is_negative(ty) && v == 1,
62             _ => unreachable!(),
63         } {
64             span_lint(cx, IDENTITY_OP, span, &format!(
65                 "the operation is ineffective. Consider reducing it to `{}`",
66                snippet(cx, arg, "..")));
67         }
68     }
69 }