1 use crate::consts::{constant_simple, Constant};
2 use crate::utils::span_help_and_lint;
3 use if_chain::if_chain;
4 use rustc::declare_lint_pass;
6 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
7 use rustc_session::declare_tool_lint;
10 /// **What it does:** Checks for `0.0 / 0.0`.
12 /// **Why is this bad?** It's less readable than `std::f32::NAN` or
15 /// **Known problems:** None.
21 pub ZERO_DIVIDED_BY_ZERO,
23 "usage of `0.0 / 0.0` to obtain NaN instead of std::f32::NaN or std::f64::NaN"
26 declare_lint_pass!(ZeroDiv => [ZERO_DIVIDED_BY_ZERO]);
28 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ZeroDiv {
29 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
30 // check for instances of 0.0/0.0
32 if let ExprKind::Binary(ref op, ref left, ref right) = expr.kind;
33 if let BinOpKind::Div = op.node;
34 // TODO - constant_simple does not fold many operations involving floats.
35 // That's probably fine for this lint - it's pretty unlikely that someone would
36 // do something like 0.0/(2.0 - 2.0), but it would be nice to warn on that case too.
37 if let Some(lhs_value) = constant_simple(cx, cx.tables, left);
38 if let Some(rhs_value) = constant_simple(cx, cx.tables, right);
39 if Constant::F32(0.0) == lhs_value || Constant::F64(0.0) == lhs_value;
40 if Constant::F32(0.0) == rhs_value || Constant::F64(0.0) == rhs_value;
42 // since we're about to suggest a use of std::f32::NaN or std::f64::NaN,
43 // match the precision of the literals that are given.
44 let float_type = match (lhs_value, rhs_value) {
46 | (_, Constant::F64(_)) => "f64",
53 "constant division of 0.0 with 0.0 will always result in NaN",
55 "Consider using `std::{}::NAN` if you would like a constant representing NaN",