]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/zero_div_zero.rs
move lint documentation into macro invocations
[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_tool_lint, lint_array};
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 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     fn name(&self) -> &'static str {
33         "ZeroDiv"
34     }
35 }
36
37 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
38     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
39         // check for instances of 0.0/0.0
40         if_chain! {
41             if let ExprKind::Binary(ref op, ref left, ref right) = expr.node;
42             if let BinOpKind::Div = op.node;
43             // TODO - constant_simple does not fold many operations involving floats.
44             // That's probably fine for this lint - it's pretty unlikely that someone would
45             // do something like 0.0/(2.0 - 2.0), but it would be nice to warn on that case too.
46             if let Some(lhs_value) = constant_simple(cx, cx.tables, left);
47             if let Some(rhs_value) = constant_simple(cx, cx.tables, right);
48             if Constant::F32(0.0) == lhs_value || Constant::F64(0.0) == lhs_value;
49             if Constant::F32(0.0) == rhs_value || Constant::F64(0.0) == rhs_value;
50             then {
51                 // since we're about to suggest a use of std::f32::NaN or std::f64::NaN,
52                 // match the precision of the literals that are given.
53                 let float_type = match (lhs_value, rhs_value) {
54                     (Constant::F64(_), _)
55                     | (_, Constant::F64(_)) => "f64",
56                     _ => "f32"
57                 };
58                 span_help_and_lint(
59                     cx,
60                     ZERO_DIVIDED_BY_ZERO,
61                     expr.span,
62                     "constant division of 0.0 with 0.0 will always result in NaN",
63                     &format!(
64                         "Consider using `std::{}::NAN` if you would like a constant representing NaN",
65                         float_type,
66                     ),
67                 );
68             }
69         }
70     }
71 }