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