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