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