]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/zero_div_zero.rs
Auto merge of #4591 - 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::hir::*;
5 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6 use rustc::{declare_lint_pass, declare_tool_lint};
7
8 declare_clippy_lint! {
9     /// **What it does:** Checks for `0.0 / 0.0`.
10     ///
11     /// **Why is this bad?** It's less readable than `std::f32::NAN` or
12     /// `std::f64::NAN`.
13     ///
14     /// **Known problems:** None.
15     ///
16     /// **Example:**
17     /// ```rust
18     /// 0.0f32 / 0.0;
19     /// ```
20     pub ZERO_DIVIDED_BY_ZERO,
21     complexity,
22     "usage of `0.0 / 0.0` to obtain NaN instead of std::f32::NaN or std::f64::NaN"
23 }
24
25 declare_lint_pass!(ZeroDiv => [ZERO_DIVIDED_BY_ZERO]);
26
27 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ZeroDiv {
28     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
29         // check for instances of 0.0/0.0
30         if_chain! {
31             if let ExprKind::Binary(ref op, ref left, ref right) = expr.kind;
32             if let BinOpKind::Div = op.node;
33             // TODO - constant_simple does not fold many operations involving floats.
34             // That's probably fine for this lint - it's pretty unlikely that someone would
35             // do something like 0.0/(2.0 - 2.0), but it would be nice to warn on that case too.
36             if let Some(lhs_value) = constant_simple(cx, cx.tables, left);
37             if let Some(rhs_value) = constant_simple(cx, cx.tables, right);
38             if Constant::F32(0.0) == lhs_value || Constant::F64(0.0) == lhs_value;
39             if Constant::F32(0.0) == rhs_value || Constant::F64(0.0) == rhs_value;
40             then {
41                 // since we're about to suggest a use of std::f32::NaN or std::f64::NaN,
42                 // match the precision of the literals that are given.
43                 let float_type = match (lhs_value, rhs_value) {
44                     (Constant::F64(_), _)
45                     | (_, Constant::F64(_)) => "f64",
46                     _ => "f32"
47                 };
48                 span_help_and_lint(
49                     cx,
50                     ZERO_DIVIDED_BY_ZERO,
51                     expr.span,
52                     "constant division of 0.0 with 0.0 will always result in NaN",
53                     &format!(
54                         "Consider using `std::{}::NAN` if you would like a constant representing NaN",
55                         float_type,
56                     ),
57                 );
58             }
59         }
60     }
61 }