1 use consts::{Constant, constant_simple, FloatWidth};
4 use utils::span_help_and_lint;
6 /// `ZeroDivZeroPass` is a pass that checks for a binary expression that consists
7 /// `of 0.0/0.0`, which is always `NaN`. It is more clear to replace instances of
8 /// `0.0/0.0` with `std::f32::NaN` or `std::f64::NaN`, depending on the precision.
9 pub struct ZeroDivZeroPass;
11 /// **What it does:** This lint checks for `0.0 / 0.0`.
13 /// **Why is this bad?** It's less readable than `std::f32::NAN` or `std::f64::NAN`
15 /// **Known problems:** None
17 /// **Example** `0.0f32 / 0.0`
19 pub ZERO_DIVIDED_BY_ZERO,
21 "usage of `0.0 / 0.0` to obtain NaN instead of std::f32::NaN or std::f64::NaN"
24 impl LintPass for ZeroDivZeroPass {
25 fn get_lints(&self) -> LintArray {
26 lint_array!(ZERO_DIVIDED_BY_ZERO)
30 impl LateLintPass for ZeroDivZeroPass {
31 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
32 // check for instances of 0.0/0.0
35 let ExprBinary(ref op, ref left, ref right) = expr.node,
36 let BinOp_::BiDiv = op.node,
37 // TODO - constant_simple does not fold many operations involving floats.
38 // That's probably fine for this lint - it's pretty unlikely that someone would
39 // do something like 0.0/(2.0 - 2.0), but it would be nice to warn on that case too.
40 let Some(Constant::Float(ref lhs_value, lhs_width)) = constant_simple(left),
41 let Some(Constant::Float(ref rhs_value, rhs_width)) = constant_simple(right),
42 let Some(0.0) = lhs_value.parse().ok(),
43 let Some(0.0) = rhs_value.parse().ok()
46 // since we're about to suggest a use of std::f32::NaN or std::f64::NaN,
47 // match the precision of the literals that are given.
48 let float_type = match (lhs_width, rhs_width) {
50 | (_, FloatWidth::F64) => "f64",
53 span_help_and_lint(cx, ZERO_DIVIDED_BY_ZERO, expr.span,
54 "constant division of 0.0 with 0.0 will always result in NaN",
55 &format!("Consider using `std::{}::NAN` if you would like a constant representing NaN", float_type));