2015-05-15 11:46:43 -05:00
|
|
|
use rustc::lint::*;
|
2015-09-03 09:42:17 -05:00
|
|
|
use rustc_front::hir::*;
|
2015-05-15 11:46:43 -05:00
|
|
|
use syntax::codemap::Span;
|
|
|
|
|
2015-08-17 04:43:36 -05:00
|
|
|
use consts::{constant, is_negative};
|
2015-08-17 10:51:30 -05:00
|
|
|
use consts::Constant::ConstantInt;
|
2015-08-26 17:31:35 -05:00
|
|
|
use utils::{span_lint, snippet, in_external_macro};
|
2015-07-09 10:02:21 -05:00
|
|
|
|
2015-05-15 11:46:43 -05:00
|
|
|
declare_lint! { pub IDENTITY_OP, Warn,
|
2015-08-13 03:32:35 -05:00
|
|
|
"using identity operations, e.g. `x + 0` or `y / 1`" }
|
2015-08-11 13:22:20 -05:00
|
|
|
|
2015-05-15 11:46:43 -05:00
|
|
|
#[derive(Copy,Clone)]
|
|
|
|
pub struct IdentityOp;
|
|
|
|
|
|
|
|
impl LintPass for IdentityOp {
|
|
|
|
fn get_lints(&self) -> LintArray {
|
|
|
|
lint_array!(IDENTITY_OP)
|
|
|
|
}
|
2015-05-22 17:49:13 -05:00
|
|
|
|
2015-05-15 11:46:43 -05:00
|
|
|
fn check_expr(&mut self, cx: &Context, e: &Expr) {
|
2015-05-22 17:49:13 -05:00
|
|
|
if let ExprBinary(ref cmp, ref left, ref right) = e.node {
|
|
|
|
match cmp.node {
|
|
|
|
BiAdd | BiBitOr | BiBitXor => {
|
|
|
|
check(cx, left, 0, e.span, right.span);
|
|
|
|
check(cx, right, 0, e.span, left.span);
|
|
|
|
},
|
2015-08-11 13:22:20 -05:00
|
|
|
BiShl | BiShr | BiSub =>
|
2015-05-22 17:49:13 -05:00
|
|
|
check(cx, right, 0, e.span, left.span),
|
|
|
|
BiMul => {
|
|
|
|
check(cx, left, 1, e.span, right.span);
|
|
|
|
check(cx, right, 1, e.span, left.span);
|
|
|
|
},
|
|
|
|
BiDiv =>
|
|
|
|
check(cx, right, 1, e.span, left.span),
|
|
|
|
BiBitAnd => {
|
|
|
|
check(cx, left, -1, e.span, right.span);
|
|
|
|
check(cx, right, -1, e.span, left.span);
|
|
|
|
},
|
|
|
|
_ => ()
|
|
|
|
}
|
|
|
|
}
|
2015-05-15 11:46:43 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
fn check(cx: &Context, e: &Expr, m: i8, span: Span, arg: Span) {
|
2015-08-17 10:51:30 -05:00
|
|
|
if let Some((c, needed_resolution)) = constant(cx, e) {
|
|
|
|
if needed_resolution { return; } // skip linting w/ lookup for now
|
|
|
|
if let ConstantInt(v, ty) = c {
|
2015-08-16 16:09:56 -05:00
|
|
|
if match m {
|
|
|
|
0 => v == 0,
|
2015-08-17 04:43:36 -05:00
|
|
|
-1 => is_negative(ty) && v == 1,
|
|
|
|
1 => !is_negative(ty) && v == 1,
|
2015-08-16 16:09:56 -05:00
|
|
|
_ => unreachable!(),
|
|
|
|
} {
|
2015-08-26 17:31:35 -05:00
|
|
|
if in_external_macro(cx, e.span) {return;}
|
2015-08-16 16:09:56 -05:00
|
|
|
span_lint(cx, IDENTITY_OP, span, &format!(
|
|
|
|
"the operation is ineffective. Consider reducing it to `{}`",
|
|
|
|
snippet(cx, arg, "..")));
|
2015-05-22 17:49:13 -05:00
|
|
|
}
|
2015-08-16 16:09:56 -05:00
|
|
|
}
|
2015-05-22 17:49:13 -05:00
|
|
|
}
|
2015-05-15 11:46:43 -05:00
|
|
|
}
|