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