]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/float_equality_without_abs.rs
Auto merge of #87150 - rusticstuff:simplify_wrapping_neg, r=m-ou-se
[rust.git] / src / tools / clippy / clippy_lints / src / float_equality_without_abs.rs
1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::{match_def_path, paths, sugg};
3 use if_chain::if_chain;
4 use rustc_ast::util::parser::AssocOp;
5 use rustc_errors::Applicability;
6 use rustc_hir::def::{DefKind, Res};
7 use rustc_hir::{BinOpKind, Expr, ExprKind};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_middle::ty;
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 use rustc_span::source_map::Spanned;
12
13 declare_clippy_lint! {
14     /// ### What it does
15     /// Checks for statements of the form `(a - b) < f32::EPSILON` or
16     /// `(a - b) < f64::EPSILON`. Notes the missing `.abs()`.
17     ///
18     /// ### Why is this bad?
19     /// The code without `.abs()` is more likely to have a bug.
20     ///
21     /// ### Known problems
22     /// If the user can ensure that b is larger than a, the `.abs()` is
23     /// technically unneccessary. However, it will make the code more robust and doesn't have any
24     /// large performance implications. If the abs call was deliberately left out for performance
25     /// reasons, it is probably better to state this explicitly in the code, which then can be done
26     /// with an allow.
27     ///
28     /// ### Example
29     /// ```rust
30     /// pub fn is_roughly_equal(a: f32, b: f32) -> bool {
31     ///     (a - b) < f32::EPSILON
32     /// }
33     /// ```
34     /// Use instead:
35     /// ```rust
36     /// pub fn is_roughly_equal(a: f32, b: f32) -> bool {
37     ///     (a - b).abs() < f32::EPSILON
38     /// }
39     /// ```
40     pub FLOAT_EQUALITY_WITHOUT_ABS,
41     suspicious,
42     "float equality check without `.abs()`"
43 }
44
45 declare_lint_pass!(FloatEqualityWithoutAbs => [FLOAT_EQUALITY_WITHOUT_ABS]);
46
47 impl<'tcx> LateLintPass<'tcx> for FloatEqualityWithoutAbs {
48     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
49         let lhs;
50         let rhs;
51
52         // check if expr is a binary expression with a lt or gt operator
53         if let ExprKind::Binary(op, left, right) = expr.kind {
54             match op.node {
55                 BinOpKind::Lt => {
56                     lhs = left;
57                     rhs = right;
58                 },
59                 BinOpKind::Gt => {
60                     lhs = right;
61                     rhs = left;
62                 },
63                 _ => return,
64             };
65         } else {
66             return;
67         }
68
69         if_chain! {
70
71             // left hand side is a substraction
72             if let ExprKind::Binary(
73                 Spanned {
74                     node: BinOpKind::Sub,
75                     ..
76                 },
77                 val_l,
78                 val_r,
79             ) = lhs.kind;
80
81             // right hand side matches either f32::EPSILON or f64::EPSILON
82             if let ExprKind::Path(ref epsilon_path) = rhs.kind;
83             if let Res::Def(DefKind::AssocConst, def_id) = cx.qpath_res(epsilon_path, rhs.hir_id);
84             if match_def_path(cx, def_id, &paths::F32_EPSILON) || match_def_path(cx, def_id, &paths::F64_EPSILON);
85
86             // values of the substractions on the left hand side are of the type float
87             let t_val_l = cx.typeck_results().expr_ty(val_l);
88             let t_val_r = cx.typeck_results().expr_ty(val_r);
89             if let ty::Float(_) = t_val_l.kind();
90             if let ty::Float(_) = t_val_r.kind();
91
92             then {
93                 let sug_l = sugg::Sugg::hir(cx, val_l, "..");
94                 let sug_r = sugg::Sugg::hir(cx, val_r, "..");
95                 // format the suggestion
96                 let suggestion = format!("{}.abs()", sugg::make_assoc(AssocOp::Subtract, &sug_l, &sug_r).maybe_par());
97                 // spans the lint
98                 span_lint_and_then(
99                     cx,
100                     FLOAT_EQUALITY_WITHOUT_ABS,
101                     expr.span,
102                     "float equality check without `.abs()`",
103                     | diag | {
104                         diag.span_suggestion(
105                             lhs.span,
106                             "add `.abs()`",
107                             suggestion,
108                             Applicability::MaybeIncorrect,
109                         );
110                     }
111                 );
112             }
113         }
114     }
115 }