2018-12-29 09:04:45 -06:00
|
|
|
use rustc::hir::*;
|
|
|
|
use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
|
2019-04-08 15:43:55 -05:00
|
|
|
use rustc::{declare_lint_pass, declare_tool_lint};
|
2018-12-29 09:04:45 -06:00
|
|
|
use syntax::source_map::Span;
|
2017-09-30 12:14:00 -05:00
|
|
|
|
2019-01-30 19:15:29 -06:00
|
|
|
use crate::consts::{constant_simple, Constant};
|
2019-05-11 22:40:05 -05:00
|
|
|
use crate::utils::{in_macro_or_desugar, span_lint};
|
2019-01-30 19:15:29 -06:00
|
|
|
|
2018-03-28 08:24:26 -05:00
|
|
|
declare_clippy_lint! {
|
2019-01-30 19:15:29 -06:00
|
|
|
/// **What it does:** Checks for erasing operations, e.g., `x * 0`.
|
2019-03-05 10:50:33 -06:00
|
|
|
///
|
|
|
|
/// **Why is this bad?** The whole expression can be replaced by zero.
|
|
|
|
/// This is most likely not the intended outcome and should probably be
|
|
|
|
/// corrected
|
|
|
|
///
|
|
|
|
/// **Known problems:** None.
|
|
|
|
///
|
|
|
|
/// **Example:**
|
2019-01-30 19:15:29 -06:00
|
|
|
/// ```rust
|
2019-03-10 17:01:56 -05:00
|
|
|
/// let x = 1;
|
2019-03-05 10:50:33 -06:00
|
|
|
/// 0 / x;
|
|
|
|
/// 0 * x;
|
2019-03-10 17:01:56 -05:00
|
|
|
/// x & 0;
|
2019-03-05 10:50:33 -06:00
|
|
|
/// ```
|
2017-09-30 12:14:00 -05:00
|
|
|
pub ERASING_OP,
|
2018-03-28 08:24:26 -05:00
|
|
|
correctness,
|
2019-01-30 19:15:29 -06:00
|
|
|
"using erasing operations, e.g., `x * 0` or `y & 0`"
|
2017-09-30 12:14:00 -05:00
|
|
|
}
|
|
|
|
|
2019-04-08 15:43:55 -05:00
|
|
|
declare_lint_pass!(ErasingOp => [ERASING_OP]);
|
2017-09-30 12:14:00 -05:00
|
|
|
|
|
|
|
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ErasingOp {
|
|
|
|
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
|
2019-05-11 22:40:05 -05:00
|
|
|
if in_macro_or_desugar(e.span) {
|
2017-09-30 12:14:00 -05:00
|
|
|
return;
|
|
|
|
}
|
2018-07-12 02:30:57 -05:00
|
|
|
if let ExprKind::Binary(ref cmp, ref left, ref right) = e.node {
|
2017-09-30 12:14:00 -05:00
|
|
|
match cmp.node {
|
2018-07-12 02:50:09 -05:00
|
|
|
BinOpKind::Mul | BinOpKind::BitAnd => {
|
2017-09-30 12:14:00 -05:00
|
|
|
check(cx, left, e.span);
|
|
|
|
check(cx, right, e.span);
|
|
|
|
},
|
2018-07-12 02:50:09 -05:00
|
|
|
BinOpKind::Div => check(cx, left, e.span),
|
2017-09-30 12:14:00 -05:00
|
|
|
_ => (),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-23 06:01:12 -05:00
|
|
|
fn check(cx: &LateContext<'_, '_>, e: &Expr, span: Span) {
|
2018-05-13 06:16:31 -05:00
|
|
|
if let Some(Constant::Int(v)) = constant_simple(cx, cx.tables, e) {
|
2018-03-13 05:38:11 -05:00
|
|
|
if v == 0 {
|
2017-09-30 12:14:00 -05:00
|
|
|
span_lint(
|
|
|
|
cx,
|
|
|
|
ERASING_OP,
|
|
|
|
span,
|
2017-10-15 02:32:47 -05:00
|
|
|
"this operation will always return zero. This is likely not the intended outcome",
|
2017-09-30 12:14:00 -05:00
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|