2 constant, constant_simple, Constant,
3 Constant::{Int, F32, F64},
5 use crate::utils::{get_parent_expr, higher, numeric_literal, span_lint_and_sugg, sugg, SpanlessEq};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir::{BinOpKind, Expr, ExprKind, PathSegment, UnOp};
9 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 use rustc_span::source_map::Spanned;
15 use std::f32::consts as f32_consts;
16 use std::f64::consts as f64_consts;
19 declare_clippy_lint! {
20 /// **What it does:** Looks for floating-point expressions that
21 /// can be expressed using built-in methods to improve accuracy
22 /// at the cost of performance.
24 /// **Why is this bad?** Negatively impacts accuracy.
26 /// **Known problems:** None
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! {
51 /// **What it does:** Looks for floating-point expressions that
52 /// can be expressed using built-in methods to improve both
53 /// accuracy and performance.
55 /// **Why is this bad?** Negatively impacts accuracy and performance.
57 /// **Known problems:** None
62 /// use std::f32::consts::E;
65 /// let _ = (2f32).powf(a);
66 /// let _ = E.powf(a);
67 /// let _ = a.powf(1.0 / 2.0);
68 /// let _ = a.log(2.0);
69 /// let _ = a.log(10.0);
71 /// let _ = a.powf(2.0);
72 /// let _ = a * 2.0 + 4.0;
73 /// let _ = if a < 0.0 {
78 /// let _ = if a < 0.0 {
85 /// is better expressed as
88 /// use std::f32::consts::E;
95 /// let _ = a.log10();
97 /// let _ = a.powi(2);
98 /// let _ = a.mul_add(2.0, 4.0);
100 /// let _ = -a.abs();
102 pub SUBOPTIMAL_FLOPS,
104 "usage of sub-optimal floating point operations"
107 declare_lint_pass!(FloatingPointArithmetic => [
112 // Returns the specialized log method for a given base if base is constant
113 // and is one of 2, 10 and e
114 fn get_specialized_log_method(cx: &LateContext<'_>, base: &Expr<'_>) -> Option<&'static str> {
115 if let Some((value, _)) = constant(cx, cx.tables(), base) {
116 if F32(2.0) == value || F64(2.0) == value {
118 } else if F32(10.0) == value || F64(10.0) == value {
119 return Some("log10");
120 } else if F32(f32_consts::E) == value || F64(f64_consts::E) == value {
128 // Adds type suffixes and parenthesis to method receivers if necessary
129 fn prepare_receiver_sugg<'a>(cx: &LateContext<'_>, mut expr: &'a Expr<'a>) -> Sugg<'a> {
130 let mut suggestion = Sugg::hir(cx, expr, "..");
132 if let ExprKind::Unary(UnOp::UnNeg, inner_expr) = &expr.kind {
137 // if the expression is a float literal and it is unsuffixed then
138 // add a suffix so the suggestion is valid and unambiguous
139 if let ty::Float(float_ty) = cx.tables().expr_ty(expr).kind;
140 if let ExprKind::Lit(lit) = &expr.kind;
141 if let ast::LitKind::Float(sym, ast::LitFloatType::Unsuffixed) = lit.node;
146 // Check for float literals without numbers following the decimal
147 // separator such as `2.` and adds a trailing zero
148 if sym.as_str().ends_with('.') {
156 suggestion = match suggestion {
157 Sugg::MaybeParen(_) => Sugg::MaybeParen(op),
158 _ => Sugg::NonParen(op)
163 suggestion.maybe_par()
166 fn check_log_base(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) {
167 if let Some(method) = get_specialized_log_method(cx, &args[1]) {
172 "logarithm for bases 2, 10 and e can be computed more accurately",
174 format!("{}.{}()", Sugg::hir(cx, &args[0], ".."), method),
175 Applicability::MachineApplicable,
180 // TODO: Lint expressions of the form `(x + y).ln()` where y > 1 and
181 // suggest usage of `(x + (y - 1)).ln_1p()` instead
182 fn check_ln1p(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) {
183 if let ExprKind::Binary(
185 node: BinOpKind::Add, ..
191 let recv = match (constant(cx, cx.tables(), lhs), constant(cx, cx.tables(), rhs)) {
192 (Some((value, _)), _) if F32(1.0) == value || F64(1.0) == value => rhs,
193 (_, Some((value, _))) if F32(1.0) == value || F64(1.0) == value => lhs,
201 "ln(1 + x) can be computed more accurately",
203 format!("{}.ln_1p()", prepare_receiver_sugg(cx, recv)),
204 Applicability::MachineApplicable,
209 // Returns an integer if the float constant is a whole number and it can be
210 // converted to an integer without loss of precision. For now we only check
211 // ranges [-16777215, 16777216) for type f32 as whole number floats outside
212 // this range are lossy and ambiguous.
213 #[allow(clippy::cast_possible_truncation)]
214 fn get_integer_from_float_constant(value: &Constant) -> Option<i32> {
216 F32(num) if num.fract() == 0.0 => {
217 if (-16_777_215.0..16_777_216.0).contains(num) {
218 Some(num.round() as i32)
223 F64(num) if num.fract() == 0.0 => {
224 if (-2_147_483_648.0..2_147_483_648.0).contains(num) {
225 Some(num.round() as i32)
234 fn check_powf(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) {
236 if let Some((value, _)) = constant(cx, cx.tables(), &args[0]) {
237 let method = if F32(f32_consts::E) == value || F64(f64_consts::E) == value {
239 } else if F32(2.0) == value || F64(2.0) == value {
249 "exponent for bases 2 and e can be computed more accurately",
251 format!("{}.{}()", prepare_receiver_sugg(cx, &args[1]), method),
252 Applicability::MachineApplicable,
257 if let Some((value, _)) = constant(cx, cx.tables(), &args[1]) {
258 let (lint, help, suggestion) = if F32(1.0 / 2.0) == value || F64(1.0 / 2.0) == value {
261 "square-root of a number can be computed more efficiently and accurately",
262 format!("{}.sqrt()", Sugg::hir(cx, &args[0], "..")),
264 } else if F32(1.0 / 3.0) == value || F64(1.0 / 3.0) == value {
267 "cube-root of a number can be computed more accurately",
268 format!("{}.cbrt()", Sugg::hir(cx, &args[0], "..")),
270 } else if let Some(exponent) = get_integer_from_float_constant(&value) {
273 "exponentiation with integer powers can be computed more efficiently",
276 Sugg::hir(cx, &args[0], ".."),
277 numeric_literal::format(&exponent.to_string(), None, false)
291 Applicability::MachineApplicable,
296 fn check_powi(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) {
297 if let Some((value, _)) = constant(cx, cx.tables(), &args[1]) {
299 if let Some(parent) = get_parent_expr(cx, expr) {
300 if let Some(grandparent) = get_parent_expr(cx, parent) {
301 if let ExprKind::MethodCall(PathSegment { ident: method_name, .. }, _, args, _) = grandparent.kind {
302 if method_name.as_str() == "sqrt" && detect_hypot(cx, args).is_some() {
308 if let ExprKind::Binary(
310 node: BinOpKind::Add, ..
316 let other_addend = if lhs.hir_id == expr.hir_id { rhs } else { lhs };
322 "square can be computed more efficiently",
325 "{}.mul_add({}, {})",
326 Sugg::hir(cx, &args[0], ".."),
327 Sugg::hir(cx, &args[0], ".."),
328 Sugg::hir(cx, &other_addend, ".."),
330 Applicability::MachineApplicable,
341 "square can be computed more efficiently",
343 format!("{} * {}", Sugg::hir(cx, &args[0], ".."), Sugg::hir(cx, &args[0], "..")),
344 Applicability::MachineApplicable,
350 fn detect_hypot(cx: &LateContext<'_>, args: &[Expr<'_>]) -> Option<String> {
351 if let ExprKind::Binary(
353 node: BinOpKind::Add, ..
359 // check if expression of the form x * x + y * y
361 if let ExprKind::Binary(Spanned { node: BinOpKind::Mul, .. }, ref lmul_lhs, ref lmul_rhs) = add_lhs.kind;
362 if let ExprKind::Binary(Spanned { node: BinOpKind::Mul, .. }, ref rmul_lhs, ref rmul_rhs) = add_rhs.kind;
363 if are_exprs_equal(cx, lmul_lhs, lmul_rhs);
364 if are_exprs_equal(cx, rmul_lhs, rmul_rhs);
366 return Some(format!("{}.hypot({})", Sugg::hir(cx, &lmul_lhs, ".."), Sugg::hir(cx, &rmul_lhs, "..")));
370 // check if expression of the form x.powi(2) + y.powi(2)
372 if let ExprKind::MethodCall(
373 PathSegment { ident: lmethod_name, .. },
378 if let ExprKind::MethodCall(
379 PathSegment { ident: rmethod_name, .. },
384 if lmethod_name.as_str() == "powi" && rmethod_name.as_str() == "powi";
385 if let Some((lvalue, _)) = constant(cx, cx.tables(), &largs[1]);
386 if let Some((rvalue, _)) = constant(cx, cx.tables(), &rargs[1]);
387 if Int(2) == lvalue && Int(2) == rvalue;
389 return Some(format!("{}.hypot({})", Sugg::hir(cx, &largs[0], ".."), Sugg::hir(cx, &rargs[0], "..")));
397 fn check_hypot(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) {
398 if let Some(message) = detect_hypot(cx, args) {
403 "hypotenuse can be computed more accurately",
406 Applicability::MachineApplicable,
411 // TODO: Lint expressions of the form `x.exp() - y` where y > 1
412 // and suggest usage of `x.exp_m1() - (y - 1)` instead
413 fn check_expm1(cx: &LateContext<'_>, expr: &Expr<'_>) {
415 if let ExprKind::Binary(Spanned { node: BinOpKind::Sub, .. }, ref lhs, ref rhs) = expr.kind;
416 if cx.tables().expr_ty(lhs).is_floating_point();
417 if let Some((value, _)) = constant(cx, cx.tables(), rhs);
418 if F32(1.0) == value || F64(1.0) == value;
419 if let ExprKind::MethodCall(ref path, _, ref method_args, _) = lhs.kind;
420 if cx.tables().expr_ty(&method_args[0]).is_floating_point();
421 if path.ident.name.as_str() == "exp";
427 "(e.pow(x) - 1) can be computed more accurately",
431 Sugg::hir(cx, &method_args[0], "..")
433 Applicability::MachineApplicable,
439 fn is_float_mul_expr<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<(&'a Expr<'a>, &'a Expr<'a>)> {
441 if let ExprKind::Binary(Spanned { node: BinOpKind::Mul, .. }, ref lhs, ref rhs) = &expr.kind;
442 if cx.tables().expr_ty(lhs).is_floating_point();
443 if cx.tables().expr_ty(rhs).is_floating_point();
445 return Some((lhs, rhs));
452 // TODO: Fix rust-lang/rust-clippy#4735
453 fn check_mul_add(cx: &LateContext<'_>, expr: &Expr<'_>) {
454 if let ExprKind::Binary(
456 node: BinOpKind::Add, ..
462 if let Some(parent) = get_parent_expr(cx, expr) {
463 if let ExprKind::MethodCall(PathSegment { ident: method_name, .. }, _, args, _) = parent.kind {
464 if method_name.as_str() == "sqrt" && detect_hypot(cx, args).is_some() {
470 let (recv, arg1, arg2) = if let Some((inner_lhs, inner_rhs)) = is_float_mul_expr(cx, lhs) {
471 (inner_lhs, inner_rhs, rhs)
472 } else if let Some((inner_lhs, inner_rhs)) = is_float_mul_expr(cx, rhs) {
473 (inner_lhs, inner_rhs, lhs)
482 "multiply and add expressions can be calculated more efficiently and accurately",
485 "{}.mul_add({}, {})",
486 prepare_receiver_sugg(cx, recv),
487 Sugg::hir(cx, arg1, ".."),
488 Sugg::hir(cx, arg2, ".."),
490 Applicability::MachineApplicable,
495 /// Returns true iff expr is an expression which tests whether or not
496 /// test is positive or an expression which tests whether or not test
498 /// Used for check-custom-abs function below
499 fn is_testing_positive(cx: &LateContext<'_>, expr: &Expr<'_>, test: &Expr<'_>) -> bool {
500 if let ExprKind::Binary(Spanned { node: op, .. }, left, right) = expr.kind {
502 BinOpKind::Gt | BinOpKind::Ge => is_zero(cx, right) && are_exprs_equal(cx, left, test),
503 BinOpKind::Lt | BinOpKind::Le => is_zero(cx, left) && are_exprs_equal(cx, right, test),
511 /// See [`is_testing_positive`]
512 fn is_testing_negative(cx: &LateContext<'_>, expr: &Expr<'_>, test: &Expr<'_>) -> bool {
513 if let ExprKind::Binary(Spanned { node: op, .. }, left, right) = expr.kind {
515 BinOpKind::Gt | BinOpKind::Ge => is_zero(cx, left) && are_exprs_equal(cx, right, test),
516 BinOpKind::Lt | BinOpKind::Le => is_zero(cx, right) && are_exprs_equal(cx, left, test),
524 fn are_exprs_equal(cx: &LateContext<'_>, expr1: &Expr<'_>, expr2: &Expr<'_>) -> bool {
525 SpanlessEq::new(cx).ignore_fn().eq_expr(expr1, expr2)
528 /// Returns true iff expr is some zero literal
529 fn is_zero(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
530 match constant_simple(cx, cx.tables(), expr) {
531 Some(Constant::Int(i)) => i == 0,
532 Some(Constant::F32(f)) => f == 0.0,
533 Some(Constant::F64(f)) => f == 0.0,
538 /// If the two expressions are negations of each other, then it returns
539 /// a tuple, in which the first element is true iff expr1 is the
540 /// positive expressions, and the second element is the positive
541 /// one of the two expressions
542 /// If the two expressions are not negations of each other, then it
544 fn are_negated<'a>(cx: &LateContext<'_>, expr1: &'a Expr<'a>, expr2: &'a Expr<'a>) -> Option<(bool, &'a Expr<'a>)> {
545 if let ExprKind::Unary(UnOp::UnNeg, expr1_negated) = &expr1.kind {
546 if are_exprs_equal(cx, expr1_negated, expr2) {
547 return Some((false, expr2));
550 if let ExprKind::Unary(UnOp::UnNeg, expr2_negated) = &expr2.kind {
551 if are_exprs_equal(cx, expr1, expr2_negated) {
552 return Some((true, expr1));
558 fn check_custom_abs(cx: &LateContext<'_>, expr: &Expr<'_>) {
560 if let Some((cond, body, Some(else_body))) = higher::if_block(&expr);
561 if let ExprKind::Block(block, _) = body.kind;
562 if block.stmts.is_empty();
563 if let Some(if_body_expr) = block.expr;
564 if let ExprKind::Block(else_block, _) = else_body.kind;
565 if else_block.stmts.is_empty();
566 if let Some(else_body_expr) = else_block.expr;
567 if let Some((if_expr_positive, body)) = are_negated(cx, if_body_expr, else_body_expr);
569 let positive_abs_sugg = (
570 "manual implementation of `abs` method",
571 format!("{}.abs()", Sugg::hir(cx, body, "..")),
573 let negative_abs_sugg = (
574 "manual implementation of negation of `abs` method",
575 format!("-{}.abs()", Sugg::hir(cx, body, "..")),
577 let sugg = if is_testing_positive(cx, cond, body) {
578 if if_expr_positive {
583 } else if is_testing_negative(cx, cond, body) {
584 if if_expr_positive {
599 Applicability::MachineApplicable,
605 fn are_same_base_logs(cx: &LateContext<'_>, expr_a: &Expr<'_>, expr_b: &Expr<'_>) -> bool {
607 if let ExprKind::MethodCall(PathSegment { ident: method_name_a, .. }, _, ref args_a, _) = expr_a.kind;
608 if let ExprKind::MethodCall(PathSegment { ident: method_name_b, .. }, _, ref args_b, _) = expr_b.kind;
610 return method_name_a.as_str() == method_name_b.as_str() &&
611 args_a.len() == args_b.len() &&
613 ["ln", "log2", "log10"].contains(&&*method_name_a.as_str()) ||
614 method_name_a.as_str() == "log" && args_a.len() == 2 && are_exprs_equal(cx, &args_a[1], &args_b[1])
622 fn check_log_division(cx: &LateContext<'_>, expr: &Expr<'_>) {
623 // check if expression of the form x.logN() / y.logN()
625 if let ExprKind::Binary(
627 node: BinOpKind::Div, ..
632 if are_same_base_logs(cx, lhs, rhs);
633 if let ExprKind::MethodCall(_, _, ref largs, _) = lhs.kind;
634 if let ExprKind::MethodCall(_, _, ref rargs, _) = rhs.kind;
640 "log base can be expressed more clearly",
642 format!("{}.log({})", Sugg::hir(cx, &largs[0], ".."), Sugg::hir(cx, &rargs[0], ".."),),
643 Applicability::MachineApplicable,
649 fn check_radians(cx: &LateContext<'_>, expr: &Expr<'_>) {
651 if let ExprKind::Binary(
653 node: BinOpKind::Div, ..
658 if let ExprKind::Binary(
660 node: BinOpKind::Mul, ..
665 if let Some((rvalue, _)) = constant(cx, cx.tables(), div_rhs);
666 if let Some((lvalue, _)) = constant(cx, cx.tables(), mul_rhs);
668 // TODO: also check for constant values near PI/180 or 180/PI
669 if (F32(f32_consts::PI) == rvalue || F64(f64_consts::PI) == rvalue) &&
670 (F32(180_f32) == lvalue || F64(180_f64) == lvalue)
676 "conversion to degrees can be done more accurately",
678 format!("{}.to_degrees()", Sugg::hir(cx, &mul_lhs, "..")),
679 Applicability::MachineApplicable,
682 (F32(180_f32) == rvalue || F64(180_f64) == rvalue) &&
683 (F32(f32_consts::PI) == lvalue || F64(f64_consts::PI) == lvalue)
689 "conversion to radians can be done more accurately",
691 format!("{}.to_radians()", Sugg::hir(cx, &mul_lhs, "..")),
692 Applicability::MachineApplicable,
699 impl<'tcx> LateLintPass<'tcx> for FloatingPointArithmetic {
700 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
701 if let ExprKind::MethodCall(ref path, _, args, _) = &expr.kind {
702 let recv_ty = cx.tables().expr_ty(&args[0]);
704 if recv_ty.is_floating_point() {
705 match &*path.ident.name.as_str() {
706 "ln" => check_ln1p(cx, expr, args),
707 "log" => check_log_base(cx, expr, args),
708 "powf" => check_powf(cx, expr, args),
709 "powi" => check_powi(cx, expr, args),
710 "sqrt" => check_hypot(cx, expr, args),
715 check_expm1(cx, expr);
716 check_mul_add(cx, expr);
717 check_custom_abs(cx, expr);
718 check_log_division(cx, expr);
719 check_radians(cx, expr);