1 use clippy_utils::consts::{
2 constant, constant_simple, Constant,
3 Constant::{Int, F32, F64},
5 use clippy_utils::diagnostics::span_lint_and_sugg;
6 use clippy_utils::{eq_expr_value, get_parent_expr, numeric_literal, sugg};
7 use if_chain::if_chain;
8 use rustc_errors::Applicability;
9 use rustc_hir::{BinOpKind, Expr, ExprKind, PathSegment, UnOp};
10 use rustc_lint::{LateContext, LateLintPass};
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 use rustc_span::source_map::Spanned;
16 use std::f32::consts as f32_consts;
17 use std::f64::consts as f64_consts;
20 declare_clippy_lint! {
22 /// Looks for floating-point expressions that
23 /// can be expressed using built-in methods to improve accuracy
24 /// at the cost of performance.
26 /// ### Why is this bad?
27 /// Negatively impacts accuracy.
32 /// let _ = a.powf(1.0 / 3.0);
33 /// let _ = (1.0 + a).ln();
34 /// let _ = a.exp() - 1.0;
37 /// is better expressed as
42 /// let _ = a.ln_1p();
43 /// let _ = a.exp_m1();
47 "usage of imprecise floating point operations"
50 declare_clippy_lint! {
52 /// Looks for floating-point expressions that
53 /// can be expressed using built-in methods to improve both
54 /// accuracy and performance.
56 /// ### Why is this bad?
57 /// Negatively impacts accuracy and performance.
61 /// use std::f32::consts::E;
64 /// let _ = (2f32).powf(a);
65 /// let _ = E.powf(a);
66 /// let _ = a.powf(1.0 / 2.0);
67 /// let _ = a.log(2.0);
68 /// let _ = a.log(10.0);
70 /// let _ = a.powf(2.0);
71 /// let _ = a * 2.0 + 4.0;
72 /// let _ = if a < 0.0 {
77 /// let _ = if a < 0.0 {
84 /// is better expressed as
87 /// use std::f32::consts::E;
94 /// let _ = a.log10();
96 /// let _ = a.powi(2);
97 /// let _ = a.mul_add(2.0, 4.0);
101 pub SUBOPTIMAL_FLOPS,
103 "usage of sub-optimal floating point operations"
106 declare_lint_pass!(FloatingPointArithmetic => [
111 // Returns the specialized log method for a given base if base is constant
112 // and is one of 2, 10 and e
113 fn get_specialized_log_method(cx: &LateContext<'_>, base: &Expr<'_>) -> Option<&'static str> {
114 if let Some((value, _)) = constant(cx, cx.typeck_results(), base) {
115 if F32(2.0) == value || F64(2.0) == value {
117 } else if F32(10.0) == value || F64(10.0) == value {
118 return Some("log10");
119 } else if F32(f32_consts::E) == value || F64(f64_consts::E) == value {
127 // Adds type suffixes and parenthesis to method receivers if necessary
128 fn prepare_receiver_sugg<'a>(cx: &LateContext<'_>, mut expr: &'a Expr<'a>) -> Sugg<'a> {
129 let mut suggestion = Sugg::hir(cx, expr, "..");
131 if let ExprKind::Unary(UnOp::Neg, inner_expr) = &expr.kind {
136 // if the expression is a float literal and it is unsuffixed then
137 // add a suffix so the suggestion is valid and unambiguous
138 if let ty::Float(float_ty) = cx.typeck_results().expr_ty(expr).kind();
139 if let ExprKind::Lit(lit) = &expr.kind;
140 if let ast::LitKind::Float(sym, ast::LitFloatType::Unsuffixed) = lit.node;
145 // Check for float literals without numbers following the decimal
146 // separator such as `2.` and adds a trailing zero
147 if sym.as_str().ends_with('.') {
155 suggestion = match suggestion {
156 Sugg::MaybeParen(_) => Sugg::MaybeParen(op),
157 _ => Sugg::NonParen(op)
162 suggestion.maybe_par()
165 fn check_log_base(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) {
166 if let Some(method) = get_specialized_log_method(cx, &args[1]) {
171 "logarithm for bases 2, 10 and e can be computed more accurately",
173 format!("{}.{}()", Sugg::hir(cx, &args[0], ".."), method),
174 Applicability::MachineApplicable,
179 // TODO: Lint expressions of the form `(x + y).ln()` where y > 1 and
180 // suggest usage of `(x + (y - 1)).ln_1p()` instead
181 fn check_ln1p(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) {
182 if let ExprKind::Binary(
184 node: BinOpKind::Add, ..
191 constant(cx, cx.typeck_results(), lhs),
192 constant(cx, cx.typeck_results(), rhs),
194 (Some((value, _)), _) if F32(1.0) == value || F64(1.0) == value => rhs,
195 (_, Some((value, _))) if F32(1.0) == value || F64(1.0) == value => lhs,
203 "ln(1 + x) can be computed more accurately",
205 format!("{}.ln_1p()", prepare_receiver_sugg(cx, recv)),
206 Applicability::MachineApplicable,
211 // Returns an integer if the float constant is a whole number and it can be
212 // converted to an integer without loss of precision. For now we only check
213 // ranges [-16777215, 16777216) for type f32 as whole number floats outside
214 // this range are lossy and ambiguous.
215 #[allow(clippy::cast_possible_truncation)]
216 fn get_integer_from_float_constant(value: &Constant) -> Option<i32> {
218 F32(num) if num.fract() == 0.0 => {
219 if (-16_777_215.0..16_777_216.0).contains(num) {
220 Some(num.round() as i32)
225 F64(num) if num.fract() == 0.0 => {
226 if (-2_147_483_648.0..2_147_483_648.0).contains(num) {
227 Some(num.round() as i32)
236 fn check_powf(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) {
238 if let Some((value, _)) = constant(cx, cx.typeck_results(), &args[0]) {
239 let method = if F32(f32_consts::E) == value || F64(f64_consts::E) == value {
241 } else if F32(2.0) == value || F64(2.0) == value {
251 "exponent for bases 2 and e can be computed more accurately",
253 format!("{}.{}()", prepare_receiver_sugg(cx, &args[1]), method),
254 Applicability::MachineApplicable,
259 if let Some((value, _)) = constant(cx, cx.typeck_results(), &args[1]) {
260 let (lint, help, suggestion) = if F32(1.0 / 2.0) == value || F64(1.0 / 2.0) == value {
263 "square-root of a number can be computed more efficiently and accurately",
264 format!("{}.sqrt()", Sugg::hir(cx, &args[0], "..")),
266 } else if F32(1.0 / 3.0) == value || F64(1.0 / 3.0) == value {
269 "cube-root of a number can be computed more accurately",
270 format!("{}.cbrt()", Sugg::hir(cx, &args[0], "..")),
272 } else if let Some(exponent) = get_integer_from_float_constant(&value) {
275 "exponentiation with integer powers can be computed more efficiently",
278 Sugg::hir(cx, &args[0], ".."),
279 numeric_literal::format(&exponent.to_string(), None, false)
293 Applicability::MachineApplicable,
298 fn check_powi(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) {
299 if let Some((value, _)) = constant(cx, cx.typeck_results(), &args[1]) {
301 if let Some(parent) = get_parent_expr(cx, expr) {
302 if let Some(grandparent) = get_parent_expr(cx, parent) {
303 if let ExprKind::MethodCall(PathSegment { ident: method_name, .. }, _, args, _) = grandparent.kind {
304 if method_name.as_str() == "sqrt" && detect_hypot(cx, args).is_some() {
310 if let ExprKind::Binary(
312 node: BinOpKind::Add, ..
318 let other_addend = if lhs.hir_id == expr.hir_id { rhs } else { lhs };
324 "multiply and add expressions can be calculated more efficiently and accurately",
327 "{}.mul_add({}, {})",
328 Sugg::hir(cx, &args[0], ".."),
329 Sugg::hir(cx, &args[0], ".."),
330 Sugg::hir(cx, other_addend, ".."),
332 Applicability::MachineApplicable,
342 fn detect_hypot(cx: &LateContext<'_>, args: &[Expr<'_>]) -> Option<String> {
343 if let ExprKind::Binary(
345 node: BinOpKind::Add, ..
351 // check if expression of the form x * x + y * y
353 if let ExprKind::Binary(Spanned { node: BinOpKind::Mul, .. }, lmul_lhs, lmul_rhs) = add_lhs.kind;
354 if let ExprKind::Binary(Spanned { node: BinOpKind::Mul, .. }, rmul_lhs, rmul_rhs) = add_rhs.kind;
355 if eq_expr_value(cx, lmul_lhs, lmul_rhs);
356 if eq_expr_value(cx, rmul_lhs, rmul_rhs);
358 return Some(format!("{}.hypot({})", Sugg::hir(cx, lmul_lhs, ".."), Sugg::hir(cx, rmul_lhs, "..")));
362 // check if expression of the form x.powi(2) + y.powi(2)
364 if let ExprKind::MethodCall(
365 PathSegment { ident: lmethod_name, .. },
370 if let ExprKind::MethodCall(
371 PathSegment { ident: rmethod_name, .. },
376 if lmethod_name.as_str() == "powi" && rmethod_name.as_str() == "powi";
377 if let Some((lvalue, _)) = constant(cx, cx.typeck_results(), &largs[1]);
378 if let Some((rvalue, _)) = constant(cx, cx.typeck_results(), &rargs[1]);
379 if Int(2) == lvalue && Int(2) == rvalue;
381 return Some(format!("{}.hypot({})", Sugg::hir(cx, &largs[0], ".."), Sugg::hir(cx, &rargs[0], "..")));
389 fn check_hypot(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) {
390 if let Some(message) = detect_hypot(cx, args) {
395 "hypotenuse can be computed more accurately",
398 Applicability::MachineApplicable,
403 // TODO: Lint expressions of the form `x.exp() - y` where y > 1
404 // and suggest usage of `x.exp_m1() - (y - 1)` instead
405 fn check_expm1(cx: &LateContext<'_>, expr: &Expr<'_>) {
407 if let ExprKind::Binary(Spanned { node: BinOpKind::Sub, .. }, lhs, rhs) = expr.kind;
408 if cx.typeck_results().expr_ty(lhs).is_floating_point();
409 if let Some((value, _)) = constant(cx, cx.typeck_results(), rhs);
410 if F32(1.0) == value || F64(1.0) == value;
411 if let ExprKind::MethodCall(path, _, method_args, _) = lhs.kind;
412 if cx.typeck_results().expr_ty(&method_args[0]).is_floating_point();
413 if path.ident.name.as_str() == "exp";
419 "(e.pow(x) - 1) can be computed more accurately",
423 Sugg::hir(cx, &method_args[0], "..")
425 Applicability::MachineApplicable,
431 fn is_float_mul_expr<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<(&'a Expr<'a>, &'a Expr<'a>)> {
433 if let ExprKind::Binary(Spanned { node: BinOpKind::Mul, .. }, lhs, rhs) = &expr.kind;
434 if cx.typeck_results().expr_ty(lhs).is_floating_point();
435 if cx.typeck_results().expr_ty(rhs).is_floating_point();
437 return Some((lhs, rhs));
444 // TODO: Fix rust-lang/rust-clippy#4735
445 fn check_mul_add(cx: &LateContext<'_>, expr: &Expr<'_>) {
446 if let ExprKind::Binary(
448 node: BinOpKind::Add, ..
454 if let Some(parent) = get_parent_expr(cx, expr) {
455 if let ExprKind::MethodCall(PathSegment { ident: method_name, .. }, _, args, _) = parent.kind {
456 if method_name.as_str() == "sqrt" && detect_hypot(cx, args).is_some() {
462 let (recv, arg1, arg2) = if let Some((inner_lhs, inner_rhs)) = is_float_mul_expr(cx, lhs) {
463 (inner_lhs, inner_rhs, rhs)
464 } else if let Some((inner_lhs, inner_rhs)) = is_float_mul_expr(cx, rhs) {
465 (inner_lhs, inner_rhs, lhs)
474 "multiply and add expressions can be calculated more efficiently and accurately",
477 "{}.mul_add({}, {})",
478 prepare_receiver_sugg(cx, recv),
479 Sugg::hir(cx, arg1, ".."),
480 Sugg::hir(cx, arg2, ".."),
482 Applicability::MachineApplicable,
487 /// Returns true iff expr is an expression which tests whether or not
488 /// test is positive or an expression which tests whether or not test
490 /// Used for check-custom-abs function below
491 fn is_testing_positive(cx: &LateContext<'_>, expr: &Expr<'_>, test: &Expr<'_>) -> bool {
492 if let ExprKind::Binary(Spanned { node: op, .. }, left, right) = expr.kind {
494 BinOpKind::Gt | BinOpKind::Ge => is_zero(cx, right) && eq_expr_value(cx, left, test),
495 BinOpKind::Lt | BinOpKind::Le => is_zero(cx, left) && eq_expr_value(cx, right, test),
503 /// See [`is_testing_positive`]
504 fn is_testing_negative(cx: &LateContext<'_>, expr: &Expr<'_>, test: &Expr<'_>) -> bool {
505 if let ExprKind::Binary(Spanned { node: op, .. }, left, right) = expr.kind {
507 BinOpKind::Gt | BinOpKind::Ge => is_zero(cx, left) && eq_expr_value(cx, right, test),
508 BinOpKind::Lt | BinOpKind::Le => is_zero(cx, right) && eq_expr_value(cx, left, test),
516 /// Returns true iff expr is some zero literal
517 fn is_zero(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
518 match constant_simple(cx, cx.typeck_results(), expr) {
519 Some(Constant::Int(i)) => i == 0,
520 Some(Constant::F32(f)) => f == 0.0,
521 Some(Constant::F64(f)) => f == 0.0,
526 /// If the two expressions are negations of each other, then it returns
527 /// a tuple, in which the first element is true iff expr1 is the
528 /// positive expressions, and the second element is the positive
529 /// one of the two expressions
530 /// If the two expressions are not negations of each other, then it
532 fn are_negated<'a>(cx: &LateContext<'_>, expr1: &'a Expr<'a>, expr2: &'a Expr<'a>) -> Option<(bool, &'a Expr<'a>)> {
533 if let ExprKind::Unary(UnOp::Neg, expr1_negated) = &expr1.kind {
534 if eq_expr_value(cx, expr1_negated, expr2) {
535 return Some((false, expr2));
538 if let ExprKind::Unary(UnOp::Neg, expr2_negated) = &expr2.kind {
539 if eq_expr_value(cx, expr1, expr2_negated) {
540 return Some((true, expr1));
546 fn check_custom_abs(cx: &LateContext<'_>, expr: &Expr<'_>) {
548 if let ExprKind::If(cond, body, else_body) = expr.kind;
549 if let ExprKind::Block(block, _) = body.kind;
550 if block.stmts.is_empty();
551 if let Some(if_body_expr) = block.expr;
552 if let Some(ExprKind::Block(else_block, _)) = else_body.map(|el| &el.kind);
553 if else_block.stmts.is_empty();
554 if let Some(else_body_expr) = else_block.expr;
555 if let Some((if_expr_positive, body)) = are_negated(cx, if_body_expr, else_body_expr);
557 let positive_abs_sugg = (
558 "manual implementation of `abs` method",
559 format!("{}.abs()", Sugg::hir(cx, body, "..")),
561 let negative_abs_sugg = (
562 "manual implementation of negation of `abs` method",
563 format!("-{}.abs()", Sugg::hir(cx, body, "..")),
565 let sugg = if is_testing_positive(cx, cond, body) {
566 if if_expr_positive {
571 } else if is_testing_negative(cx, cond, body) {
572 if if_expr_positive {
587 Applicability::MachineApplicable,
593 fn are_same_base_logs(cx: &LateContext<'_>, expr_a: &Expr<'_>, expr_b: &Expr<'_>) -> bool {
595 if let ExprKind::MethodCall(PathSegment { ident: method_name_a, .. }, _, args_a, _) = expr_a.kind;
596 if let ExprKind::MethodCall(PathSegment { ident: method_name_b, .. }, _, args_b, _) = expr_b.kind;
598 return method_name_a.as_str() == method_name_b.as_str() &&
599 args_a.len() == args_b.len() &&
601 ["ln", "log2", "log10"].contains(&&*method_name_a.as_str()) ||
602 method_name_a.as_str() == "log" && args_a.len() == 2 && eq_expr_value(cx, &args_a[1], &args_b[1])
610 fn check_log_division(cx: &LateContext<'_>, expr: &Expr<'_>) {
611 // check if expression of the form x.logN() / y.logN()
613 if let ExprKind::Binary(
615 node: BinOpKind::Div, ..
620 if are_same_base_logs(cx, lhs, rhs);
621 if let ExprKind::MethodCall(_, _, largs, _) = lhs.kind;
622 if let ExprKind::MethodCall(_, _, rargs, _) = rhs.kind;
628 "log base can be expressed more clearly",
630 format!("{}.log({})", Sugg::hir(cx, &largs[0], ".."), Sugg::hir(cx, &rargs[0], ".."),),
631 Applicability::MachineApplicable,
637 fn check_radians(cx: &LateContext<'_>, expr: &Expr<'_>) {
639 if let ExprKind::Binary(
641 node: BinOpKind::Div, ..
646 if let ExprKind::Binary(
648 node: BinOpKind::Mul, ..
653 if let Some((rvalue, _)) = constant(cx, cx.typeck_results(), div_rhs);
654 if let Some((lvalue, _)) = constant(cx, cx.typeck_results(), mul_rhs);
656 // TODO: also check for constant values near PI/180 or 180/PI
657 if (F32(f32_consts::PI) == rvalue || F64(f64_consts::PI) == rvalue) &&
658 (F32(180_f32) == lvalue || F64(180_f64) == lvalue)
664 "conversion to degrees can be done more accurately",
666 format!("{}.to_degrees()", Sugg::hir(cx, mul_lhs, "..")),
667 Applicability::MachineApplicable,
670 (F32(180_f32) == rvalue || F64(180_f64) == rvalue) &&
671 (F32(f32_consts::PI) == lvalue || F64(f64_consts::PI) == lvalue)
677 "conversion to radians can be done more accurately",
679 format!("{}.to_radians()", Sugg::hir(cx, mul_lhs, "..")),
680 Applicability::MachineApplicable,
687 impl<'tcx> LateLintPass<'tcx> for FloatingPointArithmetic {
688 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
689 if let ExprKind::MethodCall(path, _, args, _) = &expr.kind {
690 let recv_ty = cx.typeck_results().expr_ty(&args[0]);
692 if recv_ty.is_floating_point() {
693 match &*path.ident.name.as_str() {
694 "ln" => check_ln1p(cx, expr, args),
695 "log" => check_log_base(cx, expr, args),
696 "powf" => check_powf(cx, expr, args),
697 "powi" => check_powi(cx, expr, args),
698 "sqrt" => check_hypot(cx, expr, args),
703 check_expm1(cx, expr);
704 check_mul_add(cx, expr);
705 check_custom_abs(cx, expr);
706 check_log_division(cx, expr);
707 check_radians(cx, expr);