Skip to content

Commit 2be203f

Browse files
committed
Lint x.ln() / y.ln() => x.log(y)
1 parent 149c3ea commit 2be203f

File tree

4 files changed

+54
-0
lines changed

4 files changed

+54
-0
lines changed

clippy_lints/src/floating_point_arithmetic.rs

+28
Original file line numberDiff line numberDiff line change
@@ -575,6 +575,33 @@ fn check_custom_abs(cx: &LateContext<'_, '_>, expr: &Expr<'_>) {
575575
}
576576
}
577577

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

tests/ui/floating_point_logbase.fixed

+8
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

+8
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+
}
+10
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)