]> git.lizzy.rs Git - rust.git/blobdiff - clippy_lints/src/float_equality_without_abs.rs
modify code
[rust.git] / clippy_lints / src / float_equality_without_abs.rs
index dc1c3bfc9ff3cb5e183108964af2de6fd2f4989b..ca8886228de264a042c24c89e2f9688d4c15bb9f 100644 (file)
@@ -1,6 +1,9 @@
-use crate::utils::{match_qpath, paths, snippet, span_lint_and_sugg};
+use clippy_utils::diagnostics::span_lint_and_then;
+use clippy_utils::{match_def_path, paths, sugg};
 use if_chain::if_chain;
+use rustc_ast::util::parser::AssocOp;
 use rustc_errors::Applicability;
+use rustc_hir::def::{DefKind, Res};
 use rustc_hir::{BinOpKind, Expr, ExprKind};
 use rustc_lint::{LateContext, LateLintPass};
 use rustc_middle::ty;
 use rustc_span::source_map::Spanned;
 
 declare_clippy_lint! {
-    /// **What it does:** Checks for statements of the form `(a - b) < f32::EPSILON` or
-     /// `(a - b) < f64::EPSILON`. Notes the missing `.abs()`.
-     ///
-     /// **Why is this bad?** The code without `.abs()` is more likely to have a bug.
-     ///
-     /// **Known problems:** If the user can ensure that b is larger than a, the `.abs()` is
-     /// technically unneccessary. However, it will make the code more robust and doesn't have any
-     /// large performance implications. If the abs call was deliberately left out for performance
-     /// reasons, it is probably better to state this explicitly in the code, which then can be done
-     /// with an allow.
-     ///
-     /// **Example:**
-     ///
-     /// ```rust
-     /// pub fn is_roughly_equal(a: f32, b: f32) -> bool {
-     ///     (a - b) < f32::EPSILON
-     /// }
-     /// ```
-     /// Use instead:
-     /// ```rust
-     /// pub fn is_roughly_equal(a: f32, b: f32) -> bool {
-     ///     (a - b).abs() < f32::EPSILON
-     /// }
-     /// ```
+    /// ### What it does
+    /// Checks for statements of the form `(a - b) < f32::EPSILON` or
+    /// `(a - b) < f64::EPSILON`. Notes the missing `.abs()`.
+    ///
+    /// ### Why is this bad?
+    /// The code without `.abs()` is more likely to have a bug.
+    ///
+    /// ### Known problems
+    /// If the user can ensure that b is larger than a, the `.abs()` is
+    /// technically unneccessary. However, it will make the code more robust and doesn't have any
+    /// large performance implications. If the abs call was deliberately left out for performance
+    /// reasons, it is probably better to state this explicitly in the code, which then can be done
+    /// with an allow.
+    ///
+    /// ### Example
+    /// ```rust
+    /// pub fn is_roughly_equal(a: f32, b: f32) -> bool {
+    ///     (a - b) < f32::EPSILON
+    /// }
+    /// ```
+    /// Use instead:
+    /// ```rust
+    /// pub fn is_roughly_equal(a: f32, b: f32) -> bool {
+    ///     (a - b).abs() < f32::EPSILON
+    /// }
+    /// ```
+    #[clippy::version = "1.48.0"]
     pub FLOAT_EQUALITY_WITHOUT_ABS,
-    correctness,
+    suspicious,
     "float equality check without `.abs()`"
 }
 
@@ -45,7 +51,7 @@ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
         let rhs;
 
         // check if expr is a binary expression with a lt or gt operator
-        if let ExprKind::Binary(op, ref left, ref right) = expr.kind {
+        if let ExprKind::Binary(op, left, right) = expr.kind {
             match op.node {
                 BinOpKind::Lt => {
                     lhs = left;
@@ -75,36 +81,34 @@ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
 
             // right hand side matches either f32::EPSILON or f64::EPSILON
             if let ExprKind::Path(ref epsilon_path) = rhs.kind;
-            if match_qpath(epsilon_path, &paths::F32_EPSILON) || match_qpath(epsilon_path, &paths::F64_EPSILON);
+            if let Res::Def(DefKind::AssocConst, def_id) = cx.qpath_res(epsilon_path, rhs.hir_id);
+            if match_def_path(cx, def_id, &paths::F32_EPSILON) || match_def_path(cx, def_id, &paths::F64_EPSILON);
 
             // values of the substractions on the left hand side are of the type float
             let t_val_l = cx.typeck_results().expr_ty(val_l);
             let t_val_r = cx.typeck_results().expr_ty(val_r);
-            if let ty::Float(_) = t_val_l.kind;
-            if let ty::Float(_) = t_val_r.kind;
+            if let ty::Float(_) = t_val_l.kind();
+            if let ty::Float(_) = t_val_r.kind();
 
             then {
-                // get the snippet string
-                let lhs_string = snippet(
-                    cx,
-                    lhs.span,
-                    "(...)",
-                );
+                let sug_l = sugg::Sugg::hir(cx, val_l, "..");
+                let sug_r = sugg::Sugg::hir(cx, val_r, "..");
                 // format the suggestion
-                let suggestion = if lhs_string.starts_with('(') {
-                    format!("{}.abs()", lhs_string)
-                } else {
-                    format!("({}).abs()", lhs_string)
-                };
+                let suggestion = format!("{}.abs()", sugg::make_assoc(AssocOp::Subtract, &sug_l, &sug_r).maybe_par());
                 // spans the lint
-                span_lint_and_sugg(
+                span_lint_and_then(
                     cx,
                     FLOAT_EQUALITY_WITHOUT_ABS,
                     expr.span,
                     "float equality check without `.abs()`",
-                    "add `.abs()`",
-                    suggestion,
-                    Applicability::MaybeIncorrect,
+                    | diag | {
+                        diag.span_suggestion(
+                            lhs.span,
+                            "add `.abs()`",
+                            suggestion,
+                            Applicability::MaybeIncorrect,
+                        );
+                    }
                 );
             }
         }