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};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::source_map::Spanned;
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()`.
15 /// **Why is this bad?** The code without `.abs()` is more likely to have a bug.
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
26 /// pub fn is_roughly_equal(a: f32, b: f32) -> bool {
27 /// (a - b) < f32::EPSILON
32 /// pub fn is_roughly_equal(a: f32, b: f32) -> bool {
33 /// (a - b).abs() < f32::EPSILON
36 pub FLOAT_EQUALITY_WITHOUT_ABS,
38 "float equality check without `.abs()`"
41 declare_lint_pass!(FloatEqualityWithoutAbs => [FLOAT_EQUALITY_WITHOUT_ABS]);
43 impl<'tcx> LateLintPass<'tcx> for FloatEqualityWithoutAbs {
44 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
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 {
67 // left hand side is a substraction
68 if let ExprKind::Binary(
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);
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();
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());
95 FLOAT_EQUALITY_WITHOUT_ABS,
97 "float equality check without `.abs()`",
103 Applicability::MaybeIncorrect,