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