]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/floating_point_arithmetic.rs
Auto merge of #85020 - lrh2000:named-upvars, r=tmandry
[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::{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};
11 use rustc_middle::ty;
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 use rustc_span::source_map::Spanned;
14
15 use rustc_ast::ast;
16 use std::f32::consts as f32_consts;
17 use std::f64::consts as f64_consts;
18 use sugg::Sugg;
19
20 declare_clippy_lint! {
21     /// ### What it does
22     /// Looks for floating-point expressions that
23     /// can be expressed using built-in methods to improve accuracy
24     /// at the cost of performance.
25     ///
26     /// ### Why is this bad?
27     /// Negatively impacts accuracy.
28     ///
29     /// ### Example
30     /// ```rust
31     /// let a = 3f32;
32     /// let _ = a.powf(1.0 / 3.0);
33     /// let _ = (1.0 + a).ln();
34     /// let _ = a.exp() - 1.0;
35     /// ```
36     ///
37     /// is better expressed as
38     ///
39     /// ```rust
40     /// let a = 3f32;
41     /// let _ = a.cbrt();
42     /// let _ = a.ln_1p();
43     /// let _ = a.exp_m1();
44     /// ```
45     pub IMPRECISE_FLOPS,
46     nursery,
47     "usage of imprecise floating point operations"
48 }
49
50 declare_clippy_lint! {
51     /// ### What it does
52     /// Looks for floating-point expressions that
53     /// can be expressed using built-in methods to improve both
54     /// accuracy and performance.
55     ///
56     /// ### Why is this bad?
57     /// Negatively impacts accuracy and performance.
58     ///
59     /// ### Example
60     /// ```rust
61     /// use std::f32::consts::E;
62     ///
63     /// let a = 3f32;
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);
69     /// let _ = a.log(E);
70     /// let _ = a.powf(2.0);
71     /// let _ = a * 2.0 + 4.0;
72     /// let _ = if a < 0.0 {
73     ///     -a
74     /// } else {
75     ///     a
76     /// };
77     /// let _ = if a < 0.0 {
78     ///     a
79     /// } else {
80     ///     -a
81     /// };
82     /// ```
83     ///
84     /// is better expressed as
85     ///
86     /// ```rust
87     /// use std::f32::consts::E;
88     ///
89     /// let a = 3f32;
90     /// let _ = a.exp2();
91     /// let _ = a.exp();
92     /// let _ = a.sqrt();
93     /// let _ = a.log2();
94     /// let _ = a.log10();
95     /// let _ = a.ln();
96     /// let _ = a.powi(2);
97     /// let _ = a.mul_add(2.0, 4.0);
98     /// let _ = a.abs();
99     /// let _ = -a.abs();
100     /// ```
101     pub SUBOPTIMAL_FLOPS,
102     nursery,
103     "usage of sub-optimal floating point operations"
104 }
105
106 declare_lint_pass!(FloatingPointArithmetic => [
107     IMPRECISE_FLOPS,
108     SUBOPTIMAL_FLOPS
109 ]);
110
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 {
116             return Some("log2");
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 {
120             return Some("ln");
121         }
122     }
123
124     None
125 }
126
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, "..");
130
131     if let ExprKind::Unary(UnOp::Neg, inner_expr) = &expr.kind {
132         expr = inner_expr;
133     }
134
135     if_chain! {
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;
141         then {
142             let op = format!(
143                 "{}{}{}",
144                 suggestion,
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('.') {
148                     "0"
149                 } else {
150                     ""
151                 },
152                 float_ty.name_str()
153             ).into();
154
155             suggestion = match suggestion {
156                 Sugg::MaybeParen(_) => Sugg::MaybeParen(op),
157                 _ => Sugg::NonParen(op)
158             };
159         }
160     }
161
162     suggestion.maybe_par()
163 }
164
165 fn check_log_base(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) {
166     if let Some(method) = get_specialized_log_method(cx, &args[1]) {
167         span_lint_and_sugg(
168             cx,
169             SUBOPTIMAL_FLOPS,
170             expr.span,
171             "logarithm for bases 2, 10 and e can be computed more accurately",
172             "consider using",
173             format!("{}.{}()", Sugg::hir(cx, &args[0], ".."), method),
174             Applicability::MachineApplicable,
175         );
176     }
177 }
178
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(
183         Spanned {
184             node: BinOpKind::Add, ..
185         },
186         lhs,
187         rhs,
188     ) = &args[0].kind
189     {
190         let recv = match (
191             constant(cx, cx.typeck_results(), lhs),
192             constant(cx, cx.typeck_results(), rhs),
193         ) {
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,
196             _ => return,
197         };
198
199         span_lint_and_sugg(
200             cx,
201             IMPRECISE_FLOPS,
202             expr.span,
203             "ln(1 + x) can be computed more accurately",
204             "consider using",
205             format!("{}.ln_1p()", prepare_receiver_sugg(cx, recv)),
206             Applicability::MachineApplicable,
207         );
208     }
209 }
210
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> {
217     match value {
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)
221             } else {
222                 None
223             }
224         },
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)
228             } else {
229                 None
230             }
231         },
232         _ => None,
233     }
234 }
235
236 fn check_powf(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) {
237     // Check receiver
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 {
240             "exp"
241         } else if F32(2.0) == value || F64(2.0) == value {
242             "exp2"
243         } else {
244             return;
245         };
246
247         span_lint_and_sugg(
248             cx,
249             SUBOPTIMAL_FLOPS,
250             expr.span,
251             "exponent for bases 2 and e can be computed more accurately",
252             "consider using",
253             format!("{}.{}()", prepare_receiver_sugg(cx, &args[1]), method),
254             Applicability::MachineApplicable,
255         );
256     }
257
258     // Check argument
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 {
261             (
262                 SUBOPTIMAL_FLOPS,
263                 "square-root of a number can be computed more efficiently and accurately",
264                 format!("{}.sqrt()", Sugg::hir(cx, &args[0], "..")),
265             )
266         } else if F32(1.0 / 3.0) == value || F64(1.0 / 3.0) == value {
267             (
268                 IMPRECISE_FLOPS,
269                 "cube-root of a number can be computed more accurately",
270                 format!("{}.cbrt()", Sugg::hir(cx, &args[0], "..")),
271             )
272         } else if let Some(exponent) = get_integer_from_float_constant(&value) {
273             (
274                 SUBOPTIMAL_FLOPS,
275                 "exponentiation with integer powers can be computed more efficiently",
276                 format!(
277                     "{}.powi({})",
278                     Sugg::hir(cx, &args[0], ".."),
279                     numeric_literal::format(&exponent.to_string(), None, false)
280                 ),
281             )
282         } else {
283             return;
284         };
285
286         span_lint_and_sugg(
287             cx,
288             lint,
289             expr.span,
290             help,
291             "consider using",
292             suggestion,
293             Applicability::MachineApplicable,
294         );
295     }
296 }
297
298 fn check_powi(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) {
299     if let Some((value, _)) = constant(cx, cx.typeck_results(), &args[1]) {
300         if value == Int(2) {
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() {
305                             return;
306                         }
307                     }
308                 }
309
310                 if let ExprKind::Binary(
311                     Spanned {
312                         node: BinOpKind::Add, ..
313                     },
314                     lhs,
315                     rhs,
316                 ) = parent.kind
317                 {
318                     let other_addend = if lhs.hir_id == expr.hir_id { rhs } else { lhs };
319
320                     span_lint_and_sugg(
321                         cx,
322                         SUBOPTIMAL_FLOPS,
323                         parent.span,
324                         "multiply and add expressions can be calculated more efficiently and accurately",
325                         "consider using",
326                         format!(
327                             "{}.mul_add({}, {})",
328                             Sugg::hir(cx, &args[0], ".."),
329                             Sugg::hir(cx, &args[0], ".."),
330                             Sugg::hir(cx, other_addend, ".."),
331                         ),
332                         Applicability::MachineApplicable,
333                     );
334
335                     return;
336                 }
337             }
338         }
339     }
340 }
341
342 fn detect_hypot(cx: &LateContext<'_>, args: &[Expr<'_>]) -> Option<String> {
343     if let ExprKind::Binary(
344         Spanned {
345             node: BinOpKind::Add, ..
346         },
347         add_lhs,
348         add_rhs,
349     ) = args[0].kind
350     {
351         // check if expression of the form x * x + y * y
352         if_chain! {
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);
357             then {
358                 return Some(format!("{}.hypot({})", Sugg::hir(cx, lmul_lhs, ".."), Sugg::hir(cx, rmul_lhs, "..")));
359             }
360         }
361
362         // check if expression of the form x.powi(2) + y.powi(2)
363         if_chain! {
364             if let ExprKind::MethodCall(
365                 PathSegment { ident: lmethod_name, .. },
366                 ref _lspan,
367                 largs,
368                 _
369             ) = add_lhs.kind;
370             if let ExprKind::MethodCall(
371                 PathSegment { ident: rmethod_name, .. },
372                 ref _rspan,
373                 rargs,
374                 _
375             ) = add_rhs.kind;
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;
380             then {
381                 return Some(format!("{}.hypot({})", Sugg::hir(cx, &largs[0], ".."), Sugg::hir(cx, &rargs[0], "..")));
382             }
383         }
384     }
385
386     None
387 }
388
389 fn check_hypot(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) {
390     if let Some(message) = detect_hypot(cx, args) {
391         span_lint_and_sugg(
392             cx,
393             IMPRECISE_FLOPS,
394             expr.span,
395             "hypotenuse can be computed more accurately",
396             "consider using",
397             message,
398             Applicability::MachineApplicable,
399         );
400     }
401 }
402
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<'_>) {
406     if_chain! {
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";
414         then {
415             span_lint_and_sugg(
416                 cx,
417                 IMPRECISE_FLOPS,
418                 expr.span,
419                 "(e.pow(x) - 1) can be computed more accurately",
420                 "consider using",
421                 format!(
422                     "{}.exp_m1()",
423                     Sugg::hir(cx, &method_args[0], "..")
424                 ),
425                 Applicability::MachineApplicable,
426             );
427         }
428     }
429 }
430
431 fn is_float_mul_expr<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<(&'a Expr<'a>, &'a Expr<'a>)> {
432     if_chain! {
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();
436         then {
437             return Some((lhs, rhs));
438         }
439     }
440
441     None
442 }
443
444 // TODO: Fix rust-lang/rust-clippy#4735
445 fn check_mul_add(cx: &LateContext<'_>, expr: &Expr<'_>) {
446     if let ExprKind::Binary(
447         Spanned {
448             node: BinOpKind::Add, ..
449         },
450         lhs,
451         rhs,
452     ) = &expr.kind
453     {
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() {
457                     return;
458                 }
459             }
460         }
461
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)
466         } else {
467             return;
468         };
469
470         span_lint_and_sugg(
471             cx,
472             SUBOPTIMAL_FLOPS,
473             expr.span,
474             "multiply and add expressions can be calculated more efficiently and accurately",
475             "consider using",
476             format!(
477                 "{}.mul_add({}, {})",
478                 prepare_receiver_sugg(cx, recv),
479                 Sugg::hir(cx, arg1, ".."),
480                 Sugg::hir(cx, arg2, ".."),
481             ),
482             Applicability::MachineApplicable,
483         );
484     }
485 }
486
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
489 /// is nonnegative.
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 {
493         match op {
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),
496             _ => false,
497         }
498     } else {
499         false
500     }
501 }
502
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 {
506         match op {
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),
509             _ => false,
510         }
511     } else {
512         false
513     }
514 }
515
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,
522         _ => false,
523     }
524 }
525
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
531 /// returns None.
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));
536         }
537     }
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));
541         }
542     }
543     None
544 }
545
546 fn check_custom_abs(cx: &LateContext<'_>, expr: &Expr<'_>) {
547     if_chain! {
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);
556         then {
557             let positive_abs_sugg = (
558                 "manual implementation of `abs` method",
559                 format!("{}.abs()", Sugg::hir(cx, body, "..")),
560             );
561             let negative_abs_sugg = (
562                 "manual implementation of negation of `abs` method",
563                 format!("-{}.abs()", Sugg::hir(cx, body, "..")),
564             );
565             let sugg = if is_testing_positive(cx, cond, body) {
566                 if if_expr_positive {
567                     positive_abs_sugg
568                 } else {
569                     negative_abs_sugg
570                 }
571             } else if is_testing_negative(cx, cond, body) {
572                 if if_expr_positive {
573                     negative_abs_sugg
574                 } else {
575                     positive_abs_sugg
576                 }
577             } else {
578                 return;
579             };
580             span_lint_and_sugg(
581                 cx,
582                 SUBOPTIMAL_FLOPS,
583                 expr.span,
584                 sugg.0,
585                 "try",
586                 sugg.1,
587                 Applicability::MachineApplicable,
588             );
589         }
590     }
591 }
592
593 fn are_same_base_logs(cx: &LateContext<'_>, expr_a: &Expr<'_>, expr_b: &Expr<'_>) -> bool {
594     if_chain! {
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;
597         then {
598             return method_name_a.as_str() == method_name_b.as_str() &&
599                 args_a.len() == args_b.len() &&
600                 (
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])
603                 );
604         }
605     }
606
607     false
608 }
609
610 fn check_log_division(cx: &LateContext<'_>, expr: &Expr<'_>) {
611     // check if expression of the form x.logN() / y.logN()
612     if_chain! {
613         if let ExprKind::Binary(
614             Spanned {
615                 node: BinOpKind::Div, ..
616             },
617             lhs,
618             rhs,
619         ) = &expr.kind;
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;
623         then {
624             span_lint_and_sugg(
625                 cx,
626                 SUBOPTIMAL_FLOPS,
627                 expr.span,
628                 "log base can be expressed more clearly",
629                 "consider using",
630                 format!("{}.log({})", Sugg::hir(cx, &largs[0], ".."), Sugg::hir(cx, &rargs[0], ".."),),
631                 Applicability::MachineApplicable,
632             );
633         }
634     }
635 }
636
637 fn check_radians(cx: &LateContext<'_>, expr: &Expr<'_>) {
638     if_chain! {
639         if let ExprKind::Binary(
640             Spanned {
641                 node: BinOpKind::Div, ..
642             },
643             div_lhs,
644             div_rhs,
645         ) = &expr.kind;
646         if let ExprKind::Binary(
647             Spanned {
648                 node: BinOpKind::Mul, ..
649             },
650             mul_lhs,
651             mul_rhs,
652         ) = &div_lhs.kind;
653         if let Some((rvalue, _)) = constant(cx, cx.typeck_results(), div_rhs);
654         if let Some((lvalue, _)) = constant(cx, cx.typeck_results(), mul_rhs);
655         then {
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)
659             {
660                 span_lint_and_sugg(
661                     cx,
662                     SUBOPTIMAL_FLOPS,
663                     expr.span,
664                     "conversion to degrees can be done more accurately",
665                     "consider using",
666                     format!("{}.to_degrees()", Sugg::hir(cx, mul_lhs, "..")),
667                     Applicability::MachineApplicable,
668                 );
669             } else if
670                 (F32(180_f32) == rvalue || F64(180_f64) == rvalue) &&
671                 (F32(f32_consts::PI) == lvalue || F64(f64_consts::PI) == lvalue)
672             {
673                 span_lint_and_sugg(
674                     cx,
675                     SUBOPTIMAL_FLOPS,
676                     expr.span,
677                     "conversion to radians can be done more accurately",
678                     "consider using",
679                     format!("{}.to_radians()", Sugg::hir(cx, mul_lhs, "..")),
680                     Applicability::MachineApplicable,
681                 );
682             }
683         }
684     }
685 }
686
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]);
691
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),
699                     _ => {},
700                 }
701             }
702         } else {
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);
708         }
709     }
710 }