]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/floating_point_arithmetic.rs
Rollup merge of #73974 - CAD97:rc-no-weak, r=dtolnay
[rust.git] / src / tools / clippy / clippy_lints / src / floating_point_arithmetic.rs
1 use crate::consts::{
2     constant, constant_simple, Constant,
3     Constant::{F32, F64},
4 };
5 use crate::utils::{higher, numeric_literal, span_lint_and_sugg, sugg, SpanlessEq};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir::{BinOpKind, Expr, ExprKind, UnOp};
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_middle::ty;
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 use rustc_span::source_map::Spanned;
13
14 use rustc_ast::ast;
15 use std::f32::consts as f32_consts;
16 use std::f64::consts as f64_consts;
17 use sugg::Sugg;
18
19 declare_clippy_lint! {
20     /// **What it does:** Looks for floating-point expressions that
21     /// can be expressed using built-in methods to improve accuracy
22     /// at the cost of performance.
23     ///
24     /// **Why is this bad?** Negatively impacts accuracy.
25     ///
26     /// **Known problems:** None
27     ///
28     /// **Example:**
29     ///
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:** Looks for floating-point expressions that
52     /// can be expressed using built-in methods to improve both
53     /// accuracy and performance.
54     ///
55     /// **Why is this bad?** Negatively impacts accuracy and performance.
56     ///
57     /// **Known problems:** None
58     ///
59     /// **Example:**
60     ///
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     pub SUBOPTIMAL_FLOPS,
103     nursery,
104     "usage of sub-optimal floating point operations"
105 }
106
107 declare_lint_pass!(FloatingPointArithmetic => [
108     IMPRECISE_FLOPS,
109     SUBOPTIMAL_FLOPS
110 ]);
111
112 // Returns the specialized log method for a given base if base is constant
113 // and is one of 2, 10 and e
114 fn get_specialized_log_method(cx: &LateContext<'_>, base: &Expr<'_>) -> Option<&'static str> {
115     if let Some((value, _)) = constant(cx, cx.tables(), base) {
116         if F32(2.0) == value || F64(2.0) == value {
117             return Some("log2");
118         } else if F32(10.0) == value || F64(10.0) == value {
119             return Some("log10");
120         } else if F32(f32_consts::E) == value || F64(f64_consts::E) == value {
121             return Some("ln");
122         }
123     }
124
125     None
126 }
127
128 // Adds type suffixes and parenthesis to method receivers if necessary
129 fn prepare_receiver_sugg<'a>(cx: &LateContext<'_>, mut expr: &'a Expr<'a>) -> Sugg<'a> {
130     let mut suggestion = Sugg::hir(cx, expr, "..");
131
132     if let ExprKind::Unary(UnOp::UnNeg, inner_expr) = &expr.kind {
133         expr = &inner_expr;
134     }
135
136     if_chain! {
137         // if the expression is a float literal and it is unsuffixed then
138         // add a suffix so the suggestion is valid and unambiguous
139         if let ty::Float(float_ty) = cx.tables().expr_ty(expr).kind;
140         if let ExprKind::Lit(lit) = &expr.kind;
141         if let ast::LitKind::Float(sym, ast::LitFloatType::Unsuffixed) = lit.node;
142         then {
143             let op = format!(
144                 "{}{}{}",
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<'_>, args: &[Expr<'_>]) {
167     if let Some(method) = get_specialized_log_method(cx, &args[1]) {
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!("{}.{}()", Sugg::hir(cx, &args[0], ".."), method),
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<'_>, args: &[Expr<'_>]) {
183     if let ExprKind::Binary(
184         Spanned {
185             node: BinOpKind::Add, ..
186         },
187         lhs,
188         rhs,
189     ) = &args[0].kind
190     {
191         let recv = match (constant(cx, cx.tables(), lhs), constant(cx, cx.tables(), rhs)) {
192             (Some((value, _)), _) if F32(1.0) == value || F64(1.0) == value => rhs,
193             (_, Some((value, _))) if F32(1.0) == value || F64(1.0) == value => lhs,
194             _ => return,
195         };
196
197         span_lint_and_sugg(
198             cx,
199             IMPRECISE_FLOPS,
200             expr.span,
201             "ln(1 + x) can be computed more accurately",
202             "consider using",
203             format!("{}.ln_1p()", prepare_receiver_sugg(cx, recv)),
204             Applicability::MachineApplicable,
205         );
206     }
207 }
208
209 // Returns an integer if the float constant is a whole number and it can be
210 // converted to an integer without loss of precision. For now we only check
211 // ranges [-16777215, 16777216) for type f32 as whole number floats outside
212 // this range are lossy and ambiguous.
213 #[allow(clippy::cast_possible_truncation)]
214 fn get_integer_from_float_constant(value: &Constant) -> Option<i32> {
215     match value {
216         F32(num) if num.fract() == 0.0 => {
217             if (-16_777_215.0..16_777_216.0).contains(num) {
218                 Some(num.round() as i32)
219             } else {
220                 None
221             }
222         },
223         F64(num) if num.fract() == 0.0 => {
224             if (-2_147_483_648.0..2_147_483_648.0).contains(num) {
225                 Some(num.round() as i32)
226             } else {
227                 None
228             }
229         },
230         _ => None,
231     }
232 }
233
234 fn check_powf(cx: &LateContext<'_>, expr: &Expr<'_>, args: &[Expr<'_>]) {
235     // Check receiver
236     if let Some((value, _)) = constant(cx, cx.tables(), &args[0]) {
237         let method = if F32(f32_consts::E) == value || F64(f64_consts::E) == value {
238             "exp"
239         } else if F32(2.0) == value || F64(2.0) == value {
240             "exp2"
241         } else {
242             return;
243         };
244
245         span_lint_and_sugg(
246             cx,
247             SUBOPTIMAL_FLOPS,
248             expr.span,
249             "exponent for bases 2 and e can be computed more accurately",
250             "consider using",
251             format!("{}.{}()", prepare_receiver_sugg(cx, &args[1]), method),
252             Applicability::MachineApplicable,
253         );
254     }
255
256     // Check argument
257     if let Some((value, _)) = constant(cx, cx.tables(), &args[1]) {
258         let (lint, help, suggestion) = if F32(1.0 / 2.0) == value || F64(1.0 / 2.0) == value {
259             (
260                 SUBOPTIMAL_FLOPS,
261                 "square-root of a number can be computed more efficiently and accurately",
262                 format!("{}.sqrt()", Sugg::hir(cx, &args[0], "..")),
263             )
264         } else if F32(1.0 / 3.0) == value || F64(1.0 / 3.0) == value {
265             (
266                 IMPRECISE_FLOPS,
267                 "cube-root of a number can be computed more accurately",
268                 format!("{}.cbrt()", Sugg::hir(cx, &args[0], "..")),
269             )
270         } else if let Some(exponent) = get_integer_from_float_constant(&value) {
271             (
272                 SUBOPTIMAL_FLOPS,
273                 "exponentiation with integer powers can be computed more efficiently",
274                 format!(
275                     "{}.powi({})",
276                     Sugg::hir(cx, &args[0], ".."),
277                     numeric_literal::format(&exponent.to_string(), None, false)
278                 ),
279             )
280         } else {
281             return;
282         };
283
284         span_lint_and_sugg(
285             cx,
286             lint,
287             expr.span,
288             help,
289             "consider using",
290             suggestion,
291             Applicability::MachineApplicable,
292         );
293     }
294 }
295
296 // TODO: Lint expressions of the form `x.exp() - y` where y > 1
297 // and suggest usage of `x.exp_m1() - (y - 1)` instead
298 fn check_expm1(cx: &LateContext<'_>, expr: &Expr<'_>) {
299     if_chain! {
300         if let ExprKind::Binary(Spanned { node: BinOpKind::Sub, .. }, ref lhs, ref rhs) = expr.kind;
301         if cx.tables().expr_ty(lhs).is_floating_point();
302         if let Some((value, _)) = constant(cx, cx.tables(), rhs);
303         if F32(1.0) == value || F64(1.0) == value;
304         if let ExprKind::MethodCall(ref path, _, ref method_args, _) = lhs.kind;
305         if cx.tables().expr_ty(&method_args[0]).is_floating_point();
306         if path.ident.name.as_str() == "exp";
307         then {
308             span_lint_and_sugg(
309                 cx,
310                 IMPRECISE_FLOPS,
311                 expr.span,
312                 "(e.pow(x) - 1) can be computed more accurately",
313                 "consider using",
314                 format!(
315                     "{}.exp_m1()",
316                     Sugg::hir(cx, &method_args[0], "..")
317                 ),
318                 Applicability::MachineApplicable,
319             );
320         }
321     }
322 }
323
324 fn is_float_mul_expr<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<(&'a Expr<'a>, &'a Expr<'a>)> {
325     if_chain! {
326         if let ExprKind::Binary(Spanned { node: BinOpKind::Mul, .. }, ref lhs, ref rhs) = &expr.kind;
327         if cx.tables().expr_ty(lhs).is_floating_point();
328         if cx.tables().expr_ty(rhs).is_floating_point();
329         then {
330             return Some((lhs, rhs));
331         }
332     }
333
334     None
335 }
336
337 // TODO: Fix rust-lang/rust-clippy#4735
338 fn check_mul_add(cx: &LateContext<'_>, expr: &Expr<'_>) {
339     if let ExprKind::Binary(
340         Spanned {
341             node: BinOpKind::Add, ..
342         },
343         lhs,
344         rhs,
345     ) = &expr.kind
346     {
347         let (recv, arg1, arg2) = if let Some((inner_lhs, inner_rhs)) = is_float_mul_expr(cx, lhs) {
348             (inner_lhs, inner_rhs, rhs)
349         } else if let Some((inner_lhs, inner_rhs)) = is_float_mul_expr(cx, rhs) {
350             (inner_lhs, inner_rhs, lhs)
351         } else {
352             return;
353         };
354
355         span_lint_and_sugg(
356             cx,
357             SUBOPTIMAL_FLOPS,
358             expr.span,
359             "multiply and add expressions can be calculated more efficiently and accurately",
360             "consider using",
361             format!(
362                 "{}.mul_add({}, {})",
363                 prepare_receiver_sugg(cx, recv),
364                 Sugg::hir(cx, arg1, ".."),
365                 Sugg::hir(cx, arg2, ".."),
366             ),
367             Applicability::MachineApplicable,
368         );
369     }
370 }
371
372 /// Returns true iff expr is an expression which tests whether or not
373 /// test is positive or an expression which tests whether or not test
374 /// is nonnegative.
375 /// Used for check-custom-abs function below
376 fn is_testing_positive(cx: &LateContext<'_>, expr: &Expr<'_>, test: &Expr<'_>) -> bool {
377     if let ExprKind::Binary(Spanned { node: op, .. }, left, right) = expr.kind {
378         match op {
379             BinOpKind::Gt | BinOpKind::Ge => is_zero(cx, right) && are_exprs_equal(cx, left, test),
380             BinOpKind::Lt | BinOpKind::Le => is_zero(cx, left) && are_exprs_equal(cx, right, test),
381             _ => false,
382         }
383     } else {
384         false
385     }
386 }
387
388 /// See [`is_testing_positive`]
389 fn is_testing_negative(cx: &LateContext<'_>, expr: &Expr<'_>, test: &Expr<'_>) -> bool {
390     if let ExprKind::Binary(Spanned { node: op, .. }, left, right) = expr.kind {
391         match op {
392             BinOpKind::Gt | BinOpKind::Ge => is_zero(cx, left) && are_exprs_equal(cx, right, test),
393             BinOpKind::Lt | BinOpKind::Le => is_zero(cx, right) && are_exprs_equal(cx, left, test),
394             _ => false,
395         }
396     } else {
397         false
398     }
399 }
400
401 fn are_exprs_equal(cx: &LateContext<'_>, expr1: &Expr<'_>, expr2: &Expr<'_>) -> bool {
402     SpanlessEq::new(cx).ignore_fn().eq_expr(expr1, expr2)
403 }
404
405 /// Returns true iff expr is some zero literal
406 fn is_zero(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
407     match constant_simple(cx, cx.tables(), expr) {
408         Some(Constant::Int(i)) => i == 0,
409         Some(Constant::F32(f)) => f == 0.0,
410         Some(Constant::F64(f)) => f == 0.0,
411         _ => false,
412     }
413 }
414
415 /// If the two expressions are negations of each other, then it returns
416 /// a tuple, in which the first element is true iff expr1 is the
417 /// positive expressions, and the second element is the positive
418 /// one of the two expressions
419 /// If the two expressions are not negations of each other, then it
420 /// returns None.
421 fn are_negated<'a>(cx: &LateContext<'_>, expr1: &'a Expr<'a>, expr2: &'a Expr<'a>) -> Option<(bool, &'a Expr<'a>)> {
422     if let ExprKind::Unary(UnOp::UnNeg, expr1_negated) = &expr1.kind {
423         if are_exprs_equal(cx, expr1_negated, expr2) {
424             return Some((false, expr2));
425         }
426     }
427     if let ExprKind::Unary(UnOp::UnNeg, expr2_negated) = &expr2.kind {
428         if are_exprs_equal(cx, expr1, expr2_negated) {
429             return Some((true, expr1));
430         }
431     }
432     None
433 }
434
435 fn check_custom_abs(cx: &LateContext<'_>, expr: &Expr<'_>) {
436     if_chain! {
437         if let Some((cond, body, Some(else_body))) = higher::if_block(&expr);
438         if let ExprKind::Block(block, _) = body.kind;
439         if block.stmts.is_empty();
440         if let Some(if_body_expr) = block.expr;
441         if let ExprKind::Block(else_block, _) = else_body.kind;
442         if else_block.stmts.is_empty();
443         if let Some(else_body_expr) = else_block.expr;
444         if let Some((if_expr_positive, body)) = are_negated(cx, if_body_expr, else_body_expr);
445         then {
446             let positive_abs_sugg = (
447                 "manual implementation of `abs` method",
448                 format!("{}.abs()", Sugg::hir(cx, body, "..")),
449             );
450             let negative_abs_sugg = (
451                 "manual implementation of negation of `abs` method",
452                 format!("-{}.abs()", Sugg::hir(cx, body, "..")),
453             );
454             let sugg = if is_testing_positive(cx, cond, body) {
455                 if if_expr_positive {
456                     positive_abs_sugg
457                 } else {
458                     negative_abs_sugg
459                 }
460             } else if is_testing_negative(cx, cond, body) {
461                 if if_expr_positive {
462                     negative_abs_sugg
463                 } else {
464                     positive_abs_sugg
465                 }
466             } else {
467                 return;
468             };
469             span_lint_and_sugg(
470                 cx,
471                 SUBOPTIMAL_FLOPS,
472                 expr.span,
473                 sugg.0,
474                 "try",
475                 sugg.1,
476                 Applicability::MachineApplicable,
477             );
478         }
479     }
480 }
481
482 impl<'tcx> LateLintPass<'tcx> for FloatingPointArithmetic {
483     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
484         if let ExprKind::MethodCall(ref path, _, args, _) = &expr.kind {
485             let recv_ty = cx.tables().expr_ty(&args[0]);
486
487             if recv_ty.is_floating_point() {
488                 match &*path.ident.name.as_str() {
489                     "ln" => check_ln1p(cx, expr, args),
490                     "log" => check_log_base(cx, expr, args),
491                     "powf" => check_powf(cx, expr, args),
492                     _ => {},
493                 }
494             }
495         } else {
496             check_expm1(cx, expr);
497             check_mul_add(cx, expr);
498             check_custom_abs(cx, expr);
499         }
500     }
501 }