2021-05-27 08:49:37 -05:00
|
|
|
use clippy_utils::consts::{constant_simple, Constant};
|
2021-03-15 19:55:45 -05:00
|
|
|
use clippy_utils::diagnostics::span_lint;
|
2020-02-21 02:39:38 -06:00
|
|
|
use rustc_hir::{BinOpKind, Expr, ExprKind};
|
2020-01-12 00:08:41 -06:00
|
|
|
use rustc_lint::{LateContext, LateLintPass};
|
2020-01-11 05:37:08 -06:00
|
|
|
use rustc_session::{declare_lint_pass, declare_tool_lint};
|
2020-01-04 04:00:00 -06:00
|
|
|
use rustc_span::source_map::Span;
|
2017-09-30 12:14:00 -05:00
|
|
|
|
2018-03-28 08:24:26 -05:00
|
|
|
declare_clippy_lint! {
|
2021-07-02 13:37:11 -05:00
|
|
|
/// ### What it does
|
|
|
|
/// Checks for erasing operations, e.g., `x * 0`.
|
2019-03-05 10:50:33 -06:00
|
|
|
///
|
2021-07-02 13:37:11 -05:00
|
|
|
/// ### Why is this bad?
|
|
|
|
/// The whole expression can be replaced by zero.
|
2019-03-05 10:50:33 -06:00
|
|
|
/// This is most likely not the intended outcome and should probably be
|
|
|
|
/// corrected
|
|
|
|
///
|
2021-07-02 13:37:11 -05:00
|
|
|
/// ### 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
|
|
|
|
2020-06-25 15:41:36 -05:00
|
|
|
impl<'tcx> LateLintPass<'tcx> for ErasingOp {
|
|
|
|
fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
|
2019-08-19 11:30:32 -05:00
|
|
|
if e.span.from_expansion() {
|
2017-09-30 12:14:00 -05:00
|
|
|
return;
|
|
|
|
}
|
2021-04-02 16:35:32 -05:00
|
|
|
if let ExprKind::Binary(ref cmp, left, right) = e.kind {
|
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
|
|
|
_ => (),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-25 15:41:36 -05:00
|
|
|
fn check(cx: &LateContext<'_>, e: &Expr<'_>, span: Span) {
|
2020-07-17 03:47:04 -05:00
|
|
|
if let Some(Constant::Int(0)) = constant_simple(cx, cx.typeck_results(), e) {
|
2019-09-29 11:40:38 -05:00
|
|
|
span_lint(
|
|
|
|
cx,
|
|
|
|
ERASING_OP,
|
|
|
|
span,
|
|
|
|
"this operation will always return zero. This is likely not the intended outcome",
|
|
|
|
);
|
2017-09-30 12:14:00 -05:00
|
|
|
}
|
|
|
|
}
|