]> git.lizzy.rs Git - rust.git/blob - src/zero_div_zero.rs
Merge pull request #928 from oli-obk/unnecessary_operation
[rust.git] / src / zero_div_zero.rs
1 use consts::{Constant, constant_simple, FloatWidth};
2 use rustc::lint::*;
3 use rustc::hir::*;
4 use utils::span_help_and_lint;
5
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;
10
11 /// **What it does:** This lint checks for `0.0 / 0.0`.
12 ///
13 /// **Why is this bad?** It's less readable than `std::f32::NAN` or `std::f64::NAN`
14 ///
15 /// **Known problems:** None
16 ///
17 /// **Example** `0.0f32 / 0.0`
18 declare_lint! {
19     pub ZERO_DIVIDED_BY_ZERO,
20     Warn,
21     "usage of `0.0 / 0.0` to obtain NaN instead of std::f32::NaN or std::f64::NaN"
22 }
23
24 impl LintPass for ZeroDivZeroPass {
25     fn get_lints(&self) -> LintArray {
26         lint_array!(ZERO_DIVIDED_BY_ZERO)
27     }
28 }
29
30 impl LateLintPass for ZeroDivZeroPass {
31     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
32         // check for instances of 0.0/0.0
33         if_let_chain! {
34             [
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()
44             ],
45             {
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) {
49                     (FloatWidth::F64, _)
50                     | (_, FloatWidth::F64) => "f64",
51                     _ => "f32"
52                 };
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));
56             }
57         }
58     }
59 }