]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/floating_point_arithmetic.rs
Auto merge of #92740 - cuviper:update-rayons, r=Mark-Simulacrum
[rust.git] / src / tools / clippy / clippy_lints / src / floating_point_arithmetic.rs
1 use clippy_utils::consts::{
2     constant, constant_simple, Constant,
3     Constant::{Int, F32, F64},
4 };
5 use clippy_utils::diagnostics::span_lint_and_sugg;
6 use clippy_utils::higher;
7 use clippy_utils::{eq_expr_value, get_parent_expr, in_constant, numeric_literal, peel_blocks, sugg};
8 use if_chain::if_chain;
9 use rustc_errors::Applicability;
10 use rustc_hir::{BinOpKind, Expr, ExprKind, PathSegment, UnOp};
11 use rustc_lint::{LateContext, LateLintPass};
12 use rustc_middle::ty;
13 use rustc_session::{declare_lint_pass, declare_tool_lint};
14 use rustc_span::source_map::Spanned;
15
16 use rustc_ast::ast;
17 use std::f32::consts as f32_consts;
18 use std::f64::consts as f64_consts;
19 use sugg::Sugg;
20
21 declare_clippy_lint! {
22     /// ### What it does
23     /// Looks for floating-point expressions that
24     /// can be expressed using built-in methods to improve accuracy
25     /// at the cost of performance.
26     ///
27     /// ### Why is this bad?
28     /// Negatively impacts accuracy.
29     ///
30     /// ### Example
31     /// ```rust
32     /// let a = 3f32;
33     /// let _ = a.powf(1.0 / 3.0);
34     /// let _ = (1.0 + a).ln();
35     /// let _ = a.exp() - 1.0;
36     /// ```
37     ///
38     /// is better expressed as
39     ///
40     /// ```rust
41     /// let a = 3f32;
42     /// let _ = a.cbrt();
43     /// let _ = a.ln_1p();
44     /// let _ = a.exp_m1();
45     /// ```
46     #[clippy::version = "1.43.0"]
47     pub IMPRECISE_FLOPS,
48     nursery,
49     "usage of imprecise floating point operations"
50 }
51
52 declare_clippy_lint! {
53     /// ### What it does
54     /// Looks for floating-point expressions that
55     /// can be expressed using built-in methods to improve both
56     /// accuracy and performance.
57     ///
58     /// ### Why is this bad?
59     /// Negatively impacts accuracy and performance.
60     ///
61     /// ### Example
62     /// ```rust
63     /// use std::f32::consts::E;
64     ///
65     /// let a = 3f32;
66     /// let _ = (2f32).powf(a);
67     /// let _ = E.powf(a);
68     /// let _ = a.powf(1.0 / 2.0);
69     /// let _ = a.log(2.0);
70     /// let _ = a.log(10.0);
71     /// let _ = a.log(E);
72     /// let _ = a.powf(2.0);
73     /// let _ = a * 2.0 + 4.0;
74     /// let _ = if a < 0.0 {
75     ///     -a
76     /// } else {
77     ///     a
78     /// };
79     /// let _ = if a < 0.0 {
80     ///     a
81     /// } else {
82     ///     -a
83     /// };
84     /// ```
85     ///
86     /// is better expressed as
87     ///
88     /// ```rust
89     /// use std::f32::consts::E;
90     ///
91     /// let a = 3f32;
92     /// let _ = a.exp2();
93     /// let _ = a.exp();
94     /// let _ = a.sqrt();
95     /// let _ = a.log2();
96     /// let _ = a.log10();
97     /// let _ = a.ln();
98     /// let _ = a.powi(2);
99     /// let _ = a.mul_add(2.0, 4.0);
100     /// let _ = a.abs();
101     /// let _ = -a.abs();
102     /// ```
103     #[clippy::version = "1.43.0"]
104     pub SUBOPTIMAL_FLOPS,
105     nursery,
106     "usage of sub-optimal floating point operations"
107 }
108
109 declare_lint_pass!(FloatingPointArithmetic => [
110     IMPRECISE_FLOPS,
111     SUBOPTIMAL_FLOPS
112 ]);
113
114 // Returns the specialized log method for a given base if base is constant
115 // and is one of 2, 10 and e
116 fn get_specialized_log_method(cx: &LateContext<'_>, base: &Expr<'_>) -> Option<&'static str> {
117     if let Some((value, _)) = constant(cx, cx.typeck_results(), base) {
118         if F32(2.0) == value || F64(2.0) == value {
119             return Some("log2");
120         } else if F32(10.0) == value || F64(10.0) == value {
121             return Some("log10");
122         } else if F32(f32_consts::E) == value || F64(f64_consts::E) == value {
123             return Some("ln");
124         }
125     }
126
127     None
128 }
129
130 // Adds type suffixes and parenthesis to method receivers if necessary
131 fn prepare_receiver_sugg<'a>(cx: &LateContext<'_>, mut expr: &'a Expr<'a>) -> Sugg<'a> {
132     let mut suggestion = Sugg::hir(cx, expr, "..");
133
134     if let ExprKind::Unary(UnOp::Neg, inner_expr) = &expr.kind {
135         expr = inner_expr;
136     }
137
138     if_chain! {
139         // if the expression is a float literal and it is unsuffixed then
140         // add a suffix so the suggestion is valid and unambiguous
141         if let ty::Float(float_ty) = cx.typeck_results().expr_ty(expr).kind();
142         if let ExprKind::Lit(lit) = &expr.kind;
143         if let ast::LitKind::Float(sym, ast::LitFloatType::Unsuffixed) = lit.node;
144         then {
145             let op = format!(
146                 "{}{}{}",
147                 suggestion,
148                 // Check for float literals without numbers following the decimal
149                 // separator such as `2.` and adds a trailing zero
150                 if sym.as_str().ends_with('.') {
151                     "0"
152                 } else {
153                     ""
154                 },
155                 float_ty.name_str()
156             ).into();
157
158             suggestion = match suggestion {
159                 Sugg::MaybeParen(_) => Sugg::MaybeParen(op),
160                 _ => Sugg::NonParen(op)
161             };
162         }
163     }
164
165     suggestion.maybe_par()
166 }
167
168 fn check_log_base(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) {
169     if let Some(method) = get_specialized_log_method(cx, &args[1]) {
170         span_lint_and_sugg(
171             cx,
172             SUBOPTIMAL_FLOPS,
173             expr.span,
174             "logarithm for bases 2, 10 and e can be computed more accurately",
175             "consider using",
176             format!("{}.{}()", Sugg::hir(cx, &args[0], ".."), method),
177             Applicability::MachineApplicable,
178         );
179     }
180 }
181
182 // TODO: Lint expressions of the form `(x + y).ln()` where y > 1 and
183 // suggest usage of `(x + (y - 1)).ln_1p()` instead
184 fn check_ln1p(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) {
185     if let ExprKind::Binary(
186         Spanned {
187             node: BinOpKind::Add, ..
188         },
189         lhs,
190         rhs,
191     ) = &args[0].kind
192     {
193         let recv = match (
194             constant(cx, cx.typeck_results(), lhs),
195             constant(cx, cx.typeck_results(), rhs),
196         ) {
197             (Some((value, _)), _) if F32(1.0) == value || F64(1.0) == value => rhs,
198             (_, Some((value, _))) if F32(1.0) == value || F64(1.0) == value => lhs,
199             _ => return,
200         };
201
202         span_lint_and_sugg(
203             cx,
204             IMPRECISE_FLOPS,
205             expr.span,
206             "ln(1 + x) can be computed more accurately",
207             "consider using",
208             format!("{}.ln_1p()", prepare_receiver_sugg(cx, recv)),
209             Applicability::MachineApplicable,
210         );
211     }
212 }
213
214 // Returns an integer if the float constant is a whole number and it can be
215 // converted to an integer without loss of precision. For now we only check
216 // ranges [-16777215, 16777216) for type f32 as whole number floats outside
217 // this range are lossy and ambiguous.
218 #[allow(clippy::cast_possible_truncation)]
219 fn get_integer_from_float_constant(value: &Constant) -> Option<i32> {
220     match value {
221         F32(num) if num.fract() == 0.0 => {
222             if (-16_777_215.0..16_777_216.0).contains(num) {
223                 Some(num.round() as i32)
224             } else {
225                 None
226             }
227         },
228         F64(num) if num.fract() == 0.0 => {
229             if (-2_147_483_648.0..2_147_483_648.0).contains(num) {
230                 Some(num.round() as i32)
231             } else {
232                 None
233             }
234         },
235         _ => None,
236     }
237 }
238
239 fn check_powf(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) {
240     // Check receiver
241     if let Some((value, _)) = constant(cx, cx.typeck_results(), &args[0]) {
242         let method = if F32(f32_consts::E) == value || F64(f64_consts::E) == value {
243             "exp"
244         } else if F32(2.0) == value || F64(2.0) == value {
245             "exp2"
246         } else {
247             return;
248         };
249
250         span_lint_and_sugg(
251             cx,
252             SUBOPTIMAL_FLOPS,
253             expr.span,
254             "exponent for bases 2 and e can be computed more accurately",
255             "consider using",
256             format!("{}.{}()", prepare_receiver_sugg(cx, &args[1]), method),
257             Applicability::MachineApplicable,
258         );
259     }
260
261     // Check argument
262     if let Some((value, _)) = constant(cx, cx.typeck_results(), &args[1]) {
263         let (lint, help, suggestion) = if F32(1.0 / 2.0) == value || F64(1.0 / 2.0) == value {
264             (
265                 SUBOPTIMAL_FLOPS,
266                 "square-root of a number can be computed more efficiently and accurately",
267                 format!("{}.sqrt()", Sugg::hir(cx, &args[0], "..")),
268             )
269         } else if F32(1.0 / 3.0) == value || F64(1.0 / 3.0) == value {
270             (
271                 IMPRECISE_FLOPS,
272                 "cube-root of a number can be computed more accurately",
273                 format!("{}.cbrt()", Sugg::hir(cx, &args[0], "..")),
274             )
275         } else if let Some(exponent) = get_integer_from_float_constant(&value) {
276             (
277                 SUBOPTIMAL_FLOPS,
278                 "exponentiation with integer powers can be computed more efficiently",
279                 format!(
280                     "{}.powi({})",
281                     Sugg::hir(cx, &args[0], ".."),
282                     numeric_literal::format(&exponent.to_string(), None, false)
283                 ),
284             )
285         } else {
286             return;
287         };
288
289         span_lint_and_sugg(
290             cx,
291             lint,
292             expr.span,
293             help,
294             "consider using",
295             suggestion,
296             Applicability::MachineApplicable,
297         );
298     }
299 }
300
301 fn check_powi(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) {
302     if let Some((value, _)) = constant(cx, cx.typeck_results(), &args[1]) {
303         if value == Int(2) {
304             if let Some(parent) = get_parent_expr(cx, expr) {
305                 if let Some(grandparent) = get_parent_expr(cx, parent) {
306                     if let ExprKind::MethodCall(PathSegment { ident: method_name, .. }, _, args, _) = grandparent.kind {
307                         if method_name.as_str() == "sqrt" && detect_hypot(cx, args).is_some() {
308                             return;
309                         }
310                     }
311                 }
312
313                 if let ExprKind::Binary(
314                     Spanned {
315                         node: BinOpKind::Add, ..
316                     },
317                     lhs,
318                     rhs,
319                 ) = parent.kind
320                 {
321                     let other_addend = if lhs.hir_id == expr.hir_id { rhs } else { lhs };
322
323                     span_lint_and_sugg(
324                         cx,
325                         SUBOPTIMAL_FLOPS,
326                         parent.span,
327                         "multiply and add expressions can be calculated more efficiently and accurately",
328                         "consider using",
329                         format!(
330                             "{}.mul_add({}, {})",
331                             Sugg::hir(cx, &args[0], ".."),
332                             Sugg::hir(cx, &args[0], ".."),
333                             Sugg::hir(cx, other_addend, ".."),
334                         ),
335                         Applicability::MachineApplicable,
336                     );
337                 }
338             }
339         }
340     }
341 }
342
343 fn detect_hypot(cx: &LateContext<'_>, args: &[Expr<'_>]) -> Option<String> {
344     if let ExprKind::Binary(
345         Spanned {
346             node: BinOpKind::Add, ..
347         },
348         add_lhs,
349         add_rhs,
350     ) = args[0].kind
351     {
352         // check if expression of the form x * x + y * y
353         if_chain! {
354             if let ExprKind::Binary(Spanned { node: BinOpKind::Mul, .. }, lmul_lhs, lmul_rhs) = add_lhs.kind;
355             if let ExprKind::Binary(Spanned { node: BinOpKind::Mul, .. }, rmul_lhs, rmul_rhs) = add_rhs.kind;
356             if eq_expr_value(cx, lmul_lhs, lmul_rhs);
357             if eq_expr_value(cx, rmul_lhs, rmul_rhs);
358             then {
359                 return Some(format!("{}.hypot({})", Sugg::hir(cx, lmul_lhs, "..").maybe_par(), Sugg::hir(cx, rmul_lhs, "..")));
360             }
361         }
362
363         // check if expression of the form x.powi(2) + y.powi(2)
364         if_chain! {
365             if let ExprKind::MethodCall(
366                 PathSegment { ident: lmethod_name, .. },
367                 _lspan,
368                 [largs_0, largs_1, ..],
369                 _
370             ) = &add_lhs.kind;
371             if let ExprKind::MethodCall(
372                 PathSegment { ident: rmethod_name, .. },
373                 _rspan,
374                 [rargs_0, rargs_1, ..],
375                 _
376             ) = &add_rhs.kind;
377             if lmethod_name.as_str() == "powi" && rmethod_name.as_str() == "powi";
378             if let Some((lvalue, _)) = constant(cx, cx.typeck_results(), largs_1);
379             if let Some((rvalue, _)) = constant(cx, cx.typeck_results(), rargs_1);
380             if Int(2) == lvalue && Int(2) == rvalue;
381             then {
382                 return Some(format!("{}.hypot({})", Sugg::hir(cx, largs_0, "..").maybe_par(), Sugg::hir(cx, rargs_0, "..")));
383             }
384         }
385     }
386
387     None
388 }
389
390 fn check_hypot(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) {
391     if let Some(message) = detect_hypot(cx, args) {
392         span_lint_and_sugg(
393             cx,
394             IMPRECISE_FLOPS,
395             expr.span,
396             "hypotenuse can be computed more accurately",
397             "consider using",
398             message,
399             Applicability::MachineApplicable,
400         );
401     }
402 }
403
404 // TODO: Lint expressions of the form `x.exp() - y` where y > 1
405 // and suggest usage of `x.exp_m1() - (y - 1)` instead
406 fn check_expm1(cx: &LateContext<'_>, expr: &Expr<'_>) {
407     if_chain! {
408         if let ExprKind::Binary(Spanned { node: BinOpKind::Sub, .. }, lhs, rhs) = expr.kind;
409         if cx.typeck_results().expr_ty(lhs).is_floating_point();
410         if let Some((value, _)) = constant(cx, cx.typeck_results(), rhs);
411         if F32(1.0) == value || F64(1.0) == value;
412         if let ExprKind::MethodCall(path, _, [self_arg, ..], _) = &lhs.kind;
413         if cx.typeck_results().expr_ty(self_arg).is_floating_point();
414         if path.ident.name.as_str() == "exp";
415         then {
416             span_lint_and_sugg(
417                 cx,
418                 IMPRECISE_FLOPS,
419                 expr.span,
420                 "(e.pow(x) - 1) can be computed more accurately",
421                 "consider using",
422                 format!(
423                     "{}.exp_m1()",
424                     Sugg::hir(cx, self_arg, "..")
425                 ),
426                 Applicability::MachineApplicable,
427             );
428         }
429     }
430 }
431
432 fn is_float_mul_expr<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<(&'a Expr<'a>, &'a Expr<'a>)> {
433     if_chain! {
434         if let ExprKind::Binary(Spanned { node: BinOpKind::Mul, .. }, lhs, rhs) = &expr.kind;
435         if cx.typeck_results().expr_ty(lhs).is_floating_point();
436         if cx.typeck_results().expr_ty(rhs).is_floating_point();
437         then {
438             return Some((lhs, rhs));
439         }
440     }
441
442     None
443 }
444
445 // TODO: Fix rust-lang/rust-clippy#4735
446 fn check_mul_add(cx: &LateContext<'_>, expr: &Expr<'_>) {
447     if let ExprKind::Binary(
448         Spanned {
449             node: BinOpKind::Add, ..
450         },
451         lhs,
452         rhs,
453     ) = &expr.kind
454     {
455         if let Some(parent) = get_parent_expr(cx, expr) {
456             if let ExprKind::MethodCall(PathSegment { ident: method_name, .. }, _, args, _) = parent.kind {
457                 if method_name.as_str() == "sqrt" && detect_hypot(cx, args).is_some() {
458                     return;
459                 }
460             }
461         }
462
463         let (recv, arg1, arg2) = if let Some((inner_lhs, inner_rhs)) = is_float_mul_expr(cx, lhs) {
464             (inner_lhs, inner_rhs, rhs)
465         } else if let Some((inner_lhs, inner_rhs)) = is_float_mul_expr(cx, rhs) {
466             (inner_lhs, inner_rhs, lhs)
467         } else {
468             return;
469         };
470
471         span_lint_and_sugg(
472             cx,
473             SUBOPTIMAL_FLOPS,
474             expr.span,
475             "multiply and add expressions can be calculated more efficiently and accurately",
476             "consider using",
477             format!(
478                 "{}.mul_add({}, {})",
479                 prepare_receiver_sugg(cx, recv),
480                 Sugg::hir(cx, arg1, ".."),
481                 Sugg::hir(cx, arg2, ".."),
482             ),
483             Applicability::MachineApplicable,
484         );
485     }
486 }
487
488 /// Returns true iff expr is an expression which tests whether or not
489 /// test is positive or an expression which tests whether or not test
490 /// is nonnegative.
491 /// Used for check-custom-abs function below
492 fn is_testing_positive(cx: &LateContext<'_>, expr: &Expr<'_>, test: &Expr<'_>) -> bool {
493     if let ExprKind::Binary(Spanned { node: op, .. }, left, right) = expr.kind {
494         match op {
495             BinOpKind::Gt | BinOpKind::Ge => is_zero(cx, right) && eq_expr_value(cx, left, test),
496             BinOpKind::Lt | BinOpKind::Le => is_zero(cx, left) && eq_expr_value(cx, right, test),
497             _ => false,
498         }
499     } else {
500         false
501     }
502 }
503
504 /// See [`is_testing_positive`]
505 fn is_testing_negative(cx: &LateContext<'_>, expr: &Expr<'_>, test: &Expr<'_>) -> bool {
506     if let ExprKind::Binary(Spanned { node: op, .. }, left, right) = expr.kind {
507         match op {
508             BinOpKind::Gt | BinOpKind::Ge => is_zero(cx, left) && eq_expr_value(cx, right, test),
509             BinOpKind::Lt | BinOpKind::Le => is_zero(cx, right) && eq_expr_value(cx, left, test),
510             _ => false,
511         }
512     } else {
513         false
514     }
515 }
516
517 /// Returns true iff expr is some zero literal
518 fn is_zero(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
519     match constant_simple(cx, cx.typeck_results(), expr) {
520         Some(Constant::Int(i)) => i == 0,
521         Some(Constant::F32(f)) => f == 0.0,
522         Some(Constant::F64(f)) => f == 0.0,
523         _ => false,
524     }
525 }
526
527 /// If the two expressions are negations of each other, then it returns
528 /// a tuple, in which the first element is true iff expr1 is the
529 /// positive expressions, and the second element is the positive
530 /// one of the two expressions
531 /// If the two expressions are not negations of each other, then it
532 /// returns None.
533 fn are_negated<'a>(cx: &LateContext<'_>, expr1: &'a Expr<'a>, expr2: &'a Expr<'a>) -> Option<(bool, &'a Expr<'a>)> {
534     if let ExprKind::Unary(UnOp::Neg, expr1_negated) = &expr1.kind {
535         if eq_expr_value(cx, expr1_negated, expr2) {
536             return Some((false, expr2));
537         }
538     }
539     if let ExprKind::Unary(UnOp::Neg, expr2_negated) = &expr2.kind {
540         if eq_expr_value(cx, expr1, expr2_negated) {
541             return Some((true, expr1));
542         }
543     }
544     None
545 }
546
547 fn check_custom_abs(cx: &LateContext<'_>, expr: &Expr<'_>) {
548     if_chain! {
549         if let Some(higher::If { cond, then, r#else: Some(r#else) }) = higher::If::hir(expr);
550         let if_body_expr = peel_blocks(then);
551         let else_body_expr = peel_blocks(r#else);
552         if let Some((if_expr_positive, body)) = are_negated(cx, if_body_expr, else_body_expr);
553         then {
554             let positive_abs_sugg = (
555                 "manual implementation of `abs` method",
556                 format!("{}.abs()", Sugg::hir(cx, body, "..")),
557             );
558             let negative_abs_sugg = (
559                 "manual implementation of negation of `abs` method",
560                 format!("-{}.abs()", Sugg::hir(cx, body, "..")),
561             );
562             let sugg = if is_testing_positive(cx, cond, body) {
563                 if if_expr_positive {
564                     positive_abs_sugg
565                 } else {
566                     negative_abs_sugg
567                 }
568             } else if is_testing_negative(cx, cond, body) {
569                 if if_expr_positive {
570                     negative_abs_sugg
571                 } else {
572                     positive_abs_sugg
573                 }
574             } else {
575                 return;
576             };
577             span_lint_and_sugg(
578                 cx,
579                 SUBOPTIMAL_FLOPS,
580                 expr.span,
581                 sugg.0,
582                 "try",
583                 sugg.1,
584                 Applicability::MachineApplicable,
585             );
586         }
587     }
588 }
589
590 fn are_same_base_logs(cx: &LateContext<'_>, expr_a: &Expr<'_>, expr_b: &Expr<'_>) -> bool {
591     if_chain! {
592         if let ExprKind::MethodCall(PathSegment { ident: method_name_a, .. }, _, args_a, _) = expr_a.kind;
593         if let ExprKind::MethodCall(PathSegment { ident: method_name_b, .. }, _, args_b, _) = expr_b.kind;
594         then {
595             return method_name_a.as_str() == method_name_b.as_str() &&
596                 args_a.len() == args_b.len() &&
597                 (
598                     ["ln", "log2", "log10"].contains(&method_name_a.as_str()) ||
599                     method_name_a.as_str() == "log" && args_a.len() == 2 && eq_expr_value(cx, &args_a[1], &args_b[1])
600                 );
601         }
602     }
603
604     false
605 }
606
607 fn check_log_division(cx: &LateContext<'_>, expr: &Expr<'_>) {
608     // check if expression of the form x.logN() / y.logN()
609     if_chain! {
610         if let ExprKind::Binary(
611             Spanned {
612                 node: BinOpKind::Div, ..
613             },
614             lhs,
615             rhs,
616         ) = &expr.kind;
617         if are_same_base_logs(cx, lhs, rhs);
618         if let ExprKind::MethodCall(_, _, [largs_self, ..], _) = &lhs.kind;
619         if let ExprKind::MethodCall(_, _, [rargs_self, ..], _) = &rhs.kind;
620         then {
621             span_lint_and_sugg(
622                 cx,
623                 SUBOPTIMAL_FLOPS,
624                 expr.span,
625                 "log base can be expressed more clearly",
626                 "consider using",
627                 format!("{}.log({})", Sugg::hir(cx, largs_self, ".."), Sugg::hir(cx, rargs_self, ".."),),
628                 Applicability::MachineApplicable,
629             );
630         }
631     }
632 }
633
634 fn check_radians(cx: &LateContext<'_>, expr: &Expr<'_>) {
635     if_chain! {
636         if let ExprKind::Binary(
637             Spanned {
638                 node: BinOpKind::Div, ..
639             },
640             div_lhs,
641             div_rhs,
642         ) = &expr.kind;
643         if let ExprKind::Binary(
644             Spanned {
645                 node: BinOpKind::Mul, ..
646             },
647             mul_lhs,
648             mul_rhs,
649         ) = &div_lhs.kind;
650         if let Some((rvalue, _)) = constant(cx, cx.typeck_results(), div_rhs);
651         if let Some((lvalue, _)) = constant(cx, cx.typeck_results(), mul_rhs);
652         then {
653             // TODO: also check for constant values near PI/180 or 180/PI
654             if (F32(f32_consts::PI) == rvalue || F64(f64_consts::PI) == rvalue) &&
655                (F32(180_f32) == lvalue || F64(180_f64) == lvalue)
656             {
657                 let mut proposal = format!("{}.to_degrees()", Sugg::hir(cx, mul_lhs, ".."));
658                 if_chain! {
659                     if let ExprKind::Lit(ref literal) = mul_lhs.kind;
660                     if let ast::LitKind::Float(ref value, float_type) = literal.node;
661                     if float_type == ast::LitFloatType::Unsuffixed;
662                     then {
663                         if value.as_str().ends_with('.') {
664                             proposal = format!("{}0_f64.to_degrees()", Sugg::hir(cx, mul_lhs, ".."));
665                         } else {
666                             proposal = format!("{}_f64.to_degrees()", Sugg::hir(cx, mul_lhs, ".."));
667                         }
668                     }
669                 }
670                 span_lint_and_sugg(
671                     cx,
672                     SUBOPTIMAL_FLOPS,
673                     expr.span,
674                     "conversion to degrees can be done more accurately",
675                     "consider using",
676                     proposal,
677                     Applicability::MachineApplicable,
678                 );
679             } else if
680                 (F32(180_f32) == rvalue || F64(180_f64) == rvalue) &&
681                 (F32(f32_consts::PI) == lvalue || F64(f64_consts::PI) == lvalue)
682             {
683                 let mut proposal = format!("{}.to_radians()", Sugg::hir(cx, mul_lhs, ".."));
684                 if_chain! {
685                     if let ExprKind::Lit(ref literal) = mul_lhs.kind;
686                     if let ast::LitKind::Float(ref value, float_type) = literal.node;
687                     if float_type == ast::LitFloatType::Unsuffixed;
688                     then {
689                         if value.as_str().ends_with('.') {
690                             proposal = format!("{}0_f64.to_radians()", Sugg::hir(cx, mul_lhs, ".."));
691                         } else {
692                             proposal = format!("{}_f64.to_radians()", Sugg::hir(cx, mul_lhs, ".."));
693                         }
694                     }
695                 }
696                 span_lint_and_sugg(
697                     cx,
698                     SUBOPTIMAL_FLOPS,
699                     expr.span,
700                     "conversion to radians can be done more accurately",
701                     "consider using",
702                     proposal,
703                     Applicability::MachineApplicable,
704                 );
705             }
706         }
707     }
708 }
709
710 impl<'tcx> LateLintPass<'tcx> for FloatingPointArithmetic {
711     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
712         // All of these operations are currently not const.
713         if in_constant(cx, expr.hir_id) {
714             return;
715         }
716
717         if let ExprKind::MethodCall(path, _, args, _) = &expr.kind {
718             let recv_ty = cx.typeck_results().expr_ty(&args[0]);
719
720             if recv_ty.is_floating_point() {
721                 match path.ident.name.as_str() {
722                     "ln" => check_ln1p(cx, expr, args),
723                     "log" => check_log_base(cx, expr, args),
724                     "powf" => check_powf(cx, expr, args),
725                     "powi" => check_powi(cx, expr, args),
726                     "sqrt" => check_hypot(cx, expr, args),
727                     _ => {},
728                 }
729             }
730         } else {
731             check_expm1(cx, expr);
732             check_mul_add(cx, expr);
733             check_custom_abs(cx, expr);
734             check_log_division(cx, expr);
735             check_radians(cx, expr);
736         }
737     }
738 }