]> git.proxmox.com Git - rustc.git/blame - src/tools/clippy/clippy_lints/src/zero_div_zero.rs
New upstream version 1.63.0+dfsg1
[rustc.git] / src / tools / clippy / clippy_lints / src / zero_div_zero.rs
CommitLineData
17df50a5 1use clippy_utils::consts::{constant_simple, Constant};
cdc7bbd5 2use clippy_utils::diagnostics::span_lint_and_help;
f20569fa
XL
3use if_chain::if_chain;
4use rustc_hir::{BinOpKind, Expr, ExprKind};
5use rustc_lint::{LateContext, LateLintPass};
6use rustc_session::{declare_lint_pass, declare_tool_lint};
7
8declare_clippy_lint! {
94222f64
XL
9 /// ### What it does
10 /// Checks for `0.0 / 0.0`.
f20569fa 11 ///
94222f64
XL
12 /// ### Why is this bad?
13 /// It's less readable than `f32::NAN` or `f64::NAN`.
f20569fa 14 ///
94222f64 15 /// ### Example
f20569fa 16 /// ```rust
f20569fa 17 /// let nan = 0.0f32 / 0.0;
923072b8 18 /// ```
f20569fa 19 ///
923072b8
FG
20 /// Use instead:
21 /// ```rust
f20569fa
XL
22 /// let nan = f32::NAN;
23 /// ```
a2a8927a 24 #[clippy::version = "pre 1.29.0"]
f20569fa
XL
25 pub ZERO_DIVIDED_BY_ZERO,
26 complexity,
27 "usage of `0.0 / 0.0` to obtain NaN instead of `f32::NAN` or `f64::NAN`"
28}
29
30declare_lint_pass!(ZeroDiv => [ZERO_DIVIDED_BY_ZERO]);
31
32impl<'tcx> LateLintPass<'tcx> for ZeroDiv {
33 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
34 // check for instances of 0.0/0.0
35 if_chain! {
cdc7bbd5 36 if let ExprKind::Binary(ref op, left, right) = expr.kind;
c295e0f8 37 if op.node == BinOpKind::Div;
f20569fa
XL
38 // TODO - constant_simple does not fold many operations involving floats.
39 // That's probably fine for this lint - it's pretty unlikely that someone would
40 // do something like 0.0/(2.0 - 2.0), but it would be nice to warn on that case too.
41 if let Some(lhs_value) = constant_simple(cx, cx.typeck_results(), left);
42 if let Some(rhs_value) = constant_simple(cx, cx.typeck_results(), right);
43 if Constant::F32(0.0) == lhs_value || Constant::F64(0.0) == lhs_value;
44 if Constant::F32(0.0) == rhs_value || Constant::F64(0.0) == rhs_value;
45 then {
46 // since we're about to suggest a use of f32::NAN or f64::NAN,
47 // match the precision of the literals that are given.
48 let float_type = match (lhs_value, rhs_value) {
49 (Constant::F64(_), _)
50 | (_, Constant::F64(_)) => "f64",
51 _ => "f32"
52 };
53 span_lint_and_help(
54 cx,
55 ZERO_DIVIDED_BY_ZERO,
56 expr.span,
57 "constant division of `0.0` with `0.0` will always result in NaN",
58 None,
59 &format!(
60 "consider using `{}::NAN` if you would like a constant representing NaN",
61 float_type,
62 ),
63 );
64 }
65 }
66 }
67}