Skip to content

Commit

Permalink
Don't suggest a.mul_add(b, c) if parameters are not float
Browse files Browse the repository at this point in the history
clippy::suboptimal_flops used to not check if the second parameter to f32/f64.mul_add() was float. Since the method is
only defined to take `Self` as paremters, the suggestion was wrong.

Fixes rust-lang#11831
  • Loading branch information
lukaslueg committed Nov 18, 2023
1 parent e8e9510 commit a2e396b
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 2 deletions.
8 changes: 6 additions & 2 deletions clippy_lints/src/floating_point_arithmetic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -496,9 +496,13 @@ fn check_mul_add(cx: &LateContext<'_>, expr: &Expr<'_>) {
if let BinOpKind::Sub = op { -sugg } else { sugg }
};

let (recv, arg1, arg2) = if let Some((inner_lhs, inner_rhs)) = is_float_mul_expr(cx, lhs) {
let (recv, arg1, arg2) = if let Some((inner_lhs, inner_rhs)) = is_float_mul_expr(cx, lhs)
&& cx.typeck_results().expr_ty(rhs).is_floating_point()
{
(inner_lhs, Sugg::hir(cx, inner_rhs, ".."), maybe_neg_sugg(rhs))
} else if let Some((inner_lhs, inner_rhs)) = is_float_mul_expr(cx, rhs) {
} else if let Some((inner_lhs, inner_rhs)) = is_float_mul_expr(cx, rhs)
&& cx.typeck_results().expr_ty(lhs).is_floating_point()
{
(inner_lhs, maybe_neg_sugg(inner_rhs), Sugg::hir(cx, lhs, ".."))
} else {
return;
Expand Down
18 changes: 18 additions & 0 deletions tests/ui/floating_point_mul_add.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,21 @@ fn main() {
// Cases where the lint shouldn't be applied
let _ = (a * a + b * b).sqrt();
}

fn _issue11831() {
struct NotAFloat;

impl std::ops::Add<f64> for NotAFloat {
type Output = Self;

fn add(self, _: f64) -> Self {
NotAFloat
}
}

let a = NotAFloat;
let b = 1.0_f64;
let c = 1.0;

let _ = a + b * c;
}
18 changes: 18 additions & 0 deletions tests/ui/floating_point_mul_add.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,21 @@ fn main() {
// Cases where the lint shouldn't be applied
let _ = (a * a + b * b).sqrt();
}

fn _issue11831() {
struct NotAFloat;

impl std::ops::Add<f64> for NotAFloat {
type Output = Self;

fn add(self, _: f64) -> Self {
NotAFloat
}
}

let a = NotAFloat;
let b = 1.0_f64;
let c = 1.0;

let _ = a + b * c;
}

0 comments on commit a2e396b

Please sign in to comment.