]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/zero_div_zero.rs
Auto merge of #4938 - flip1995:rustup, r=flip1995
[rust.git] / clippy_lints / src / zero_div_zero.rs
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;
5 use rustc::hir::*;
6 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
7 use rustc_session::declare_tool_lint;
8
9 declare_clippy_lint! {
10     /// **What it does:** Checks for `0.0 / 0.0`.
11     ///
12     /// **Why is this bad?** It's less readable than `std::f32::NAN` or
13     /// `std::f64::NAN`.
14     ///
15     /// **Known problems:** None.
16     ///
17     /// **Example:**
18     /// ```rust
19     /// 0.0f32 / 0.0;
20     /// ```
21     pub ZERO_DIVIDED_BY_ZERO,
22     complexity,
23     "usage of `0.0 / 0.0` to obtain NaN instead of std::f32::NaN or std::f64::NaN"
24 }
25
26 declare_lint_pass!(ZeroDiv => [ZERO_DIVIDED_BY_ZERO]);
27
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
31         if_chain! {
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;
41             then {
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) {
45                     (Constant::F64(_), _)
46                     | (_, Constant::F64(_)) => "f64",
47                     _ => "f32"
48                 };
49                 span_help_and_lint(
50                     cx,
51                     ZERO_DIVIDED_BY_ZERO,
52                     expr.span,
53                     "constant division of 0.0 with 0.0 will always result in NaN",
54                     &format!(
55                         "Consider using `std::{}::NAN` if you would like a constant representing NaN",
56                         float_type,
57                     ),
58                 );
59             }
60         }
61     }
62 }