Skip to content

Commit 48b6124

Browse files
committed
Lint x.ln() / y.ln() => x.log(y)
1 parent 77ae3ed commit 48b6124

File tree

4 files changed

+54
-0
lines changed

4 files changed

+54
-0
lines changed

clippy_lints/src/floating_point_arithmetic.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -573,6 +573,33 @@ fn check_custom_abs(cx: &LateContext<'_, '_>, expr: &Expr<'_>) {
573573
}
574574
}
575575

576+
fn check_logbase(cx: &LateContext<'_, '_>, expr: &Expr<'_>) {
577+
// check if expression of the form x.logN() / y.logN()
578+
if_chain! {
579+
if let ExprKind::Binary(
580+
Spanned {
581+
node: BinOpKind::Div, ..
582+
},
583+
lhs,
584+
rhs,
585+
) = &expr.kind;
586+
if let ExprKind::MethodCall(PathSegment { ident: lmethod_name, .. }, _, ref largs) = lhs.kind;
587+
if let ExprKind::MethodCall(PathSegment { ident: rmethod_name, .. }, _, ref rargs) = rhs.kind;
588+
if rmethod_name.as_str() == lmethod_name.as_str();
589+
then {
590+
span_lint_and_sugg(
591+
cx,
592+
SUBOPTIMAL_FLOPS,
593+
expr.span,
594+
"division of logarithms can be calculated more efficiently and accurately",
595+
"consider using",
596+
format!("{}.log({})", Sugg::hir(cx, &largs[0], ".."), Sugg::hir(cx, &rargs[0], ".."),),
597+
Applicability::MachineApplicable,
598+
);
599+
}
600+
}
601+
}
602+
576603
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for FloatingPointArithmetic {
577604
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
578605
if let ExprKind::MethodCall(ref path, _, args) = &expr.kind {
@@ -592,6 +619,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for FloatingPointArithmetic {
592619
check_expm1(cx, expr);
593620
check_mul_add(cx, expr);
594621
check_custom_abs(cx, expr);
622+
check_logbase(cx, expr);
595623
}
596624
}
597625
}

tests/ui/floating_point_logbase.fixed

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// run-rustfix
2+
#![warn(clippy::suboptimal_flops)]
3+
4+
fn main() {
5+
let x = 3f32;
6+
let y = 5f32;
7+
let _ = x.log(y);
8+
}

tests/ui/floating_point_logbase.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// run-rustfix
2+
#![warn(clippy::suboptimal_flops)]
3+
4+
fn main() {
5+
let x = 3f32;
6+
let y = 5f32;
7+
let _ = x.ln() / y.ln();
8+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
error: division of logarithms can be calculated more efficiently and accurately
2+
--> $DIR/floating_point_logbase.rs:7:13
3+
|
4+
LL | let _ = x.ln() / y.ln();
5+
| ^^^^^^^^^^^^^^^ help: consider using: `x.log(y)`
6+
|
7+
= note: `-D clippy::suboptimal-flops` implied by `-D warnings`
8+
9+
error: aborting due to previous error
10+

0 commit comments

Comments
 (0)