1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 use crate::consts::{constant_simple, Constant};
11 use crate::rustc::hir::*;
12 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use crate::utils::span_help_and_lint;
15 use if_chain::if_chain;
17 /// **What it does:** Checks for `0.0 / 0.0`.
19 /// **Why is this bad?** It's less readable than `std::f32::NAN` or
22 /// **Known problems:** None.
28 declare_clippy_lint! {
29 pub ZERO_DIVIDED_BY_ZERO,
31 "usage of `0.0 / 0.0` to obtain NaN instead of std::f32::NaN or std::f64::NaN"
36 impl LintPass for Pass {
37 fn get_lints(&self) -> LintArray {
38 lint_array!(ZERO_DIVIDED_BY_ZERO)
42 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
43 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
44 // check for instances of 0.0/0.0
46 if let ExprKind::Binary(ref op, ref left, ref right) = expr.node;
47 if let BinOpKind::Div = op.node;
48 // TODO - constant_simple does not fold many operations involving floats.
49 // That's probably fine for this lint - it's pretty unlikely that someone would
50 // do something like 0.0/(2.0 - 2.0), but it would be nice to warn on that case too.
51 if let Some(lhs_value) = constant_simple(cx, cx.tables, left);
52 if let Some(rhs_value) = constant_simple(cx, cx.tables, right);
53 if Constant::F32(0.0) == lhs_value || Constant::F64(0.0) == lhs_value;
54 if Constant::F32(0.0) == rhs_value || Constant::F64(0.0) == rhs_value;
56 // since we're about to suggest a use of std::f32::NaN or std::f64::NaN,
57 // match the precision of the literals that are given.
58 let float_type = match (lhs_value, rhs_value) {
60 | (_, Constant::F64(_)) => "f64",
67 "constant division of 0.0 with 0.0 will always result in NaN",
69 "Consider using `std::{}::NAN` if you would like a constant representing NaN",