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